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:
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!
For you
$imagetype
, use pathinfo https://www.php.net/manual/fr/function.pathinfo.php