Error in fetching image using wp_remote_get() function

admin

Administrator
Staff member
I am using
Code:
wp_remote_get
to fetch image from a url and attach it to a post as a Featured Image. I was able to do it initially using some help from <a href="https://wordpress.stackexchange.com...age-url-when-using-wp-insert-post/41300#41300">this</a> post and images were successfully set as featured image and are displaying in backend but now images are set as featured image successfully but only name of image is being displayed (as if the path of image file is broken).
<br>
When I go to image path using ftp, I can see image file but when I try to open image it says unsupported format.
<br>
Below is the code I used to fetch images
Code:
$upload_dir = wp_upload_dir();            
$image_url = $one_post-&gt;images[0];
$image_data = wp_remote_get($image_url);
//Get image and set unique file name
$filename = $new_post_id.&quot;_&quot;.$one_post-&gt;ID.&quot;_&quot;.basename($image_url);    
if (wp_mkdir_p($upload_dir['path'])) {
     $file = $upload_dir['path'] . '/' . $filename;
     } else {
       $file = $upload_dir['basedir'] . '/' . $filename;
     }
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
           'post_mime_type' =&gt; $wp_filetype['type'],
           'post_title' =&gt; sanitize_file_name($filename),
           'post_content' =&gt; '',
           'post_status' =&gt; 'inherit',
      );            
$attach_id = wp_insert_attachment($attachment, $file, $new_post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
wp_update_attachment_metadata($attach_id, $attach_data);
set_post_thumbnail($new_post_id, $attach_id);
If I open image file with a text editor I am seeing something like below
Code:
ArrayÿØÿà JFIF
Is there some error in encoding?<br>
Please Correct me what I am doing wrong.