Suppress echo from PHP include file - php

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

Related

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

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();

How to know if a script was included inside another script

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();

Open file from a php document, and close it from another?

I am trying to do the following:
Open a file, say "myfile.json" from a php- let's call it "utils.php"; Use it in other php pages; close it from another php.
I have tried to include "utils.php" in the other files and write in the utils file, but it does not seem to work. I suppose this happens because utils.php is never actually executed, only included, but if I should execute it, how can I do it without having to refresh any page, preferably right when the user gets on the main page? This should not be seen by the user, what he sees should remain the main page.
Thanks in advance, I am quite new to php, and am trying to learn.
When you include a file, you are running all code inside it. The functions and classes will not be evaluated but will be defined for future use. If you open your file as this example:
util.php
<?php
$file_hand = fopen('/tmp/file.txt','r');
You will have a handle if the operation is completed. However, the variable $file_hand is global. If you need to use a function to close it, you will need the following code to do it:
other.php
function close_file(){
global $file_hand;
fclose($file_hand)
}
or you can pass the handle as parameter like:
function close_file($file_hand){
fclose($file_hand)
}
Doesn't matter how you will close the file. You have to make sure the variable you are using is the same created in utils.php. If you close like this:
function close_file(){
fclose($file_hand)
}
The variable you've created in until.php file is different of this one.

Using require_once inside a method

From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)
It will only include when the method is called, but have you looked at autoloading?
1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.
I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..
As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.

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