PHP中filesize()报错问题及图片保存逻辑优化问询
filesize(): stat failed Warning & Correcting Your Logic Hey Alexandra32! Let's sort out that warning and get your album cover logic working exactly how you want it.
The Root of the Warning
Your current code tries to run filesize($album_name) when the file might not exist—plus, you're passing just the album name instead of the full path to the cover file. That's why you're getting the "stat failed" warning. On top of that, your conditional logic is flipped from what you described in your requirements.
Corrected Code
Here's the fixed version that matches your intended behavior:
$album_name = $row['album']; // Use a single variable for the full cover path to avoid repetition/errors $coverPath = "cdcovers/{$album_name}.jpg"; // Logic: Skip saving only if the file EXISTS AND is larger than 5KB // Otherwise (file doesn't exist, or exists but is ≤5KB), save the image if (!file_exists($coverPath) || filesize($coverPath) <= 5 * 1024) { // Fetch and save the artwork $imageString = file_get_contents(LastFMArtwork::getArtwork($row['artist'], $row['album'], true, "large")); $save = file_put_contents('/home/link/public_html/cdcovers/'.$row['album'].'.jpg', $imageString); }
Key Changes Explained
- Full Path Variable:
$coverPathstores the complete path to the cover file, so we don't misspell it or pass the wrong value tofile_exists/filesize. - Fixed Conditional Logic:
- First, check if the file doesn't exist (
!file_exists($coverPath)): if true, we need to save the image. - If the file does exist, we then check if its size is ≤5KB (
filesize($coverPath) <= 5 * 1024). Remember,filesizereturns bytes, so 5KB = 5*1024 = 5120 bytes. - This way, we only call
filesizewhen we know the file exists, eliminating the warning entirely.
- First, check if the file doesn't exist (
- Aligned with Your Requirements: This code does exactly what you wanted:
- Do nothing if the file exists and is over 5KB.
- Save the image if the file doesn't exist, or if it exists but is 4KB or smaller (including 0KB empty files).
Bonus Tip
If you want to be extra safe, you could wrap the filesize call in a @ to suppress any rare edge-case warnings, but with the file_exists check first, that shouldn't be necessary here.
内容的提问来源于stack exchange,提问作者Alexandra32

