PHP skips function call output

66 Views Asked by At

I have the following problem

require('drawchart.php');

if ( file_exists('drawchart.php')){ cwrapper();}

command using the 'chart.png' from cwrapper;

The cwrapper is a function inside the drawchart.php that accesses a MySQL and draws a Chart. This function works perfectly fine on its own and in a test.php but it stops producing the chart in my main program and I am baffled as to why it just won't work there.

I have tried introducing a sleep(30) to see if it needs to wait for the file to be written in order to succeed. But that doesn't help either. The 2nd command following just never picks up the output file chart.png. Directories are absolute paths in both cases so that's not a problem.

It does pick up an existing chart.png there but just not the updated one that should be generated from the if call. It seems to be skipping this call to cwrapper.

The cwrapper is using pchart to draw the chart And it does that perfectly on its own in a testscript.

How do I solve this problem? Is there a better way to achieve this?

1

There are 1 best solutions below

3
On

First of all, make sure the cwrapper() function is invoked.

Because you don't provide the path of drawchart.php, if it doesn't exist in the current directory, require() searches it in the paths specified in include_path in php.ini (it can be changed during the runtime).

file_exist() is not that lucky, it can find the file only if it exists in the current directory.

The best way to handle this situation is to not check if the file exists (who cares about it?, let require() handle it) but to check if the function you want to call exists:

require 'drawchart.php';

if (function_exists('cwrapper')) {
    cwrapper();
}

In fact, because require terminates the script if the file cannot be loaded, you don't even need to check if the function exists. If it is defined in the required file then it exists after the require() statement returns (or the script is aborted otherwise).

Your code should be as simple as:

require 'drawchart.php';

cwrapper();