Search code examples
phpwordpressunlink

Wordpress/PHP- Unlink file search directory does not contain file path


I'm currently trying to create a function that will allow certain administrative users to delete posts on our Wordpress website. More specifically, directly delete files from the Wordpress media library. I can successfully retrieve these files by type and display their names, but whenever I try to utilize the unlink() method to remove some files from use, it searches for the file relative to the php script rather than the server. I've tried using $_SERVER['DOCUMENT_ROOT'] and adding "../" repeatedly in order to go back enough directories to then specify the file path correctly, but neither option has worked. I also cannot use the $context parameter for unlink() because the php version is not up to date and updating it is not feasible at the moment. Here is some of my code:

foreach($imgs as $img){
$imgcutpath = substr($img, 0, 33);
fopen($img, "r");
$imgpath = str_replace($imgcutpath, "", $img);
echo "<a href='?delete=1'>                                   Delete</a>";
if (isset($_GET['delete']))
{ unlink($_SERVER['DOCUMENT_ROOT'] . $imagepath); }
}

Also here is the warning I am receiving:

Warning: unlink(/path/to/file/from/server): Is a directory in 
/path/to/php/file/running/this/code/from/server/phpfile.php on line 28

That isn't exactly the warning, I've simply replaced the actual file paths for security reasons. Thanks for the help!


Solution

  • If you know how to get to the file relatively, you can convert that to it's canonical path using PHP's realpath() function.

    That being said, I think you are going about this wrong way and not relying on the library at hand within WordPress. At any point in your code snippet, do you have access to the file's attachment id?

    You can utilize wp_delete_attachment() to unlink media library files if you know the ID.

    If you have the post ID, and not the attachment ID's, you can use get_attached_media() with the post ID, and it will give the attachment ID's you can iterate over.

    There is more to consider than just deleting the file. A reference to the file is stored in the database, and that reference gets linked to other things. Using the tools available in WordPress means it will handle all of the cleanup correctly instead of you doing it manually.