简体   繁体   中英

Access a file within a folder with spaces in the name in PHP

I would like to open a file inside a folder in PHP. The problem is that the folder that contains the file may have spaces in the name. The code I use to open the file (and doesn't work) is the following:

$myFile = "path/to the/file.txt";
$myFile = str_replace(' ', '\ ', $myFile);
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

As you can see, I'm trying to solve the problem by putting a \\ in front of the space, but this doesn't solve the issue. I still receive the following error:

Warning: fopen(path/to\ the/file.txt) [function.fopen]: failed to open stream: No such file or directory in /path/to/my/website on line 49

Any idea on how to solve this issue?

Thanks!

Backslashes are used to escape spaces on the command line , because spaces on the command line are argument separators. There's no such problem in PHP. If you give any string to fopen , it expects that this one string is one path. It does not break the path into separate arguments at the spaces because that makes no sense in this context.

Therefore, just don't add any backslashes. The path path/to\\ the/file.txt is not the same as the path path/to the/file.txt .

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