简体   繁体   中英

PHP to download file not working with spaces

I am trying to write a script to check if a file exists or not. If the file exists, start download of file.

$get_file = $_GET['file'];
$file_raw = '/var/www/data.xxxx.com/html/' . $get_file;
$file = str_replace(' ', '\\ ', $file_raw);;

if (!file_exists($file)) { // file does not exist
    die('file not found - ' . $file);
} else {
    if (file_exists($file)) {
        $fileName = basename($file);
        $fileSize = filesize($file);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . $fileSize);
        header("Content-Disposition: attachment; filename=" . $fileName);

        // Output file.
        passthru("cat $file");
        exit();
    } else {
        die('The provided file path is not valid.');
    }
}

The issue I am encountering is if the $_GET request contains a space, I get a file not found. This is why I implemented the str_replace but this also does not help.

You don't need to escape the spaces when you call file_exists() . So use

if (!file_exists($file_raw))

When you use the shell, such as with passthru() , you should use escapeshellarg() to escape any special characters in the argument. Don't try to do it yourself with str_replace() , since there are other special characters beside spaces.

$safe_file = escapeshellarg($file_raw);
passthru("cat $safe_file");

However, it's not necessary to use passthru() in the first place. PHP has a function readfile() that copies a file to the output. So just use

readfile($file_raw);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM