Search code examples
phpunlink

Can't Use unlink function with path defined by variable


I can't read the path by use variable

$absPath = realpath('./');
//$absPath = /home/abc/domains/server2.abc.com/public_html/mockup
//$oldPath = /project_image/easy/Desert.jpg
$npath = $absPath."".$oldPath; //$oldPath is get by image element scr="xxx"

$npath will return this:

/home/abc/domains/server2.abc.com/public_html/mockup/project_image/easy/Desert.jpg

When i unlink it

unlink($npath);

Then php return

No such file or directory in /home/../mockup/update_file.php -> point unlink($npath);

And i try to Hard Code it

$npath = /home/abc/domains/server2.abc.com/public_html/mockup/project_image/easy/Desert.jpg
unlink($npath);

Then it will success.

I want to know how to use variable combine a new path to unlink it.

Sorry for my poor English


Solution

  • Are you sure your script is producing the exact same path? If you are building the path correctly and unlink is failing, you can try the shell instead. Sometimes this works like with samba mounts and what-not.

    $absPath = realpath('./');
    $npath   = $absPath."".$oldPath;
    
    // Bail if the path doesn't exist
    if(!file_exists($npath)) die('Failed to build correct path');
    
    // Try unlink via PHP
    if(!unlink($npath) || file_exists($npath)) {
    
      // PHP couldn't cut it, try unlink via shell
      exec('rm ' . $npath, $output, $return);
      if($return > 0)
        die('Failed to delete file: ' . $npath);
    }