0

I'm having a problem with writing a new image file from image-data (dataurl). Images lower than 1 mb is no problem with file_put_contents. But if the file is bigger than 1 mb. The function does not work.

Procedure

  1. A DataUrl was sent to print.php via ajax with 1436190 in length.
  2. print.php is get the var $_POST['image'] and $_POST['filename']
  3. print.php save file to hdd with file_put_contents($photo, $data);

Here's the print.php script:

<?php
header('Content-Type: image/jpeg');
ini_set('memory_limit', '128M');
$data=$_POST['image'];
if(!$_POST['filename']){
    exit("error");
}
list($dir,$folder,$file)=explode("/",$_POST['filename']);
$ext=strtolower(pathinfo($_POST['filename'], PATHINFO_EXTENSION));

$file=basename($file,".".$ext);
$data = base64_decode($data);

$imgRes = imagecreatefromstring($data);
if($imgRes !== false && imagejpeg($imgRes, $file,"100") === true)
    if(!is_dir($dir.'/'.$folder.'/new/')){
        mkdir($dir.'/'.$folder.'/new/',0777);
    }
    $photo=$dir.'/'.$folder.'/new/'.$file.'-'.time().".".$ext;//full url

    $saved=file_put_contents($photo, $data);
    if($saved){     
        echo "ok";
    }else{
        echo "error";
    }
imagedestroy($imgRes);
?>

I've tried to figure this out. But it's not working. Nothing shows in console. Or is there any smarter way to achieve this than file_put_contents?

Rohcana
  • 359
  • 4
  • 13
Wilf
  • 2,297
  • 5
  • 38
  • 82
  • How does it "not work"? Explain the specific error / result, make a screenshot, or whatever. – mario Aug 03 '15 at 14:36
  • Nothing shows in console, no file created, no error shows... It just `echo "ok"` but... not work!!! I think the issue is about the file size. If it's bigger than 1mb - it will not process. – Wilf Aug 03 '15 at 14:45
  • 1
    "Nothing shows" typically amounts to negligently keeping error_reporting turned off despite something not working. Run a debugger over your code, inspect each variable, or at least print_r/var_dump everything, check file permissions manually then. – mario Aug 03 '15 at 14:52
  • Can you see anything wrong in my code? – Wilf Aug 03 '15 at 14:57

1 Answers1

0

First: "his function returns the number of bytes that were written to the file, or FALSE on failure." Use -> if($saved !== FALSE) OK else error

Second: file_put_contents — Write a string to a file. Then you need use -> fwrite() - Binary-safe file write.

http://php.net/manual/en/function.file-put-contents.php

http://php.net/manual/en/function.fwrite.php

Good luck!