我怎么能得到我的环境变量从shell到PHP的Sendgrid API


How can I get my environment variable from the shell to PHP for Sendgrid API?

这是使用sendgrid发送电子邮件的代码。我已尽我所知按照指示去做了。似乎我的代码在没有返回任何东西的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);工作?

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

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