Save Instagram Images to WP Library

197 views Asked by At

I am using the instagram PHP scraper to get some Images from a Instagram once a Day and now I want to save them to WP to comply with the new Instagram API "cross-origin-resource-policy: same-origin" restriction.

Unfortunatly downloading the Images seems to be problematic for me. I am getting URL's like this one:

https://scontent-frt3-2.cdninstagram.com/v/t51.2885-15/e35/s1080x1080/180944446_818094295796893_2664338416777947736_n.jpg?tp=1&_nc_ht=scontent-frt3-2.cdninstagram.com&_nc_cat=101&_nc_ohc=IeiX9KxK83IAX_dtO18&edm=APU89FABAAAA&ccb=7-4&oh=78ad506e5ddbbcf3adfe3000d0a9a794&oe=60B3A80A&_nc_sid=86f79a

Should be simply saving the jpg but unfortunatly file_get_contents returns an empty file.

I am currently using this code:

$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true); 
$filename = $uniq_name.'.'.$imagetype;

$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);

$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => $filename,
    'post_content' => '',
    'post_status' => 'inherit'
);

$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data ); 
$this->conlog(wp_get_attachment_url($attach_id));

return wp_get_attachment_url($attach_id);

$imagetype is empty too, as getimagesize()['mime'] is empty.

I dont really know how to download the image, as I am not relally fluend in PHP. Do you know how this would be archived best? Thanks a lot!

1

There are 1 answers

0
Sco On

For you $imagetype , use pathinfo https://www.php.net/manual/fr/function.pathinfo.php

$imagetype = pathinfo($image_url, PATHINFO_EXTENSION);