0

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?

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
AndiAna
  • 854
  • 6
  • 26

1 Answers1

0

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();
axiac
  • 68,258
  • 9
  • 99
  • 134
  • When I call a function that produces an output chart.png for example. Is there a reason why this file should be skipped or not available at the next function call which uses it? Maybe lagging in the write of the file or something like that? In the meantime I will try without the file_exists – AndiAna Sep 05 '17 at 09:42
  • You are right. I tried putting the following command inside the if statement using {}. And it didn't even reach this command. That means the if statement is assuming FALSE even though the php file exists in the same directory as the runtime php. One step closer!! Thanks – AndiAna Sep 05 '17 at 09:49
  • Now I am running it just like you say very simply without the if shebang. I will let you know. The code takes ages to complete. Thanks for all your responses. You guys are great! – AndiAna Sep 05 '17 at 09:58