Sleep() Function not doing what I think it should - php

First, correct me if i'm wrong but i'm under the assumption that when you run the Sleep() function, it pauses running the script where it is located in the script, not at the beginning. If that is true can someone tell me why the below script waits 5 seconds and then shows both echos at the same time. NOT echo the first statement on page load and then wait 5 seconds and then fire the second echo....
echo "Your account username has been updated, you will now be redirected to the home page!";
sleep(5);
echo "REDIRECT!";

In your code PHP execution will pause for 5 seconds but it will not render itself part by part. i.e. It will not show the first statement and then the second. PHP keeps all its value in output buffer and display them when its finishes execution.
What happens is, it holds the value of first echo in output buffer and then waits for 5 seconds, then is holds another echo output in output buffer and shows all at once.
What you are trying to do is a lot easier in JS.
echo "Your account username has been updated, you will now be redirected to the home page!";
echo "<script> document.setTimeout(function() { document.location('redirect.html'); }, 5000); </script>";

Related

Print Output as it is generated in PHP

Here is the pseudo code of what I am doing:
<?php
for ($x=0;$x<5;$x++)
{
$result=shell_exec("python code.py");
echo $result;
sleep(15);
}
?>
Here is the code.py pseudo code
try:
condition
print "successful"
except:
print "not successful"
What I am trying to do is, each time the python code is run print its output on the web page instantly, then initiate the sleep timer and repeat.
Instead what I am getting now is the web page stalls for a cumulative 15*5 secs, and displays output of the python code that was run 5 times in one go.
Any suggestions on how this can be done

Delay between executions - PHP

Is it possible to set a delay between 2 portion of code in PHP? I want something like this-
<?php
function firstFunc(){
echo "anything";
}
function secondFunc(){
echo "something";
}
// call first fumction
firstFunc();
// I want the script to wait for 2 seconds here, then call second function
secondFunc();
Is it possible?
If you want to delay the execution of something, you can use the sleep($seconds) function. Here's what the documentation says
Delays the program execution for the given number of seconds.
It returns zero on success and false on error.
So you can do something like:
<?php
function firstFunc(){
echo "anything";
}
function secondFunc(){
echo "something";
}
// call first function
firstFunc();
sleep(2); //Delays execution for 2 seconds.
secondFunc();
?>
Keep in mind though, PHP is a server side language. The only thing the client will receive from a PHP script(if the client has to receive anything at all) is HTML(or CSS, JS and so on). So when you run this code, the page will show nothing for 2 seconds and then output anything and something together because the delay is happening at a server level, and not on client machine. If you want a kind a delay where something is visible on the screen and then after 2 seconds anything appears, you want to use JavaScript.
Hope this helps :)
You should use function sleep(int seconds)

I don't understand PHP sleep() behavior

