Search code examples
phpunlink

unlink() doesn't work with absolute path


I'm working on a method which delete pictures using unlink(). However I can't find a way to make it work using absolute path.

Here is my code :

$img = $_SERVER['DOCUMENT_ROOT'].'/i/koala.png';
unlink($img);

Error :

Warning: unlink(/var/www/html/i/koala.png): No such file or directory in /var/www/html/king/test.php on line 15

Any help?


Solution

  • When you cobble together various strings to make a path, you should use realpath to verify it and convert any relative fragments like /../.

    http://php.net/manual/en/function.realpath.php

    $path = $_SERVER['DOCUMENT_ROOT'].'/i/koala.png';
    $img = realpath($path);
    

    $img will either be false, or a string of a valid path!