如何将我的环境变量从shell获取到PHP for Sendgrid API?

时间:2016-11-10 03:20:00

标签: php sendgrid

这是使用sendgrid发送电子邮件的代码。据我所知,我曾尝试过directions。好像我的代码在getev($apiKey);失败了,它没有返回任何内容,因此出现了Unauthorized Access错误。我怎样才能让它发挥作用?

<?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);工作?

1 个答案:

答案 0 :(得分:0)

有关环境变量及其工作原理的指南应澄清一些事项:http://www.codecoffee.com/tipsforlinux/articles/030.html

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