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?
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();
Related
Some time ago, I developed a PHP script to send text messages, log sms usage, and so on. This is working fine.
Now I have modified it so that it may be included within another script via "include" or "require." Again it is working fine but I would like to make it operate slightly differently if "included" versus the command-line call. For example, if it's called from command line, then the parameters are in $argv, but if included in some function, we can assume certain necessary variables have already been set up, SQL connections are established, etc.
The point where I'm stuck, is trying to determine if this code is "include"d or is the main file. I know I can use get_included_files() to retrieve the necessary list. But at present (assuming my script is /path/myscript) the only test I know to use is something like:
$includes = get_included_files() ;
$isMainScript = ($includes[0] == '/path/myscript') ;
And therefore $isMainScript will be true if this was called from the command line. But clearly this is bad form; all one has to do to break it, is to rename the included script, or move it to some other directory. But I don't see any method of finding out the name of this file (/path/myscript) ... only the name of the main file (__FILE__ and its workalikes).
What do others do in order to determine if this script is a main script, or is subordinate to some other?
I modified about 600 lines of code amongst over 5000 lines of code by updating function calls to match the new library I created for use with the script. I have spot some errors manually when updating before by hand, but I believe I overlooked some.
So far, the only way I can spot them is to run the code and have it crash when the error happens. This is a bad idea because such errors will happen before resources are freed.
Here's an example in code that explains my question:
Say I have mainline code (called index.php) that consists of this:
<?php
include "library.php";
$file=fopen("afile","w");
doWrite($file);
brokenFunction();
fclose($file);
exit();
?>
and say library.php contains only this:
<?php
function doWrite($file){
fwrite($file,"Test");
doNothing();
}
?>
Because brokenFunction(); and doNothing(); don't exist, an error is expected. Rather than PHP compile then execute code up until the first failing function call, how do I have PHP check to see if all referenced functions the mainline code links to exist before executing code?
So in my example, I expect an error and the code to stop compiling/executing at $file=fopen("afile","w"); because brokenFunction(); and doNothing(); don't exist.
How do I achieve this?
You can use the built-in function_exists() function:
if (!function_exists('brokenFunction')) {
throw new \Exception('brokenFunction is missing');
}
But this will only raise an error when executing the code.
Some tools like PHPStorm can check your code (without running it) and throw warnings if a function is missing.
Some other tools are listed in this (closed) SO question: Is there a static code analyzer [like Lint] for PHP files?.
The best way I've found to globally debug an environment without using #A.L's method and pasting a function_exists call before every edited line, is to use a PHP debugger of some sort, most likely built into an IDE that compares every function call line against a 'test compile' of your code and all included libraries to make sure the called function exists (and would likely underline it in red if it didn't). A PHP IDE like Aptana might be what you're looking for (especially if you see yourself having future updates to run as this solution will have the time overhead of installing/setting up Aptana).
I am new to PHP and very likely I am using the incorrect approach because I am not used to think like a PHP programmer.
I have some files that include other files as dependencies, these files need to have global code that will be executed if $_POST contains certain values, something like this
if (isset($_POST["SomeValue"]))
{
/* code goes here */
}
All the files will contain this code section, each one it's own code of course.
The problem is that since the files can be included in another one of these files, then the code section I describe is executed in every included file, even when I post trhough AJAX and explicitly use the URL of the script I want to POST to.
I tried using the $_SERVER array to try and guess which script was used for the post request, and even though it worked because it was the right script, it was the same script for every included file.
Question is:
Is there a way to know if the file was included into another file so I can test for that and skip the code that only execute if $_POST contains the required values?
Note: The files are generated using a python script which itself uses a c library that scans a database for it's tables and constraints, the c library is mine as well as the python script, they work very well and if there is a fix for a single file, obviously it only needs to be performed to the python script.
I tell the reader (potential answerer) about this because I think it makes it clear that I don't need a solution that works over the already existant files, because they can be re-generated.
From the sounds of it you could make some improvements on your code structure to completely avoid this problem. However, with the information given a simple flag variable should do the trick:
if (!isset($postCodeExecuted) && isset($_POST["SomeValue"]))
{
/* code goes here */
$postCodeExecuted = true;
}
This variable will be set in the global namespace and therefore it will be available from everywhere.
I solved the problem by doing this
$caller = str_replace($_SERVER["DOCUMENT_ROOT"], "", __FILE__);
if ($_SERVER["REQUEST_METHOD"] === "POST" and $caller === $_SERVER["PHP_SELF"])
performThisAction();
I want to write a script that creates a PHP file with some definitions (define(..., ...);) and then within this script i want to run more commands that uses the definitions i just defined in the newly created php file. for this to work i am guessing i could do something like that :
create file (say def.php) and write definitions to it
require_once 'def.php';
run commands that uses definitions from def.php
will this work? if not what is the right way of doing it?
It will work, you can use it but if the file does not exist then it will call exit() in the middle of your page so you will get a half loaded page with an error message.
I think the eval() or anonymous functions (closures) should be better.
http://www.php.net/manual/en/function.eval.php
http://php.net/manual/en/functions.anonymous.php
So I've got all of this really neato PHP code and I've started doing some reuse with functions out of necessity. I'm debugging, trying to figure out why I can't delete comments on my website while I'm deleting folder (because who wants orphaned comments?)
So I have a call to deletefolder( $parent) inside a file called deletefolder.php. This a function that will recursively traverse my tree structure.
I've include another file inside deletefolder.php. The file is call helpers.php, and it contains the deletefolder function.
The deletefolder function calls deletecomments (kills all the comments per file) and delete file (which kills the file itself).
Now, all of it is just slathered with echo statements to help me figure out what's going on. When I call this combination of functions from other locations I don't seem to have a problem getting messages. But when I call them from the deletefolder.php page I don't get any. Does anybody know why this would be the case?
A few things you might want to verify.
Check the source of the output. You might be echoing straight in a middle of a HTML comment or a tag which is hiding the output.
Are you using output buffering (ob_start()) ? You might be clearing the buffer at some point in your code and forgot all about it.
Different files with the same name but not in the same directory. Do a die() in your function to make sure it actually reaches your code. You might be editing/including a copy of your file (happened to me quite a few times).
Well, I seriously doubt you've found a bug in the echo command, so the problem is with your program logic somewhere. Without seeing your code, it's impossible to say really. Perhaps there's some variable being set or unset unexpectedly, or you're not actually include()ing the files properly.