Web Hosting Talk







View Full Version : Does this script look okay?


Looie
12-22-2007, 01:49 PM
I only started with PHP a bit ago, I don't know much, but I had an idea and just wanted to see if it would work

<?php

// Mirror server
$mirror = 'http://www.mirrorserver.com/';

// Files directory
$dir = 'x71';

// Where to get the current server load
$getLoad = '/proc/loadavg';

//Where to get the mirror server's load
$getLoad2 = 'load.php';

// Gets the name of the file requested
$file = $_GET['file'];

// Checks to make sure the request is valid, and stops executing code if it isn't
if ( strstr($file, '/') || empty($file) || !strstr($file, '.') )
exit;

// Gets the server load for the current server
$handle = fopen($getLoad, 'r');
$load = fread($handle, '5');

// Gets the server load for the mirror server
$handle = fopen($mirror. $getLoad2, 'r');
$load2 =fread($handle, '5');

// Checks to see if the mirror server has a lower load and redirects if it does
if ($load > $load2)
header('location: ' . $mirror . '?file=' . $file);

// Gets the proper location of the file
$newfile = '/filesystem/path/to/file/' . $dir . '/' . $file;

// Checks to see if the file exists, and redirects if it does
if ( file_exists($newfile) )
header('location: /' . $dir . '/' . $file);
else
echo 'Error.';

?>

Can anyone tell me if there's a problem, what it is, and how it can be fixed. Also, is it secure?

Steve_Arm
12-22-2007, 03:34 PM
IT will take less time to let the page load, whatever the load, than doing remote fopen and checking the load. Does the servers allow remote fopens?

Codelphious
12-22-2007, 08:09 PM
Just FYI it's good practice to die() or exit() after sending redirect headers.

servergoods
12-23-2007, 09:52 PM
i think it is ok, i like to use {} , anyway it all on your own favorite

futhey
12-24-2007, 02:20 AM
Neat idea. I haven't tested your code, but it looks functional.

Gave me an idea for writing a php based load balancing system :)

ZackN
12-24-2007, 05:28 AM
Have you considered doing something like weighted random numbers to pick the server?


$randomNumber = mt_rand(0,100);
if($randomNumber <= 40) {
$server = 1;
} else if($randomNumber <= 100) {
$server = 2;
}
Weight it based on the specs/traffic of the servers. If only two servers are involved there's no need for the second if. I've never tried anything like this, but it should work fine.