Question mark on filename using fopen

2019-07-18 19:05发布

问题:

I am having a problem saving a file using fopen. For some reason the saved file has a question mark in the end.

I am attempting to retrieve a list of files from a remote server and download them to my server. This is the part of my code that does the job :

$arrlength = count($reports);
for ($x = 0; $x < $arrlength; ++$x) {
    $report = $reports[$x];
    $thefilepath = returnfilename($report);
    echo 'the filepath : '.$thefilepath;
    echo '<br>';
    $thefilename = basename($thefilepath).PHP_EOL;
    echo 'the filename : '.$thefilename;
    echo '<br>';
    $localfile = 'incoming/'.$thefilename;
    echo 'local file to save : '.$localfile;
    echo '<br>';
    curl_setopt($ch, CURLOPT_URL, $thefilepath);
    $out = curl_exec($ch);
    $fp = fopen($localfile, 'w');
    fwrite($fp, $out);
    fclose($fp);
}

This script returns the following (I've hidden the actual addresses - retain the spaces etc):

the filepath : https://example.com.com/xxx/xxx.xlsx
the filename : xxx.xlsx 
local file to save : incoming/xxx.xlsx 

When on my server I do a ls I get :

-rw-r--r-- 1 www-data www-data 29408 May 17 23:01 xxx.xlsx?

There is nothing wrong with the file, when I remove the ? I can retrieve it as normal and open it. What is this? And how can I do it so it is not added in the end?

回答1:

The string you're using to name the file has a non-printable character at the end, and ls is telling you that there is something there, even if you would normally be unable to see it. Strip the character from the string before using it.