WordPress image upload using url or from external site

     
      $filepath = dirname(__FILE__) . ‘/’ . $filename;

$wp_filetype = wp_check_filetype($filepath, null );
$uploads = wp_upload_dir();

$fullpathfilename = $uploads[‘path’] . “/” . $filename;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, get_template_directory_uri().’/youtubeupload/’.$filename);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$image_string = curl_exec($ch);
curl_close($ch);

$fileSaved = file_put_contents($uploads[‘path’] . “/” . $filename, $image_string);
if ( !$fileSaved ) {
echo “The file cannot be saved.”;
}

$attachment = array(
‘post_mime_type’ => $wp_filetype[‘type’],
‘post_title’ => preg_replace(‘/.[^.]+$/’, ”, $filename),
‘post_content’ => ”,
‘post_status’ => ‘inherit’,
‘guid’ => $uploads[‘url’] . “/” . $filename
);
$attach_id = wp_insert_attachment( $attachment, $fullpathfilename );
if ( !$attach_id ) {
echo “Failed to save record into database.”;
}
require_once(ABSPATH . “wp-admin” . ‘/includes/image.php’);
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullpathfilename );
wp_update_attachment_metadata( $attach_id,  $attach_data );

set_post_thumbnail( $post_id, $attach_id );