user3008755
user3008755

Reputation:

PHP readfile error

I am getting an error. I am trying to read an attachment. It does work perfectly on most files but on few I get this error. The files have the same format and the location it is trying to read from is correct. I have tested it on windows explorer. This is way i am reading it:

        header('Content-Description: File Transfer'); 
        header('Content-Type: application/octet-stream'); 
        header('Content-Disposition: attachment; filename="' . $filename .'"'); 
        header('Content-Transfer-Encoding: binary'); 
        header('Expires: 0'); 
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
        header('Pragma: public'); 
        header('Content-Length: ' . filesize($attachment_location)); 
        ob_clean(); 
        flush(); 
        readfile($attachment_location);     
        exit();  

This is the error I get

Warning: readfile(C:\Users\Public\asdgasd\4sf3\Suppliers\saf342\Files\Revit\2016\Seinätikas.rfa): failed to open stream: No such file or directory in C:\xampp\htdocs\web\downloadattachment.php on line 58

Upvotes: 2

Views: 4095

Answers (3)

damianopetrungaro
damianopetrungaro

Reputation: 96

You should put a checker for see if the file exists in your filesystem.

if (!file_exists($filePath)) {

    // Throw an exception or do something for alert the wrong path.
    throw new Exception('File with this path is not available.');

} else {

    // Do your amazing stuff here

}

Upvotes: 1

Martin
Martin

Reputation: 22760

as Johndodo kind of references, you need to ensure that PHP is operating with the correct internal character set and encoding, so that it recognises the way the file is stored in your (windows) directory structure. See what character set your windows system is using and then use that same character set for PHP internal encoding.

Edit:

Logic process would be to:

  • Open file reference from email and convert the filename $var into the correct encoding.
  • Do the file_exists check
  • Proceed to pass the $var to the readfile function to open.

Upvotes: 1

Florian
Florian

Reputation: 875

could you please provide the content of $filename and $attachment_location.

Could you please extend your code with this:

if (file_exists($file)) {
 Your code goes here
 ....
 exit();
}

Further things to check: Is the file readable by the webserver user (if you're using a websever). Does the problem have an effect on files in which there are special chars in the filename ?

Upvotes: 0

Related Questions