Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asd.jpg is not a valid JPEG file - Scandir PHP

I have a software that upload each minute a jpeg into FTP account.

In PHP i make a little PHP code in crontab that take last JPEG file and performs graphics processing. This work fine.

$all_files = scandir("./dir/dir",1);
$last_files = $all_files[0]; //take last jpeg
..etc..

The problem is that sometimes the PHP Code in crontab takes a file that is still being written over FTP (so it is incomplete) and generate this error:

[01-Jun-2016 15:30:05 Europe/Rome] PHP Warning:  imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file in /home/asdasd/public_html/www.asdasdasdasd.com/asd/asd/cron.php on line 15
[01-Jun-2016 15:30:05 Europe/Rome] PHP Warning:  imagecreatefromjpeg(): './dir/dir/153000.jpg' is not a valid JPEG file in /home/asdasd/public_html/www.asdasdasdasd.com/asd/asd/cron.php on line 15
[01-Jun-2016 15:30:05 Europe/Rome] PHP Warning:  imagecopyresampled() expects parameter 2 to be resource, boolean given in /home/asdasd/public_html/www.asdasdasdasd.com/asd/asd/cron.php on line 17

How do I add a check for scandir to catch the last complete file and not being written?

like image 497
Francesco Langiulli Avatar asked Nov 28 '25 14:11

Francesco Langiulli


1 Answers

You can just check the JPEG file if it's valid before processing it (cron.php):

if(exif_imagetype($filepath) != IMAGETYPE_JPEG){
    // Exit the script
    exit;
}

// Your image processing code goes here...

http://php.net/manual/en/function.exif-imagetype.php

like image 86
James A Avatar answered Dec 01 '25 05:12

James A