Provide multiple mirrors if a file doesn't exist

I want a Mirror script which determines whether or not a certain file is accessible or not. If the mirror1 is accessible, it will present the link to mirror 1. If mirror 1 is not accessible, it will present the link to mirror 2.

This so far is perfect, however I would like more mirrors. For example, if mirror 2 is unavailable, mirror 3 will be presented. If mirror 3 is unavailable, mirror 4 will be presented and so on. I’m just not quite sure exactly how I could make this work. Has anyone got any suggestions that would be highly appreciated. I’ve tried quite a lot of things already!

[php]$mirror1 = “download1.exe”;
$mirror2 = “download2.exe”;
$header_response = get_headers($mirror1, 1);
if ( strpos( $header_response[0], “404” ) !== false )
{
echo ’
Download Mirror 1
';
}
else
{
echo ’
Download Mirror 2
';
}[/php]

What you’ll want to do is something similar to this:

[php]<?php
$mirrors = array(“download1.exe”,“download2.exe”,“download3.exe”);
foreach ($mirrors as $k => $url) {
$status = get_headers($url,1);
if (strpos($status[0], “404”) !== false) {
echo “<a href=”", $url, “”>Mirror “, $k+1,”";
}
}[/php]

Just add elements to the array!

Secondly, on a slightly different note, you definitely want to add this before your script:

[php]stream_context_set_default(
array(
‘http’ => array(
‘method’ => ‘HEAD’
)
)
);[/php]

The reason for this is simple: by default, get_headers performs a GET request. Yes, this means that your server will download the whole lot of the file, which is a blocking request and will take a bloody long time if your file is big.
This line changes the stream context options to use a HEAD request, where no body of the request is transferred from the original server. This quite literally means a maximum of 4kb of data from their server to your server instead of a potential gigabyte or two.

Thank you, this has been really useful. I appreciate it.

Sponsor our Newsletter | Privacy Policy | Terms of Service