I would like to make my PHP script freeze at a screen for at least 5 seconds before loading into the next script. I have tried "Sleep()" however that is not the function I am looking for as it only pause the script that is "going" to be loaded.
Here are my codes:
echo "Welcome ",$_SESSION['username']."<br>";
echo "Click here to Logout : ".'<br>Logout';
sleep(10);
header("Location: http://192.168.11.32/phploginserver/test.php");
echo '<script type="text/javascript">window.location="test.php"</script>';
}
I would like the echo'to another page' to be delayed for at least 5 seconds before loaded so that my users can view their user name before being automatically redirected to the next page.
$time = new DateTime();
$newtime = $time->Modify("+5 seconds");
while($newtime > (new DateTime()))
{
// Do nothing
}
You cannot freeze PHP script at a screen.
Just because there are no PHP scripts at screen. But merely HTML, rendered by browser.
Such a freezing considered bad practice and don't used nowadays.
Either show a message, if it's really important, or get user to the destination immediately (preferred).
You can use some AJAX-powered tips, as stackoverflow does.
so that my users can view their user name
Don't they know it already?
Can't they see it on the next page?
What if a user got disturbed and do not notice that message?
You can use an additional parameter with the php header to delay it. Like this:
header('Refresh: 10; url=http://192.168.11.32/phploginserver/test.php');
Related
This may seem like a simple thing but I just can't get my head around it. How do I use php to display a div on a website at a specific time for only a duration? Eg. Show object for 10min every hr.
Ok, I have an object ie ahajsjajshaksjaksjiajsns which is displayed on a website when visitors visit the site. But I don't want it to show all the time but say every hr. And to disappear from the website after 10min.
if(date("i") < 10) echo "...";
This code will echo ... every hour from minute 0 to minute 9. e.g. 8.00-8.09, 9.00-9.09, 10.00-10.09, ...
PHPs date function is able to give you values you can check against a specific date. For more information see the docs.
I haven't coded anything web in a few years, so forgive me if I'm rusty but:
You can't do this all serverside. The page will compile but unless the user refreshes the page, the object in question will be forever available.
What you want to do, is use kekub's example to generate the following code only if it's within the time range, but also include JavaScript to destroy it when time is up:
$time = date("i");
if($time < 10){
$timeToExpire = 10 - $time;
echo "<div id="yourObject">I will expire soon!</div>;
echo"<script type = 'text/javascript'>setTimeout(function() {
$('#yourObject').fadeOut('fast');
}, ".$timeToExpire * 10000.");</script>"; // * milliseconds e.g 6 minutes
}
I haven't tested it but what should happen is, the webpage will generate the div and also the code needed to hide it when the time is up (say there is only 6 minutes left to show it).
Although I think personally you should do this all in Javascript.
you can set time for two divs using setTimeout and can call divs in that function
setTimeout(function(){page2(mintime)},10000);
setTimeout(function(){page1(mintime)},10000);
This kind of function usually should not be done in server side. Anyway if you want to achieve this using PHP you can have something like this:
while (true) {
$result = yourfunction;
if (resultIsGood) {
break;
}
sleep(3);
}
You can sleep in a loop
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.
Well, i was trying to reach a solution and i thought this might work:
On the PHP file:
$liguem = getdate();
$liguemoff = $_COOKIE['liguemoff'];
$liguemon = $_COOKIE['liguemon'];
if(empty($liguemoff)){
setcookie('liguemoff',$liguem[0],time() + (50000));
}
setcookie('liguemon',$liguem[0],time() + (20000));
$body->assign("COOKIE2", $liguemoff);
$body->assign("COOKIE3", $liguemon);
This has some body assign because I'm working with XTemplate, but the PHP is just PHP.
Now on the index file, some JavaScript:
var cookie2 = {COOKIE2};
var cookie3 = {COOKIE3};
if( cookie3-cookie2 > 60){
alert('alerta');
};
Truth is that it works! People might not be navigating, but it is what i want, the pop up will only open after the visitor sees at least 2 pages (Server-side thing).
The main problem is, that i CAN'T make the function popup(); to trigger where i have the ALERT displaying. The ALERT is working alright though.... Any hints?
PS:
This is the popthat(); function:
function popthat(){
$("#darkside").css('opacity','0.3').fadeIn('slow');
$("#darkside").click(function () {
$(this).css('opacity','1').fadeIn('fast');
$("#liguem").hide();
});
$("#liguem").corner();
$("#liguem").hide();
$("#liguem").delay(200).css('visibility','visible');
$("#liguem").fadeIn('fast');
}
You can set a timeout to display your popup after a specified amount of time. This amount of time can be dicated by your PHP since the server-side code will be able to track the amount of time on the site through page-views. This way the popup can display after 60 seconds on the site even if the user is not navigating to another page.
Something like:
setTimeout(popthat, <?php echo $_COOKIE[...]; ?>);
Your PHP would echo the number of milliseconds until the popup should display.
A note: when you replace your alert() with the popthat() function the DOM may not be ready and popthat() won't be able to work because it won't find any elements that match your selectors. Try running your code on document.ready ($(function() {});).
Browsers automatically block popups initialized on page load, because nobody likes these sorts of popups.
When you do an alert(), execution of your script stops. alert() is a blocking function, and nothing will happen until it has moved on.
I don't know if you just made a typo, but your function is called popthat(), and in your statement you said you called the function popup(). You need to change popup(); to popthat(); for this to work, unless as I said that was a mistake.
Every 4 seconds I am refreshing a php page and it updates the time.
Each time this happens I want to send the time to another page but NOT navigate away from the page
that is refreshing the time...
Below is some sample code:
<?
$target = mktime(10, 0, 0, 0, 0, 0) ;
header('refresh:4; url=timer.php');
$today = (int)(time ());
$siteToReceiveTime = "http://www.nbit.co.za/toriggo/receive.php?time=$today";
print "time in $today seconds";
?>
There are a couple of ways that you could do this...
Ajax being one - that could handle the every 4 seconds bit and would be able to make requests without changing the page.
The other option would be with php curl...
Read the CURL function documentation. You can have PHP call CURL to load the page for you from the PHP script without interfering with your users.
file_get_contents("http://www.nbit.co.za/toriggo/receive.php?time=$today");
I have a javascript setInterval that checks an external page every 5 seconds for mail, I am finding sometimes that if I login or click a form submit at the same time as the request goes out, I sometimes find myself looking at a Y or a N (what my JS was to intercept) instead of the real link I wanted to go to.
How does one debug this? I am using firefox with firebug, my app is using PHP with javascript.
EDIT: it's almost as if the onComplete is being missed by java, and it just dumps it as the user is signing in.... it only happens when someone is changing pages and the java is running at the same time.
EDIT 2: If you want to see this for yourself, you'll need visit my site and create an account and go through the signup process (2-3 mins to do tops), the website is http://mikesandmegs.com and the beta password is goldfish. What you want to do is login just as the check mail sends its request off. Its like I need to cancel something or tell java to throw the callback out or something. You should see the requests every 5 seconds, (well it adds 5 seconds each request) but you'll see. It may take a couple try's or some luck, but it is reproducible.
This is the javascript that is running (i think I have it all posted) If I seem to be missing anything, let me know. I also posted an htnl input html that the javascript checks...
<input id="hasMail" type="hidden" value="y">
<script type='text/javascript'>
mailTimer = setInterval("checkMail();", 10000);
function checkMail()
{
// should we check the mail now?
if ($('hasMail').value == "y")
{
// remove mail new mail alert (mail-check.php returns y or n
new Ajax.Request('mail-check.php',
{
method: 'post',
postBody: '',
onComplete: checkMailNotify
});
}
}
function checkMailNotify(req)
{
if (req.responseText.length > 5)
{
$('hasMail').value = "n";
clearInterval (mailTimer);
return;
}
if (req.responseText == "y")
{
$('hasMail').value = "n";
$('topMessage').update('You have new mail...');
$('alertBox').appear();
clearInterval (mailTimer);
}
else
{
clearInterval (mailTimer);
mailInterval = mailInterval + 5000;
mailTimer = setInterval("checkMail();", mailInterval);
}
}
</script>
I know this is nowhere near a solution, but it WILL help to increase the 5 second interval, even to something like 30 seconds. I've done work with mailservers before, and we often came across problems where people would have e.g their iphone as well as their desktop mail client ping the server at very short intervals. This would result in confusing (to them) failures because of locks.
So yeah, 5 seconds for messages is very quick (it doesn't look like chat but rather just messages, is that right?). At best if you do that then the problem will happen a lot less if it all. You will however have the horrible knowledge that it can happen.
Please don't take this as an attempt at a solution to your problem. just a suggestion.
I think what's happening is that while changing pages, the data from the mail-check.php is clashing with the new request that is coming back from the network at the same time. I think a possible solution is to disable the setInterval whenever you change a page or submit a form, then re-enable it after loading the new data.
Something like:
<input type="button" onClick="clearInterval('mailTimer'); this.submit()" />
...