How to use Unlink() function

给你一囗甜甜゛ 提交于 2019-12-09 14:57:50

问题


I'm trying to use PHP unlink() function to delete away the specific document in the folder. That particular folder has already been assigned to full rights to the IIS user.

Code:

$Path = './doc/stuffs/sample.docx';
if (unlink($Path)) {    
    echo "success";
} else {
    echo "fail";    
}

It keep return fail. The sample.docx does reside on that particular path. Kindly advise.


回答1:


I found this information in the comments of the function unlink()

Under Windows System and Apache, denied access to file is an usual error to unlink file. To delete file you must to change the file's owner. An example:

chown($tempDirectory . '/' . $fileName, 666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody" 
unlink($tempDirectory . '/' . $fileName); 

So try something like this:

$path = './doc/stuffs/sample.docx';

chown($path, 666);

if (unlink($path)) {
    echo 'success';
} else {
    echo 'fail';
}

EDIT 1

Try to use this in the path:

$path = '.'
         . DIRECTORY_SEPARATOR . 'doc'
         . DIRECTORY_SEPARATOR . 'stuffs'
         . DIRECTORY_SEPARATOR . 'sample.docx';



回答2:


Try this:

$Path = './doc/stuffs/sample.docx';
if (file_exists($Path)){
    if (unlink($Path)) {   
        echo "success";
    } else {
        echo "fail";    
    }   
} else {
    echo "file does not exist";
}

If you get file does not exist, you have the wrong path. If not, it may be a permissions issue.




回答3:


This should work once you are done with the permission issue. Also try

ini_set('display_errors', 'On');  

That will tell you whats wrong




回答4:


You need the full file path to the file of interest. For example: C:\doc\stuff\sample.docx. Try using __DIR__ or __FILE__ to get your relative file position so you can navigate to the file of interest.




回答5:


define("BASE_URL", DIRECTORY_SEPARATOR . "book" . DIRECTORY_SEPARATOR);
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'] . BASE_URL);

$path = "doc/stuffs/sample.docx";

if (unlink(ROOT_PATH . $Path)) {   
  echo "success";
} else {
  echo "fail";    
}

// http://localhost/book/doc/stuffs/sample.docx
// C:/xampp/htdocs\book\doc/stuffs/sample.docx


来源:https://stackoverflow.com/questions/11463581/how-to-use-unlink-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!