通过PHP下载文件[关闭]

I'm trying to initiate a file download through PHP. It downloads, however, the file can't be opened. My path is correct because I did a test through previewing the image via the image tags in HTML.

    $findPage = mysql_query("SELECT * FROM pages WHERE page_id = '$pageId' LIMIT 1");
    $pg = mysql_fetch_array($findPage);

    $fullPath = $pg['page_link'];
    $explode = explode(".", $fullPath);

    $ext = $explode[count($explode)-1];

    header('Content-disposition: attachment; filename="Name.'.$ext.'"');
    header('Content-type: image/'.$ext);
    readfile($fullPath);

What do you get if you try the following:

$fullPath = 'https://www.google.co.uk/images/srpr/logo3w.png';

list($w,$h,$t) = getimagesize($fullPath);  
$mimetype = image_type_to_mime_type($t);
$extension = end(explode('.', $fullPath));

header('Content-disposition: attachment; filename="Name.'.$extension.'"');
header('Content-type: '.$mimetype);
readfile($fullPath);

You should get Google's logo downloading... I do on my local set-up.

*(this code will require fopen_wrappers enabled on your server)*

If you do get Google's logo downloading correctly then I would suggest it's either a problem with the data being served from your db, or a permissions problem when readfile tries to access and read your file.

file_exists( $fullPath ) /// will tell you if the file exists or not

is_readable( $fullPath ) /// could be useful to detect a read error

If you don't get Google's logo then either fopen_wrappers are disabled on your server or something odd is going on elsewhere in your code.

extra notes

Where is $pageId being set? If it is being passed into your script from the outside world - as in through a URL - I would insist that you use a different way of building your database query. At the very least you should be running some kind of escaping function on the $pageId value before you insert it to your query. Otherwise it's quite a security problem. This is because anyone who has access to your URL can obviously modify it, and by doing so they can directly modify your query. The quickest way you can protect your database when dealing with simple IDs is to make sure the value is a number.

$pageId = (int) $pageId;