Prevent exit() in third-party function from exiting? - php

I'm calling several functions (which I can't edit) in sequence, but some of the functions redirect the user, so I never get to the next one.
I'm calling a third-party function which has calls to wp_redirect() which I'm able to prevent, but then the next line is exit; which I can't figure out how get around.
I was hoping to get around it with the ob_ functions, but no luck so far.
Any suggestions, hacky or otherwise, will be hugely appreciated!
edit: I have an idea I haven't tried yet - somehow spawning off new processes to perform these tasks - what would be best way to do that, waiting for each to complete before moving on.

I believe is possible to get the source code of the php interpreter ... mess with the exit function and then recompile and install on the web server your new custom version of php ...

I'm afraid you just can't. There is an option to redefind native php function, see runkit_function_redefine.
But in the comments it also says:
language constructs
(eval, die, exit, isset, unset, echo etc.) which might be confused
with functions, cannot be renamed or redefined even with
runkit.internal_override.

You may be able to use runkit_function_redefine. You'll need to make sure you can modify internal functions in your php.ini file in order to be able to change native/internal functions.
I think the php.ini setting you need to ensure is switched on is runkit.internal_override.
I've not tested this.
However, since exit is a language construct I'm not even sure it's possible to get around it even with the above function.

In the end I went with using cURL to make three synchronous requests to a file with different GET params.

Throw an exception in wp_redirect, and wrap the code with try-catch statement, then check if the exception message contains the message you have set and return the response accordingly, I have used this hack with most plugins including woocommerce, ultimatemember etc...
example:
ob_start();
try{
whatever code....
}catch(\Exception $e){
}
echo ob_get_clean();

Related

check if functions referenced inside functions exist before commands are processed - PHP

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

Monitor a PHP variable for change in value

I am actually trying to monitor a PHP variable (may be as a separate thread but not possible in PHP) and fire a PHP function whenever the value of the variable changes.
eg: lets take a variable $_GLOBALS['foo']=1;
if at any point in the code, the value of $_GLOBALS['foo'] changes to something else, i want to fire a PHP function immediately.
The variable can be anywhere inside a loop or in a function,etc.
Why i want this: I have a variable which stores the last error occured as a text. If the value of the variable changes from "" to something else, i want to trigger an error. My LOGIC may seem a bit strange but this is what i would like to do.
Thanx in advance.
Edit: I tried: How to use monitors in PHP? and How can one use multi threading in PHP applications but does not seem to solve the problem.
The Code (Thought this could solve some of your doubts on my question):
public function addtag($tagarray,$uid,$tagtype="1")
{
$dbobj=new dboperations();
$uiobj=new uifriend();
$tagid=$uiobj->randomstring(30,DB_SOCIAL,SOCIAL_TAG,tag_tagid);
$c=0;
foreach($tagarray as $tags)
{
$c++;
$tagname=$tags["tagname"];
$taguid=$tags["tagid"];
$dbobj->dbinsert("INSERT INTO ".SOCIAL_TAG." (".tag_tagid.",".tag_fuid.",".tag_tuid.",".tag_tagname.",".tag_tagtype.") VALUES
('$tagid','$uid','$taguid','$tagname','$tagtype')",DB_SOCIAL);
}
if($c==0)
{
$lasterror="No tags were added";return "";
}
else
{
return $tagid;
}
}
Here, if i call a error handling function instead of monitoring the variable, it wont be advisable in my case since the error handling function may do any operation like give alert and redirect to a page or any similar operation.
I asked this question cause, i thought what if the script does not reach the line
return "";
It would affect the project's workflow. Thats what i am worried about.
And the variable i was talking about is $lasterror and i have many functions like this where $lasterror is used.
I saw this, so I built this:
https://github.com/leedavis81/vent
Should solve your problem.
There is no built-in way to do this in PHP, and there's no easy way to add it. It doesn't really feel right for the way the language works anyway.
Instead of setting a variable, you could build a custom function that handles the error - or use PHP's built-in error handling functionality using a custom error handler.
Another error handling method which comes close to what you want to do (I think) is exceptions.

Suppress echo from PHP include file

I have a file PHP01.php which:
- performs a function
- creates an array
- echo's some message
I need to include this file in another php script, say PHP02.php as I need access to the array it created. But when I jquery POST request to PHP02.php, the data it returns also has the echo from PHP01.php
How can I suppress the echo from the first file?
You can output buffer it if editing or otherwise restructuring is not possible:
ob_start();
include "PHP02.php";
ob_end_clean();
If you can, you should look at refactoring the code in the original PHP file. If it's performing a function, it should do that. Then, the code that called the function should decide if they want to echo a message.
As you've just learned, this is an important part of orthogonal design. I'd recommend re-writing it so that it performs what you want it to, and let the code that calls the function, decide what they want to output. That way you won't have to worry about these things again.
You can also look into using output buffers. See ob_flush in PHP: http://php.net/manual/en/function.ob-flush.php
Try adding a conditional to PHP01.php that checks to see where it is being called from, this will ensure that you only echo it out if the file making the call is PHP01.php
Additionally it is better if you place functions in their own file to be included if needed so as to keep certain features that are present from being included for example in PHP01.php you can add include 'function01.php'; and it will have that function shared across the two files.
create a new function without the echo

Print the executed PHP code (Path of code taken)

I have a script with alot of nested includes and functions calling each other from lots of if conditions. Basically, its a coding nightmare.
Is there any way i can "PRINT" the PHP code executed ? I mean, print the actual flow of the code and the path taken by the script from start to end ?
PHP can't do this out of the box. You'd need to install the xDebug extension on your PHP development machine. Once installed, you could use the code coverage function to determine which lines have executed.
Lacking that, I'd create a simple debug function to include at the top of your code
public function myDebugString($string)
{
file_put_contents('/tmp/debug.log',"$string\n",FILE_APPEND);
return;
}
and then add calls to this throughout you code
myDebugString('Called at ' . __LINE__);
And then tail the log file created. Removing the debug statements is a simple find/replace operation for your editor once you're done.
Many frameworks have debugging objects that do way more than this built it, but if you're dealing with stand alone code something simple like this should be enough to get you by.
You can try debug_backtrace() or debug_print_backtrace().
Additionally, I recommend using Xdebug. It prints a very useful stack trace on exceptions (you can configure it to print out every method parameter and every local variable (xdebug.collect_params=4 and xdebug.show_local_vars=on configuration parameters).
Take a look at code coverage tools. This allows you to identify those functions and lines of code that are actually executed when a script runs

So Echo isn't echoing

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.

Categories