Reputation: 5451
I wanted to redirect user to a remote server after processing is done on my server. Sometimes, because of network connection timeout in user's end, the redirection isn't happening which causes his/her page to not get updated status.
What I currently use is
header('Location: http://anotherwebsite.com');
If this fails, it will not try again... how can I implement something that 'will try again'
$retry_limit = 0;
while(//http status code not 301 or 302 && $retry_limit < 3)
{
header('Location: http://anotherwebsite.com');
$retry_limit++;
}
I'm confused if I use cURL then it will double redirect if I also implement header... or maybe I misunderstood it?
Thanks a lot!
Upvotes: 1
Views: 2457
Reputation: 7830
As has been pointed out, header()
will just fire a HTTP header and forget, so with PHP you won't be able to easily implement a retry mechanism.
But what is the underlying problem that you are trying to fix? If the partner website that you are redirecting to is so overloaded that it will sometimes only react on the 2nd or 3rd attempt: seriously, you should make that server work more reliably.
On the other hand, if you are simply looking for a way to notice a possible downtime of the other server and inform your users accordingly, you could add a quick server-to-server check to your code. In case the other server is down, you can redirect to a different page and apologise or offer a retry link.
Look at this answer for a way to ping a server to find out if it is up or not.
A rough solution could look like this:
<?php
$url = 'http://anotherwebsite.com';
if(pingDomain($url) != -1) {
header('Location: ' . $url);
} else {
header('Location: sorry_retry_later.html');
}
// Ping function, see
// https://tournasdimitrios1.wordpress.com/2010/10/15/check-your-server-status-a-basic-ping-with-php/
function pingDomain($domain){
$starttime = microtime(true);
$file = fsockopen ($domain, 80, $errno, $errstr, 10);
$stoptime = microtime(true);
$status = 0;
if (!$file) $status = -1; // Site is down
else {
fclose($file);
$status = ($stoptime - $starttime) * 1000;
$status = floor($status);
}
return $status;
}
Upvotes: 1
Reputation: 2310
header
can be only used for one-time redirects. Since there is no return value, you can't check it this way. You should first try with JSON to check if there is a response from the site, if so, redirect the user, else write an error message or something.
I haven't used this personally, but have seen others do it successfully with this method.
Upvotes: 0