phpunlink

PHP unlink file from root-relative path


My script is in http://localhost/path/test/index.php and the file I want to delete is in http://localhost/path/media/test.txt.

I want to have the path of the project as a constant PATH which would be path/ in this example. So I tried it with the root-relative path unlink("/" . PATH . "media/test.txt"), which didn't work.

Any ideas how to solve this path problem?


Solution

  • By putting a / at the begining of the unlink, you are telling PHP to dlete from the root of the server's file system, which is unlikely to be the same folder as your localhost (probably /var/www/)

    Ideally in web applications, you should define the root of your application in the filesystem, e.g.:

    $root = '/var/www/sites/project/';
    

    Then you can unlink like:

    unlink( $root . "media/test.txt" );
    

    Alternatively you can unlink by relative, rather than absolute path (as above:)

    unlink( '../media/test.txt' );
    

    To get your root, see: this