Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 879
Lloyd Banks Avatar asked Sep 07 '25 15:09

Lloyd Banks


2 Answers

Execute the cron job this way:

myEnvVariable=value php test.php

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

like image 164
Marek Avatar answered Sep 11 '25 05:09

Marek


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)

like image 42
Thushara Buddhika Avatar answered Sep 11 '25 05:09

Thushara Buddhika