PHP clean_all_processes() giving 500 internal error, but still outputs - php

So my PHP file is meant to check if a variable is null, if so than echo and output, and stop there
Here is that code:
if(is_null($ip)){
echo "IP is not valid";
clean_all_processes();
}
So when I try to test this script using the insomnia rest client it outputs the "IP is not valid" but also gives a "500 internal server error"
In my error_log file it spits out this every time
Uncaught Error: Call to undefined function clean_all_processes()
Note: I am using php 7.3

There is no such function called clean_all_processes() in PHP. The answer you linked to used it as an example name of a function you could call.
If you want a hard stop of your script use die(). This is not recommended! You should structure your code in such a way that you should almost never need to use this approach.
There is no way to break out of if statement, because such thing makes no sense. An if statement is already a condition. You either execute the code or don't.

Related

PHP - Should I add the die() function at the end of every php script? [duplicate]

In a php script I have some test and after the script the html page.
When a test fail i call die("Test 1 failed");
If no test fail the php script reach the end ?> and then load the html code after the php script.
Is this a good procedure? Or I need to write die() or exit() before the end of php script?
No you don't have to write that and this is not best practice. If the script reaches the end without fatal errros it will exit.
If this means "testing" for you, you're wrong. Testing should be done using unit tests. For php there is phpunit. Give it a try, that's the proper way of testing your code.
Edit: As CompuChip says in a comment, the only useful use case for exit is when you're writing a php based shell script that should return an error code. See the parameter section of the documentation for the exit() function.
You should never be using die() or exit in your production PHP scripts except in very specific cases. Instead, re-work your code paths to simply show an error message to the user rather than exiting the script early.
No you don't need that, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way. That's when you use exit() or die()
Is the die() or exit() function needed in the end of a php script?
No, PHP will end the script itself. If the script is an included file (called from another file) then it will end script in the included file and then continue with any code in the original file after where you included (if there is any code).
So you put die() or exit() where ever you want or need it.
For testing, put it after each block of code you test. I use them in some parts of testing if I just want PHP to show me something then stop, such as print out an array to make sure it's being constructed correctly etc.
eg:
print_r($array);
exit();
For other code tests, I sometimes just echo "Section A worked", etc, such as within if/else. If I want to know if a particular part of code is working or if some criteria is being met or not (basically, it lets you trace where PHP itself is going within your code).
All that said, don't use die() or exit() in production code. You should use a more friendly and controlled messaging setup. For security reasons and visual, as you could potentially give them some info like "ERROR Failed to load SomethingSecret". Also it doesn't look pretty when you page only half loads and then puts out an on screen error message which likely means nothing to the end user.
Have a read through this:
PHP Error handling: die() Vs trigger_error() Vs throw Exception
No !
This is not recommanded to use it
Use trigger_error or error_log to log the tests in your error.log. Then check it.
No you don't have to use these functions at the end of the script, because it exists anyway at the end of the script.
No need to put a die or an exit at the end of the scipt.
But you may use exit to terminate your script with a specific exit code (by default it's 0).
E.g
$ php -r "/* does nothing */;"
$ echo $?
0
$ php -r "exit(123);"
$ echo $?
123
http://php.net/exit
From the documentation:
The link to the server will be closed as soon as the execution of the
script ends, unless it's closed earlier by explicitly calling
mysql_close().
https://secure.php.net/function.mysql-connect
Nope, you don't need to call die() or exit(0 if you have another code to run, like you HTML code

Error include functions.php

I have 2 pages :
functions.php
function get_test($name) {
return 'Yo '.$name.' !';
}
test.php
include('http://www.exemple.com/functions.php');
echo get_test(Thomas);
When I execute my script on the server :
Fatal error: Call to undefined function get_test() in /htdocs/test.php on line 5
Note: I don't use Wordpress
Thanks
Don't do this:
include('http://www.exemple.com/functions.php');
It causes PHP to issue a full-blown HTTP request to your own server, causing Apache to EXECUTE that script, and return its output. That means you're not getting PHP code. You're getting the OUTPUT of that php code, which is not likely to be valid PHP code.
include/require via HTTP is almost always a sign of bad design, and also a major security vulnerability, if you're include/requiring from an actual remote url. Nothing says that the remote url can't return something like <?php system('rm -rf /'); ?>, which your server will then happily start executing.
Almost certainly you only need something like this:
include('functions.php');

ReferenceError, Function not Defined

I am very new to php and I tried to write this function. Now it seems like the function is not Defined. Nothing happens when I open the php file and if I try to use console to run it. It gives an error --
contentcheck('ex1.php','Bajestani')
ReferenceError: contentcheck is not defined
The Code is below.
<?php
if(contentcheck('ex1.php','Bajestani')===true)
echo 'Got it';
function contentcheck($filename,$phrase)
{
$content = shell_exec('C:\xampp\htdocs\docman\pdftotext '.$filename.' -');
if (strpos($content,$phrase) !== false)
{
return true;
}
else
return false;
}
if(contentcheck('ex1.php','Bajestani')===true)
echo 'Got it';
?>
Thanks In advance
You state that you try to run the function from the console.
In addition, ReferenceError: contentcheck is not defined is a Javascript error, not a PHP error.
Both of these facts lead me to the conclusion that you are trying to run the PHP code from inside the browser.
Please note that PHP code is not available from within the browser -- the function will indeed be undefined if you run it in the console, because PHP is run on the web server, not in the browser. The browser will never see your PHP functions; it simply sees the output of the PHP program (eg the HTML code, etc that is printed from by your PHP program). The PHP code itself is never seen by the browser.
It's not entirely clear what your program is supposed to be doing but what is clear is that the way you're trying to run it is not going to work. You're going to have to re-think this one completely, and possibly learn a bit more about how client/server systems work, and PHP in particular.

eval() and PHP errors

I have a eval function like this
if(FALSE === #eval($code)) echo 'your code has php errors';
So if the code has synthax errors it will return that message.
The problem is that if within the code you have something like:
require_once('missing_file.php');
it will just break the page, without my nice error message :(
Is there any workaround for this?
Well, first I hope that $code comes from a trusted source and that you're executing arbitrary code sent by the users.
Second, the only way I see you can workaround that is to save $code into a file, run it with the command line PHP interpreter, and check the exit value. Note that passing this test doesn't make $code fatal error free, it just so happened that this particular execution of the script did not throw any fatal error; there may be other code paths that trigger such an error.
This is because once eval triggers a fatal error, it can't be recovered and the script dies. eval only returns FALSE if there is a parsing error.

Fatal error php

Is there a way to make the code continue (not exit) when you get a fatal error in PHP?
For example I get a timeout fatal error and I want whenever it happens to skip this task and the continue with others.
In this case the script exits.
There is a hack using output buffering that will let you log certain fatal errors, but there's no way to continue a script after a fatal error occurs - that's what makes it fatal!
If your script is timing out you can use set_time_limit() to give it more time to execute.
"Fatal Error", as it's name indicates, is Fatal : it stop the execution of the script / program.
If you are using PHP to generate web pages and get a Fatal error related to max_execution_time which, by defaults, equals 30 seconds, you are certainly doing something that really takes too mych time : users won't probably wait for so long to get the page.
If you are using PHP to do some heavy calculations, not in a webpage (but via CLI, or a cron, or stuff like that), you can set another (greater) value for max_execution_time.
You have two ways of doing that :
First is to modify php.ini, to set this value (it's already in the file ; just edit the property's value). Problem is it'll modify it also for the web server, which is bad (this is a security measure, after all).
Better way is to create a copy of php.ini, called, for instance, phpcli.ini, and modify this file. Then, use it when invoking php :
php -c phpcli.ini myscript.php
This'll work great if you have many properties you need to configure for CLI execution. (Like memory_limit, which often has to be set to a higher value for long-running batches)
The other way is to define a different value for max_execution_time when you invoke php, like this :
php -d max_execution_time=60 myscript.php
This is great if you launch this via the crontab, for instance.
It depends on the exact error type. You can catch errors by creating your own error handler. See the documentation on set_error_handler(), but not all types of errors can be caught. Look at the timeout error you get and see what type it is. If it is one of E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR or E_COMPILE_WARNING then you cannot catch it with an error handler. If it another type then you can. Catch it with the error handler and simply return.
If you have a suitable PHP version (PHP>=5.2 for error_get_last) you can try the technique described here which uses register_shutdown_function and error_get_last.
This won't allow you to "continue" when you get a fatal error, but it at least allows you to log the error (and perhaps send a warning email) before displaying a custom error page to the user.
It works something like this:
function fatalErrorHandler()
{
$lastError = error_get_last();
if (isset($lastError["type"]) && $lastError["type"]==E_ERROR) {
// do something with the fatal error
}
}
...
register_shutdown_function('fatalErrorHandler');
A few points:
you can use ob_clean() to remove any content that was generated prior to the fatal error.
it's a really bad idea to do anything to intensive in the shutdown handler, this technique is about graceful failure rather than recovery.
whatever you do, don't try to log the error to a database ... what if it was a database timeout that caused the fatal error?
for some reason I've had problems getting this technique to work 100% of the time when developing in Windows using WAMP.
The most simple answer I can give you is this function: http://php.net/manual/en/function.pcntl-fork.php
In more detail, what you can do is:
Fork the part of the process you think might or might not cause a fatal error (i.e. the bulk of your code)
The script that forks the process should be a very simple script.
For example this is something that I would do with a job queue that I have:
<?php
// ... load stuff regarding the job queue
while ($job = $queue->getJob()) {
$pid = pcntl_fork();
switch ($pid) {
case -1:
echo "Fork failed";
break;
case 0:
// do your stuff here
echo "Child finished working";
break;
default:
echo "Waiting for child...";
pcntl_wait($status);
// check the status using other pcntl* functions if you want
break;
}
}
Is there a way then to limit the execution time of an function but not all script?
For example
function blabla()
{
return "yes";
}
to make it so that if it is not executed in 25 seconds to return no;

Categories