Windows to Linux Site Move; Dealing with 404 Errors and Case Sensitivity in PHP

Windows servers are not case sensitive.

Linux servers are. Files and directories must be exact case.

So when you move a website from a Windows server to a Linux server, you're probably going to have some 404 errors. Today I rolled the best solution possible. This would be applicable to moving a PHP site from a Windows to Linux server.

This little snippet will search your users request using PHP and compares alphabetic case! Then it sends people to the correctly cased request. When making links on a Windows server they don't have to be as exact as they have to be in Linux. You can make a link to Windows Servers.doc, using the format wInDoWs sErVeR.dOc and a Windows server will find it. Not on a Linux server though, each variation in case in the filename represents a separate file, and there are no spaces allowed. This PHP snip addresses files and directories that have been moved to live on a Linux server, where variations of the HTML links cause 404 errors. As far as making HTML links to work on Linux, "

If you already have a (php) 404 document, you can just add this in. If you don't, you should make one so your users don't get lost or leave your site. Either way, put this at the top of of the file:

<?php
$mydir
=getdir("/",$_SERVER['REQUEST_URI']);
if(
$mydir!=false)
{
   
$thedomain = 'http://' . $_SERVER['SERVER_NAME'];
   
header("HTTP/1.1 301 Moved Permanently");
   
header( 'Location: ' . $thedomain.$mydir );
}
function
getdir($loc,$tfile)
{
   
$startloc=$_SERVER['DOCUMENT_ROOT'];
    if (
file_exists($startloc.$loc) && $handle = opendir($startloc.$loc))
    {
        while (
false !== ($file = readdir($handle)))
        {
            if (
$file != "." && $file != ".." && strncasecmp($loc.$file,$tfile,strlen($loc.$file))==0)
            {
                if(
strncasecmp($loc.$file,$tfile,strlen($tfile))==0)
                {
                    return
$loc.$file;
                }
                else
                {
                    return
getdir($loc.$file."/",$tfile);
                }
            }
        }
       
closedir($handle);
    }
    return
false;
}
?>

If they've requested something that actually doesn't exist, you can include the contents of your 404 page below the closing php tag complete with a 404 message.

Make sure to specify the 404 document in your .htaccess file with the line:

ErrorDocument 404 /notfound.php

That's it! Save yourself a day going through code and fixing all the links, and going through files and directories renaming stuff!

Category: