Pregunta

Essentially, what I am doing is intercepting a 404 using ErrorDocument in .htaccess, and pointing it at getFile.php. getFile then grabs the file name out of the url and searches for it in the mysql database, getting the data and applying appropriate headers.

In my dev environment (up-to-date LAMP server running under ubuntu) everything seems to work fine, but the site is being hosted on GoDaddy, and there seems to be some issue with the headers returned. I think GoDaddy returns a 404, then sends the data anyway.

The result is when I right click on a link that is to be handled in this manner, I can 'Save As', and everything works fine. If the file is an image, it opens no problem. But if I just click the link and it is a file that is to be downloaded rather than viewed in a browser, I get 'File Not Found' errors, across all browsers. Firebug Console claims it is a 404 error, regardless of whether the file successfully transfers. My code is the following:

$folder = explode( "/" , $_SERVER["REQUEST_URI"] );
$pageName = $folder[sizeof($folder)-1];

$sql = "SELECT data, mimeType, OCTET_LENGTH(data) AS size FROM tblFiles WHERE fileName = '".$pageName."' AND active=1;";

$result = mysql_query("$sql") or die();

$data = mysql_fetch_array($result);

header("HTTP/1.0 200 OK");
header("Content-Type: ".$data['mimeType']);
header("Content-Length: ".$data['size']);

echo $data['data'];

And the .htaccess file:

ErrorDocument 404 /FILES/dbFiles/getFile.php

Now this is the full .htaccess file present at /FILES/dbFiles. I don't know if GoDaddy is expecting more stuff in there, but it seems to work just as written on my own server.

I've tried numerous combinations of header info with no positive effect.

My code apparently works, but I can't seem to prevent that 404 from happening.

Thanks! -Jer

¿Fue útil?

Solución

Try this in your /FILES/dbFiles/.htaccess file (without the ErrorDocument part):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ getFile.php?file=$0 [QSA,L]

This will direct all non-existing URLs to your getFile.php script without generating a 404. Make sure you do output a 404 if the script does not find the content in your database.

Inside your PHP file, use:

if(@$_GET['file']) {

    //Your code here.  Use $_GET['file'] instead of $_SERVER["REQUEST_URI"]

} else {
    //Weird.  This file was directly accessed.
    die();
}

Otros consejos

Oh man, nice solution. My situation was this: I was streaming javascript content from another directory when a requested .js file didn't exist, and while the actual content of the javascript was returning just fine the status was 404.

For my purposes this is what helped, hopefully it helps others too:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) route/index.php [L,QSA]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top