I have this form:
<form method="post" action="secret.php">
<label for="pw">Password: </label><input type="password" name="pw" id="pw" />
</form>
This is secret.php:
<?php
if(isset($_POST["pw"])) {
if($_POST["pw"] == "hello") {
echo("<strong>Good pw.</strong><br />");
} else {
echo("<strong>Bad pw.</strong><br />");
echo("Back");
sleep(5);
}
} else {
header("Location: /tut/first/form.php");
}
?>
What happens is that if the password is wrong, it sleeps before displaying Bad pw. When I submit the form, it sleeps 5 seconds on the form page, and then changes page and displays Bad pw. Why?
What is happening is that you are causing the PHP script to sleep. The script must complete before it sends the result back to the client (the browser).* So you are causing the script to take 5 seconds longer before it responds to the client that it wasn't a good password.
Since you are not trying to avoid a brute force situation here I would suggest something like this:
<?php
if(isset($_POST["pw"])) {
if($_POST["pw"] == "hello") {
echo("<strong>Good pw.</strong><br />");
} else {
echo("<strong>Bad pw.</strong><br />");
echo("<script type=\"text/javascript\">");
echo ("setTimeout(function() {");
echo ("window.location = form.php;"); //might need a more complete URL here
echo ("}, 5)"); //sleep for 5 seconds before redirecting
echo("</script>");
sleep(5);
}
} else {
header("Location: /tut/first/form.php");
}
?>
*The output is actually sent back as it's written in the PHP script but with buffering you don't see this making much of a difference except in headers and very large pages.
You need to look into output buffering, although from what I see, the logic is flawed.
This may help
If you want to echo something to the browser right away, try doing flush() when you want to flush the output buffer to the browser. Also, you may need to disable compression (like gzip) which can interfere with output buffering.
However with that said, you're going about this completely wrong. All that the user would have to do is open up another tab / refresh and the server will validate the login information again, so doing sleep() isn't going to have the effect you think it is.
I have actually designed something similar to this and this is what I did:
Create a database table called failed_logins and another called login_bans and both are based on IP address. Every time a user provides incorrect information, add an entry in the failed_logins table. What you want to do is tier it so that after the first login, the user is banned for 5 seconds, after the second, it goes up to 15 seconds and 3 or more within a certain period (like say 2 hours) the user is banned for 45 seconds. This is all done server-side so that there is nothing the user can do to circumvent the ban. So you will have to check their IP every time they access the page to see if their IP has been banned.
Then on the client-side display a countdown timer containing the number of seconds remaining in the ban and disable the submit button.

PHP Sleep Output before putting to sleep for next step

I am using SLEEP(). It seems the function works, but the script waits until all my sleep() functions have ran their course before the script displays any output.
Is there a way I can get output for for 1st and then it should wait and go to next ?
echo date('h:i:s') . "<br />";
//sleep for 10 seconds
sleep(10);
//start again
echo date('h:i:s'). "<br />";
//sleep for 10 seconds
sleep(10);
//start again
echo date('h:i:s');
I need output of 1st echo and then script should wait and give second echo ....and so on
Sleep Does not matter as for as output of the page is concerned. Page is served as soon as the last sleep is done... Though it stop processing of the page on server for the time of the sleep. .. in your scenario you should be using javascript for the affect.
You see, PHP runs completely on server-side, and sleep will just make the latency of the page more severe.
As Rab has suggested, try using JavaScript instead. It's not the same as Java (in fact, a lot different), and you might like to find some good tutorials online, or get some good books (the one from Murach is really good, trust me).

"No data received" error when I have a mysql query in while loop

I have this PHP code:
<?php
include_once("connect_to_mysql.php");
$max=300;
while($max--)
{
sleep(1);
doMyThings();
}
?>
it is supposed to repeat a mysql query 300 times with gap of 1 second between each. But the problem is after a minute or so in the browser i get this message: No Data Received. Unable to load the webpage because the server sent no data.
The problem is the following: Your code will at least (without considering the amount of time needed by doMyThings()) last 300 seconds. Most PHP environments set the default script running time to about 60 secs, the script stops and nothing is printed out.
Next thing is (if script execution time is set high enough to allow long running scripts), the script has to run until its finished (that is, ~300 secs) and after that, data is written onto the output stream. Until there, you won't see any output.
To circumvent those two problems, see this code:
<?php
// If allowed, unlimited script execution time
set_time_limit(0);
// End output buffering
ob_end_flush();
include_once("connect_to_mysql.php");
$max=300;
// End output buffering IE and Safari Workaround
// They will only display the webpage if it's completely loaded or
// at least 5000 bytes have been "printed".
for($i=0;$i<5000;$i++)
{
echo ' ';
}
while($max > 0)
{
sleep(1);
doMyThings();
$max--;
// Manual output buffering
ob_flush();
flush();
}
?>
Maybe this post is also of interest to you: Outputting exec() ping result progressively
The browser will not wait a whole 5 minutes for you to complete your queries.
You need to find a different solution. Consider executing the PHP script in CLI.
It seems that you have a timeout executing 300 times doMyThings();
You can try with set_time_limit(0);
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini.
When you execute long time php code on server side, you need change max_execution_time directive in php.ini. But browser will not wait how long as you want so you need use async technology like AJAX

Categories