Home / PHP / JpGraph Error Can’t access PHP_SELF, PHP global variable

JpGraph Error Can’t access PHP_SELF, PHP global variable

One of the sites I work on uses JpGraph to generate graphs for their reports. A few months ago we moved the site from an old server with PHP 4 to a new server with PHP 5 and started getting the error “JpGraph Error: Can’t access PHP_SELF, PHP global variable”. This post looks at the error and a couple of possible solutions to it.

The error message

Instead of generating the requested graph, JpGraph instead displays an image as follows, containing the error message “JpGraph Error: Can’t access PHP_SELF, PHP global variable. You can’t run PHP from command line if you want to use the ‘auto’ naming of cache or image files.”

JpGraph Error Can

We were running this from a web browser and not from the command line so the error message seemed a little odd. However it was clear that the functions are trying to access the PHP_SELF variable in some way that isn’t defined.

Reason for the error

A quick dig through the source and I found that it’s an old version of JpGraph designed for PHP 4. In several places in the jpgraph.php file were references to PHP_SELF using the old HTTP_SERVER_VARS array like so:

 global $HTTP_SERVER_VARS;

 if( $aCacheName=='auto' )
     $aCacheName=basename($HTTP_SERVER_VARS['PHP_SELF']);

How to resolve the error

There are two versions of JpGraph currently maintained, one for PHP 4 and one for PHP 5. You can download either of these from the JpGraph download page.

I figured grabbing the PHP 5 version might end up taking a while to test and make sure everything was working correctly so instead made a minor change to the jpgraph.php file by adding the following to the top of the script:

$HTTP_SERVER_VARS = array(
 'PHP_SELF' => $_SERVER['PHP_SELF']
);

Each function call does “global $HTTP_SERVER_VARS” so even though this array won’t have gobal scope in PHP 5 it will still be available to all the functions that use it.

The alternative hack to the file would be to replace all the instances of $HTTP_SERVER_VARS with $_SERVER. The following example shows the earlier example changed to be like this.

 if( $aCacheName=='auto' )
     $aCacheName=basename($_SERVER['PHP_SELF']);

Conclusion

The “JpGraph Error: Can’t access PHP_SELF, PHP global variable” error is caused by the use of $HTTP_SERVER_VARS when running the scripts under PHP 5, a global array which has been deprecated and is no longer available in PHP 5 unless you enable the long arrays in the PHP config. The solution is to get the PHP 5 version of the library or apply one of the “hacks” I have supplied in the above examples.