【问题标题】:How can I get my environment variable from the shell to PHP for Sendgrid API?如何将环境变量从 shell 获取到 PHP for Sendgrid API?
【发布时间】:2016-11-10 03:20:00
【问题描述】:

这是使用 sendgrid 发送电子邮件的代码。据我所知,我已尝试关注directions。我的代码似乎在getev($apiKey); 失败,它没有返回任何内容,因此出现未经授权的访问错误。我怎样才能让它工作?

<?php

    error_reporting(E_ALL);
    require_once ('../vendor/autoload.php');
    $from = new SendGrid\Email("name","blah@blah.com");
    $subject = "First Test Email Hello World from the SendGrid PHP Library!";
    $to = new SendGrid\Email("another name","blah@gmail.com");
    $content = new SendGrid\Content("text/html", "<h1>Hello, Email!</h1>");
    $mail = new SendGrid\Mail($from, $subject, $to, $content);

    $apiKey = getenv('SENDGRID_API_KEY');
    echo "please work";
    echo "API KEY: " . $apiKey . "<br>";      //return nothing :(
    $sg = new \SendGrid($apiKey);

    $response = $sg->client->mail()->send()->post($mail);
    echo $response->statusCode();
    echo $response->headers();
    echo $response->body();


?>

我在根文件夹中运行了这些,甚至使用了export -p,其中列出了SENDGRID_API_KEY,并已设置为我的API 密钥。

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

我怎样才能让getenv($apiKey); 工作?

【问题讨论】:

  • 为什么不将 API 密钥存储在配置文件中并从那里引用它?

标签: php sendgrid


【解决方案1】:

关于环境变量是什么以及它们如何工作的指南应该澄清一些事情:http://www.codecoffee.com/tipsforlinux/articles/030.html

您需要使用该变量配置您的环境(服务器、shell 等)。它不是来自文件。您可以通过putenv 在 PHP 中临时执行此操作,但变量不会保留。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多