Search code examples
phpspacesunlink

unlink not working with space in foldername path


I read a few threats on escaping but doesn't work. it works with a path without spaces fine.... ($subfolder contains spaces)

 $subfolder = "this a subf";
$filepath = "/var/www/domain/$subfolder/$imagetodelete";
$filepath = str_replace(" ", "\ ", $filepath);
unlink($filepath); // correct if $subfolder/path contains no spaces
echo $filepath;

Solution

  • $filepath = str_replace(" ", "\ ", $filepath);
    

    The problem here is that you are escaping the space character in PHP, not actually inserting a backslash. In order to actually mean a backslash, you have to escape a backslash, like so:

    $filepath = str_replace(" ", "\\ ", $filepath);