简体   繁体   中英

Can't escape the '&' in a filename such that file_exists evaluates to true

This is a PHP app running in a Linux Docker container.

  • A file gets uploaded from the FE that is called "A & T.pdf".
  • The filename is saved in the database as "A & T.pdf".
  • The file is saved in Azure File Storage as "A & T.pdf".

When we go to download the file, it says ERROR: File 'A' doesn't exist . It is apparently cutting the filename off before the ampersand.

$filename = get_get('file', '0', 'string', 255);
$file=$CFG->questdir.$filename;

if (file_exists($file)) {
  ...
} else {
  echo "ERROR: File '$filename' doesn't exist";
}

I've tried a number of different things: str_replace($file, '&', '\&') , addeslashes() , urlencode() , and a few others that aren't coming to mind.

Things like this should be sanitized going on, which is being fixed.

At this point, I'm just curious how to to resolve this error as it exists?

Database has the correct name. Storage has the correct name. PHP doesn't like the ampersand. How do you properly escape it in the variable being passed to file_exists() ?

EDIT:

Tracing the steps, it looks like the filename is getting chopped off in here:

function get_get($name,$default='',$type='string',$maxlenght=0){
    if(!isset($_GET[$name])) {
        $var=$default; //Default
    } else {
        $var=trim($_GET[$name]);
        if(strlen($var)>$maxlenght) $var=substr($var,0,$maxlenght);
        settype($var,$type);
        if($type=="string" && !get_magic_quotes_gpc())  {
            $var=pg_escape_string(my_connect(), $var);
        }
    }

    return $var;
}

It looks like it is getting truncated at the $var=trim($_GET[$name]);.

My bet is that it's not actually PHP with this issue, as & is not a special character for PHP, and given the error it actually appears to be the space at issue. While space and & are not special characters in PHP, they are in a URL. So, I suspect what is happening is your URL is something like

http://www.example.org/script.php?name=A & T.pdf

This would need to be URL encoded

http://www.example.org/script.php?name=A%20%26%20T.pdf

PHP has a command you can use if you're setting up the URL with it, otherwise do some googling for online URL encoders: https://www.php.net/manual/en/function.urlencode.php

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