服务器上的PHP下载空图像

时间:2018-09-17 09:06:46

标签: php regex wordpress curl

我有一个php函数,可以将youtube缩略图下载到服务器上,并且在我的本地版本上可以正常工作,但是,一旦将其上传到服务器上,它下载的所有.jpg文件都是空的。 / p>

function download_thumbnail() {

  preg_match('/src="(.+?)"/', get_field('youtube_link'), $matches); //Pull the URL of the video out of the iframe generated by ACF
  preg_match("/embed\/(.+)\?/", $matches[1], $vid_id); //Pull the ID of the video from the URL

  $download_url = "https://img.youtube.com/vi/".$vid_id[1]."/maxresdefault.jpg"; //Use the standard youtube link to get the max res thumbnail

  $uploads = wp_upload_dir();
  $path = $uploads['path']."/"; //Get the upload path

  $filename = $vid_id[1].'.jpg'; //Set the filename as the ID of the video

  $save_as = $path.$filename; //Full path of the created file

  if(!file_exists($save_as)) { //Check if file exists
   $ch = curl_init($download_url); //Initialize the PHP cURL to the youtube page

   $fp = fopen($save_as, 'wb'); //Start the path link

   curl_setopt($ch, CURLOPT_FILE, $fp); //Download the image to the path link
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_exec($ch);
   curl_close($ch);
   fclose($fp);

   $filetype = wp_check_filetype( basename( $save_as ), null ); //Check the file type

   $attachment = array( //Create neccessary wordpress data to the image
   'guid'           => $uploads['url'] . '/' . basename( $save_as ),
   'post_mime_type' => $filetype['type'],
   'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $save_as ) ),
   'post_content'   => '',
   'post_status'    => 'inherit'
   );

   $attach_id = wp_insert_attachment( $attachment, $save_as, get_the_ID() ); //Add neccessary wordpress data to the image
   require_once( ABSPATH . 'wp-admin/includes/image.php' ); //Make sure that the image gets registered as an image


   $attach_data = wp_generate_attachment_metadata( $attach_id, $save_as ); //Generate more meta data
   wp_update_attachment_metadata( $attach_id, $attach_data ); //Attatch the meta data

   set_post_thumbnail( get_the_ID(), $attach_id ); //Set image as the featured image
  }
  }

感谢您的帮助/见识。

谢谢

0 个答案:

没有答案