PHP中检查图片文件存在并删除的写法是否正确?性能相关疑问
Hey there! Let's go through your questions about the image deletion code one by one:
Your code works logically, but there's a small optimization you can make: the file_exists($file) check inside the loop is redundant. The glob() function only returns paths to files that actually exist, so you can safely call unlink($file) directly without extra validation.
Here's the simplified version:
foreach (glob("../imgs/" . $name . ".*") as $file) { unlink($file); }
Just keep two things in mind:
- Double-check that the relative path
../imgs/is correct (it depends on where your executing script is located). - Make sure the PHP process has write/delete permissions for the target folder—otherwise
unlink()will fail silently (or throw an error, depending on your error settings).
This depends entirely on your business scenario:
- If each user's unique ID maps to only one image file (e.g., you overwrite the same file extension on each upload, or your system restricts users to a single profile picture), then adding a
breakafter deleting the first match makes sense—it cuts down on unnecessary loop iterations:foreach (glob("../imgs/" . $name . ".*") as $file) { unlink($file); break; // Stop looping once the target file is deleted } - If users might have multiple old images with different extensions (e.g., a
.pngfrom last month and a.jpgfrom last week that both need deleting), don't terminate the loop—you need to process all matching files.
Yes, glob() can get slow when dealing with directories that have a huge number of files (like thousands or more). The reason is that glob() scans the entire directory first, loads all matching file paths into memory, then iterates through them—this gets progressively slower as the number of files grows.
If your image folder is large, here are two better alternatives:
- Option 1: Use
DirectoryIteratorinsteadDirectoryIteratoruses an iterator pattern, so it reads directory entries one at a time, processes matches on the fly, and doesn't load all file paths into memory at once. This is more memory-efficient and faster for large directories:$dir = new DirectoryIterator("../imgs/"); foreach ($dir as $fileinfo) { if (!$fileinfo->isDot() && str_starts_with($fileinfo->getFilename(), $name . ".")) { unlink($fileinfo->getPathname()); // Add a break here if you only need to delete one file } } - Option 2: Store file paths in a database
The best performance approach is to save the full path of each user's image (e.g.,../imgs/user123.png) to your database when the image is uploaded. When you need to delete the old image, just fetch the path from the database and callunlink()directly—no directory scanning required at all.
内容的提问来源于stack exchange,提问作者SomeBeginner

