You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中filesize()报错问题及图片保存逻辑优化问询

Fixing the 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: $coverPath stores the complete path to the cover file, so we don't misspell it or pass the wrong value to file_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, filesize returns bytes, so 5KB = 5*1024 = 5120 bytes.
    • This way, we only call filesize when we know the file exists, eliminating the warning entirely.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:41:14