Reputation: 11
i have this code:
$album_name = $row['album'];
if(!file_exists("cdcovers/$album_name.jpg") && filesize($album_name) > 5){
//gravar as imagens
$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);
}
but i gives an error(Warning: filesize(): stat failed for...) if the image is not there, my ideia was if the file exists and is bigger then 5kb then do nothing if it is 4kb or below save image, even if a file exists with 0kb.
Upvotes: 0
Views: 37993
Reputation: 6068
Base on what I understand you want to create an image if it does not exist or update the image if it is smaller than 5kb.
In short, filesize
will yield the warning if you give it a file that does not exists but there are a few more issues with the original code:
filesize
returns the size in bytes and 5kb is ~5,000 bytes. <
should be used instead greater than operator >
.I modified the sample code to store the absolute path to the image in a variable and reference it where needed, fixed the bytes comparison and updated the condition block requirements to prevent the filesize
warning.
Please review the updated code below:
$albumCoverImg = '/home/link/public_html/cdcovers/' . $row['album'] . '.jpg';
$minSize = 5 * 1000; // 5KB
$fileExist = is_file($albumCoverImg);
if (!$fileExist || ($fileExist && filesize($albumCoverImg) < $minSize)) {
//gravar as imagens
$imageString = file_get_contents(LastFMArtwork::getArtwork($row['artist'], $row['album'], true, "large"));
$save = file_put_contents($albumCoverImg, $imageString);
}
Upvotes: 6
Reputation: 19764
You have to check if the file exists before to check its size.
If "cdcovers/$album_name.jpg"
and $album_name
are different files, you also have to check the second.
if (!file_exists("cdcovers/$album_name.jpg") &&
file_exists($album_name) &&
filesize($album_name) > 5) {
If the files are the same, it's the error (missing folder and file extension).
Also, you save the file with an absolute path : '/home/link/public_html/cdcovers/'.$row['album'].'.jpg'
. It could differ from "cdcovers/$album_name.jpg"
(depending of the current folder's script execution). You may use the absolute path, of __dir__
constant to be relative to your current folder.
You may use variables to store filename and limit errors by writing them multiple times :
$filename = '/home/link/public_html/cdcovers/'.$row['album'].'.jpg' ;
if (!file_exists($filename) ||
(file_exists($filename) && filesize($filename) < 5000)) {
file_put_contents($filename, ...);
}
Please also note that filesize()
returns the size in bytes, not in Kb.
Upvotes: 0