Ask Your Question
3

How can PHP be used to store an image/jpeg HTTP response as a file?

asked 2023-06-16 23:38:34 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-17 00:07:02 +0000

david gravatar image

To store an image/jpeg HTTP response as a file using PHP, you can follow the below steps:

  1. Send an HTTP request to the image URL using cURL or filegetcontents() function.
  2. Verify that the response is a valid image using getimagesize() function.
  3. Create a new file and write the image contents to it using fileputcontents() function.

The below PHP code can be used to store the image:

$imageUrl = 'http://example.com/image.jpg';
$response = file_get_contents($imageUrl); // or use cURL to fetch image

if ($imageInfo = @getimagesizefromstring($response)) {
    $newFilename = 'new-image.jpg';
    $destination = 'path/to/save/' . $newFilename;

    if (file_put_contents($destination, $response)) {
        echo 'Image saved as ' . $newFilename;
    } else {
        echo 'Failed to save image';
    }
} else {
    echo 'Invalid image format';
}

Note that you should replace the $imageUrl variable with the actual image URL and provide the correct path for saving the image. Also, make sure that the directory where you are saving the image has write permission.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-16 23:38:34 +0000

Seen: 12 times

Last updated: Jun 17 '23