简体   繁体   中英

How to open file with special characters in the name

In PHP, how can I open a file that has special characters in the name?

The name is similar to iPad|-5542fa5501f31.log

Per 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 also already tried:

$dst_file = escapeshellarg($dst_file);

And of course started out with just straight:

$logid = $_GET['logid'];

The initial file was created by a PHP script on a Linux system. I'm confused why a PHP script can write a file name like that, but can't open it for reading.

Here's 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";

The only thing I found was to rename the file then open. The problem is no PHP functions so I tried system commands. None worked. The ftp RNTO command will rename it. But it would be much better to filter out "special characters" when the file is saved.

Somebody on another forum had 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, except using fopen/fclose (no cat) will not work.

I was struggling to open the file "2017-09-19_Comisión_Ambiental.jpg", that "ó" was giving me this error :

file_get_contents ... failed to open stream: No such file or directory in ...

So I used utf8_decode on the filename and it worked :

$data = file_get_contents( utf8_decode( $filename ) );

I know this is an old question, there's even an accepted answer, I just posted it because it might help somebody.

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