1

Just noticed something, but I'm not sure why this is true, or why it is different than a standard script, maybe someone can help me solve this riddle. When running a PHP script that contains a json_* function from the command line as an executable I will get a Fatal error: Call to undefined function json_encode() in /var/www/jsontest.php on line 6 with the script below

#!/usr/bin/php -n
<?php

$arr = array('foo', 'bar', 'baz');

print_r($json = json_encode($arr));
print_r(json_decode($bar));

This also happens with json_decode() when trying to decode standard clean json input (validated via jsonlint)

The above script was being run as follows, in a Linux/DEB terminal...

$ chmod +x jsontest.php
$ ./jsontest.php

By running this through my local webserver though, I receive my expect output

#!/usr/bin/php -n ["foo","bar","baz"]Array ( [0] => foo [1] => bar [2] => baz ) 

What is going on? Why is JSON not available when interpreted as an executable?

PHP version is PHP 5.5.3-1ubuntu2 (cli) (built: Oct 9 2013 14:49:24) and PHPInfo for anyone who might want it is published on my Ubuntu One Account

ehime
  • 8,025
  • 14
  • 51
  • 110

1 Answers1

4

I'm guessing that the issue here is your php.ini file - PHP uses a different ini file when running as CLI. Have a look at Explosion Pill's answer on this question:

When running php from the command line, you can use the -c or --php-ini argument to point to the php.ini file to use. This will allow you to use one php.ini file for both. You can also alias php to php -c/path/to/php.ini if you are running the script yourself.

Community
  • 1
  • 1
Ben D
  • 14,321
  • 3
  • 45
  • 59
  • Upvoted and accepted, CLI is pointing to `/etc/php5/cli/php.ini`, stack is pointing to `/etc/php5/apache2/php.ini`. Excellent answer and reference. – ehime Dec 05 '13 at 18:20
  • Actually what the issue was, was I was running it with the -n switch as you can see from the script above (`#!/usr/bin/php -n`), and as you can see from `php -h` we get.... `-n No php.ini file will be used` ;) – ehime Dec 05 '13 at 18:41