How can I save a picture using php?

First we get image_id

  global $con; $con = new mysqli($host, $user, $password, $db); mysqli_query($con, "INSERT INTO user_images (image_user_id) VALUES ('$session_user_id')"); $image_id = mysqli_insert_id($con); 

And how can you save the images/$image_id.jpg type as images/$image_id.jpg and update image_url

 mysqli_query($con, "UPDATE user_images SET image_url = $image_id WHERE user_id = $session_user_id"); 

Php code

 <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $targ_w = $targ_h = 200; $jpeg_quality = 90; $src = $_FILES['image']['name'].'.jpg'; $img_r = imagecreatefromjpeg($src); $dst_r = ImageCreateTrueColor( $targ_w, $targ_h ); imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'], $targ_w,$targ_h,$_POST['w'],$_POST['h']); header('Content-type: image/jpeg'); imagejpeg($dst_r,null,$jpeg_quality); exit; } ?> 

Closed due to the fact that off-topic participants Dmitriy Simushev , torokhkun , Vladimir Glinskikh , Athari , Streletz 17 Nov '15 at 13:32 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Dmitriy Simushev, torokhkun, Vladimir Glinskikh, Athari, Streletz
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • And the question is what? What exactly is not working? - Dmitriy Simushev
  • By implicit conclusions from the text of the post, I concluded that the author needs to save the image to a file, and not to display it in the browser. - GrayHoax
  • @DmitriySimushev works but cannot save as a file - KYRAN
  • one
    I accept applications for the game in psychics =) - GrayHoax

1 answer 1

Your question already has an answer. But I would like to correct.

Use int conversion for security: imagecopyresampled($dst_r, $img_r, 0, 0, (int)$_POST['x'], (int)$_POST['y'], $targ_w, $targ_h, (int)$_POST['w'], (int)$_POST['h']); .

In addition, you are already using the imagejpeg function, the documentation for which is here .

To make it work, change the second parameter of this function: imagejpeg($dst_r, 'images/' . $image_id . '.jpg', $jpeg_quality); , you also need to remove the header('Content-type: image/jpeg'); if no image output is planned. Otherwise, the browser will always offer to save the image, or will show a "broken image."

  • Thank you so much for sure! - KYRAN