Quick administrative access in PHP
Posted on December 6, 2008 at 2:44 am
I recently got this all polished up, and it’s working so well I decided I had to share. This little gem allows me to completely do away with setting up a dev server to make changes on a live site, as the functionality is basically created on an as-needed basis. It’s easy, but oh so useful.
// I put this in my session class, as it's guaranteed to be called on each and every page
function is_admin() {
$ip = array(
file_get_contents('/secret/text/file.txt'),
'123.45.678.90',
);
return (in_array($_SERVER['REMOTE_ADDR'], $ip));
}
So, what does it do? Simple. It checks to see if the IP address of the computer making the request is the same as the predefined IP address it’s got in 1) the hard-coded array and 2) the /secret/text/file.txt I’ve set up elsewhere on the site. What text file? Oh, yes, almost forgot.
This function worked great for a while, but one client in particular had an IP address that changed fairly rapidly. Every other week I’d get a request to change the embedded IP, and eventually I just got sick of it. The solution was the following:
// Save as /super/secret/ip/reset.php, or whatever suits your fancy.
$ip = $_SERVER['REMOTE_ADDR'];
$filename = '/secret/text/file.txt';
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $ip) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);
header('Location: /');
die();
} else {
echo "The file $filename is not writable";
}
Now control was back in the clients’ hands. Each time their IP changes, they just click a bookmark that accesses the above script. It opens the aforementioned text file, grabs the current IP address, and writes a single line of text. This is followed immediately by a redirect to home (/), but you could just as easily have it point anywhere.
So, now the function works. How do you use it? The short answer would be “everywhere” — at least, that’s been my experience:
if (is_admin()) {
echo 'content that only admins can see';
} else {
echo 'content that everyone else sees';
}
This can be used anywhere you want to make changes to a site, but leave everything completely intact for anyone that’s not on your VIP list. I’ve managed to complete some pretty extensive modifications by simply wrapping everything I was working on in this function. Clients love it because they can see changes and know that customers aren’t seeing development in progress. As for the amount of time I’ve saved by not hassling with copying files, making changes, reuploading, renaming, etc., well, it’s safe to say that I’m never going back to the old ways.
edit 2/8/10:
For quick deployment, this can be easily memorized and typed in about ten seconds:
function is_admin() {
return ($_SERVER['REMOTE_ADDR'] == '123.45.678.90');
}