How to fix "getimagesize(): Read error!" in PHP

streetmaster86 picture streetmaster86 · Jan 9, 2019 · Viewed 8.1k times · Source

I want to upload images to a server using ajax and php.

On client-side i hava the following code:

var reader = new FileReader();
reader.readAsDataURL(file, 'UTF-8');
reader.onload = function (event) {
    var result = event.target.result;
    $.ajax({    
    type: "POST",
    url: "url", 
    data: { 
       data: result, 
       name: file.name,
       mimeType: file.type
    }
   });
 };

On server-side my code looks like the following:

 $path = 'somehow/'
 $fp = fopen( $path . $_POST['name'], 'w');
    $data = explode( ',', $_POST['data'] );
    fwrite($fp, base64_decode( $data[ 1 ] ));
    fclose($fp);
    chmod($path . $_POST['name'], 7777);

    list($width, $height) = getimagesize($path . $_POST['name']);

Now the method "getimagesize" always runs into an error "getimagesize(): Read error!"

Does anybody know, why this happens? When i look into the filesystem on the server the file 'FILENAME.JPG' exists ...

Answer

Houssein Zouari picture Houssein Zouari · Jan 9, 2019

There are two possible reasons for this error : either the url path is incommplete/incorrect or the picture file is corrupt and cannot be opened. A file may be corrupted, for example, if the image is not fully/correctly loaded onto the server.