Search code examples
phpjqueryapachejquery-file-uploadblueimp

PHP ReadFile Issues with Spaces


Got a bit of a PHP problem I am stuck on at the moment. I have a file called download.php which gives secure access to file downloads which are stored in a private folder on the server. i.e. 1 level above httpd.

The code looks like this.

        $Document = new Documents($DID);

        $file = $Document->getfilewithdir();

        header("Content-Description: File Transfer");
        header("Content-length: " . $Document->getfilesize());
        header("Content-type: " . $Document->getfiletype());
        header("Pragma: public");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-disposition: attachment; filename=\"" . basename($Document->getfilename()) . "\"");

        readfile($file);
        exit;

Where

$Document->getfilewithdir() returns something like /Applications/MAMP/htdocs/Portal_QCNW/private/portal_files/filename.docx

and

$Document->getfilename() returns something like filename.docx.

Extra code included:

    function setfilename($Val)
    {
        $this->c_Filename = $Val;
    }

    function getfilename()
    {
        return $this->c_Filename;
    }

    function getfilewithdir()
    {
        $path_parts = pathinfo($this->geturl());
        $file_name  = $path_parts['basename'];

        return FILELOC . $file_name;
    }

This is all fine if there file name has no spaces in, but if there are spaces in the file name i.e. file name.docx or filename (1).docx then the readfile statement returns "failed to open stream". What can I do to get round this and deal with spaces in filenames?

I use https://blueimp.github.io/jQuery-File-Upload/ to upload the file, and there could be something there were I remove spaces at the upload stage.

Any thoughts and advice would be great.

Kind Regards

James


Solution

  • Thanks for your help. I reviewed the code and simplified it. Because I was passing a URL file name it was been formatted as a url rather than a string.

    All sorted now.

    James