Hi... Just wanted to float a PHP script I wrote - and see if there are any suggestions for improvement.
Coming from a Windows background, but currently purchasing Linux based hosting (for monitary reasons, and that nice price tag on MySQL databases vs. MSSQL in a hosted environment) I have certain expectations for the web. One is that URLs are case insensitive. After searching for some time on how to make Apache case-insensitive (didn't realize right away it was a file-system thing) I decided to write a 404.php script that helped fake case-insensitive URLs. (BTW - if someone else has done this, please point me toward it. Thanks.)
Anywho, this is a script that basically takes the URL that caused the 404 error using the
Code:
$_SERVER['REDIRECT_URL']
and massaging it to find the requested file in a case-insensitive search (and then redirecting to that if necessary.
Please keep in mind I started learning PHP yesterday. Any improvements on the code would be appreciated.
Code:
<?php
// The deal is to get the requested bad page,
// do a search for a matching page in any case,
// and redirect to it.
// Get the offending page
$badURL = $_SERVER['REDIRECT_URL'];
// Get rid of the first slash
$badURL = substr($badURL, 1, strlen($badURL) - 1);
// Get rid of any trailing slash
if (substr($badURL, strlen($badURL) - 1, 1) == '/')
$badURL = substr($badURL, 0, strlen($badURL) - 1);
// Split the URL into an array
$badList = explode('/', $badURL);
// Create an array
$top = count($badList);
// Get the current base directory
$currentDir = getcwd();
// We want to store a variable that will be the actual path
// to the found file, if we in fact find a file.
$desiredPath = '/';
// Loop
for ($i = 0; $i < $top; $i += 1)
{
// If it's less, then we are in a folder
if ($i < $top - 1)
{
// We want to get all the folders in $currentDir
// using the opendir function
$dir_handle = @opendir($currentDir) or die("Unable to open $currentDir");
// Get the current index
while ($folder = readdir($dir_handle))
{
// Make sure it's a Folder and it's a match
if (is_dir($folder) && strcasecmp($folder, $badList[$i]) == 0)
{
// It's a match. Append the real folder to
// the $desiredPath variable
$desiredPath .= $folder . '/';
$currentDir .= '/' . $folder;
break;
}
}
// Close the open directory
closedir($dir_handle);
}
else
{
// Look for the matching file or folder (if it's a request without a
// specific file) in $currentDir
$dir_handle = @opendir($currentDir);
// Do the file loop
while ($fileOrFolder = readdir($dir_handle))
{
// See if it's a match
if (strcasecmp($fileOrFolder, $badList[$i]) == 0)
{
// Ladies and Gentlemen, we have a match
$desiredPath .= $fileOrFolder;
closeDir($dir_handle);
header("Location: $desiredPath");
}
}
// We're not gonna find it. Close
// the file handle.
closeDir($dir_handle);
}
}
// If we get to this point, we're boned.
?>
404 Error Text Here if no redirect.
Thanks for your help/comments!
Dave