Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.