简体   繁体   中英

Php File_exists not working properly

**I am using xampp for this project.

Hi all having a small problem with an inventory I am building. When I delete an object from the database I want to delete the picture that I linked to it. I do this by giving the images the same ID as the product so when Im deleting the item I can just look up the image to delete via its id.

The problem is when I delete the object the image is not deleted. File_exists keeps returning false. Any help would be great.

if(isset($_GET["yesdelete"])){

$id_to_delete = $_GET["yesdelete"];
$sql = mysqli_query($link,"DELETE FROM products WHERE id = $id_to_delete") or die (mysqli_error());

$pictodelete=("../Images/$id_to_delete.jpg");

if(file_exists($pictodelete)){
unlink($pictodelete);
}

header("location: inventory_list.php");
exit();
}

Try using DIRECTORY_SEPARATOR instead of '/' as separator. Windows uses a different separator for file system paths (backslash) than Linux systems.

I would also suggest to recheck the filename, sometimes there can be some kind of spelling mistake or case sensitive issues.

Use, the exact physical path for the file.

For that, use following:

$_SERVER['DOCUMENT_ROOT'];

And using this, get the exact path:

eg

$pictodelete = $_SERVER['DOCUMENT_ROOT'] . "/Images/" . $id_to_delete.".jpg";

Hope this works.

I found the answer and I want to thank everyone that helped with the problem. I think my filename had a space beforehand that was causing it to not find the file, but im only a beginner at php so i could be wrong but this solved my problem.

$id_delete = preg_replace('#[^0-9]#i','',$_GET["yesdelete"]); <-------- added this

$pictodelete = ("../Images/$id_delete.jpg");
if(file_exists($pictodelete)){
unlink($pictodelete);
}

I have faced a similar situation and the problem was the fact that my server was converting my file's name into capital letter so i did

if(file_exists(strtolower(trim($myimagefile)))==true)

and it worked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM