How to open a file with special characters in the name
In PHP, how can I open a file with special characters in the name?
Name looks like iPad | -5542fa5501f31.log
In another forum, I've tried:
$logid = str_replace(" ", "\x20", $_GET['logid']);
$logid = str_replace("|", "\x7C", $logid);
To massage the name, but that doesn't work for me either.
I've already tried:
$dst_file = escapeshellarg($dst_file);
And, of course, it started simply:
$logid = $_GET['logid'];
The source file was generated by a PHP script on Linux system. I am confused why a PHP script can write a filename like this, but cannot open it for reading.
Here is my current code:
$logid = str_replace(" ", "\x20", $_GET['logid']);
$logid = str_replace("|", "\x7C", $logid);
$logdate = str_replace("-", "/", $_GET['date'])."/";
$dst_file = $uploads_dir.$logdate.$logid.'.log';
// read the data from the log file
echo "<pre>\n";
if (file_exists($dst_file)) {
$file_handle = fopen($dst_file, "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
if (strlen($line) < 3) continue;
echo $line;
}
fclose($file_handle);
} else {
echo $dst_file." does not exist\n";
}
echo "</pre>\n";
source to share
Someone on another forum suggested using popen, so I tried this and it works:
$logid = $_GET['logid'];
$logdate = str_replace("-", "/", $_GET['date'])."/";
$dst_file = escapeshellarg($uploads_dir.$logdate.$logid.'.log');
echo "<pre>\n";
$handle = popen("cat ".$dst_file, 'r');
while(!feof($handle)) {
$line = fgets($handle);
if (strlen($line) > 3) {
echo $line;
}
ob_flush();
flush();
}
pclose($handle);
echo "</pre>\n";
The exact same code, other than using fopen / fclose (no cat), will not work.
source to share
I tried to open the file "2017-09-19_Comisión_Ambiental.jpg" which "ó" was giving me this error:
file_get_contents ... failed to open stream: no such file or directory in ...
So I used utf8_decode in the filename and it worked:
$data = file_get_contents( utf8_decode( $filename ) );
I know this is an old question, there is even an accepted answer, I just posted it because it might help someone.
source to share