Save image from url with curl PHP

To save an image from a URL using PHP and cURL, you can use the following function:


function saveImage($image_url, $image_name)
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $image_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $data = curl_exec($ch);
  $image = imagecreatefromstring($data);
  $image_name = preg_replace('/[^A-Za-z0-9\. -]/', '', $image_name);
  imagejpeg($image, $image_name, 100);

Watch a course Learn object oriented PHP

To use this function, pass the URL of the image as the first argument and the desired name for the saved image as the second argument. For example:


saveImage("", "image.jpg");

This will save the image to the current working directory with the specified name. You can also specify a different directory by including the path in the image name. For example:


saveImage("", "/path/to/directory/image.jpg");