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

3
  • 1
    What does "php -ni | grep json" give you? Commented Dec 5, 2013 at 18:03
  • Try doing phpinfo() on both environments and make sure that you are using the same version of PHP and php.ini files. It's possible that you have the extension loaded in one ini file and not the other. Commented Dec 5, 2013 at 18:05
  • @JesperBunnyJensen empty string Commented Dec 5, 2013 at 18:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.