Lloyd Banks
Lloyd Banks

Reputation: 36659

PHP - Environment Variables Not Available When Script Called From Cron Job / Command Line

My test.php file looks like:

<?php

echo $_SERVER["myEnvVariable"];
echo getenv("myEnvVariable");

The above will return my set environment variable twice. It works when the script is called from outside the server.

If I call the same script on the server using the command line command:

php test.php

or using a cronjob

****** curl http://localhost/test.php

nothing is returned.

How do I make available my environment variables within the server itself? I am setting my environment variables within the Apache httpd.conf file.

Upvotes: 4

Views: 4246

Answers (4)

Thushara Buddhika
Thushara Buddhika

Reputation: 1820

If you are having lots of environment variables try this,

Export env entries to a file

env >> /etc/environment

Add the CRON job with crontab -e

5,35 * * * * . /etc/environment; /usr/local/bin/php /srv/app/artisan schedule:run >> /dev/null 2>&1

CRON: Running php scheduler at 05, 35 of each hour with source of all the environment variables. (replace with your command)

Upvotes: 3

Marcel Kohls
Marcel Kohls

Reputation: 1892

I suggest you to make a special curl call to your file. Something like this:

test.php (this is your file, no changes here)

specialcurl.php:

<?php
    $curl = curl_init('http://www.youraddresshere.com/pathtofile/test.php');
    curl_setopt($curl, CURLOPT_FAILONERROR, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($curl);
    echo $result;
    curl_close($curl);
?>

Now, run with php command the specialcurl.php script from the server as:

php specialcurl.php

The point here is to call your test.php as a valid user calling your server. It works for me.

Upvotes: 2

Marek
Marek

Reputation: 7433

Execute the cron job this way:

myEnvVariable=value php test.php

Variable will be available from getenv("myEnvVariable"), not in $_SERVER.

Upvotes: 3

violator667
violator667

Reputation: 499

Try setting wget to http://address.domain/test.php in cron. I know this isn't solution but might help.

Upvotes: 1

Related Questions