PHP on Server downloads empty images - php

I've got a php function that downloads youtube thumbnails to the server, and it works fine on my local version, however as soon as it gets uploaded to the server all of the .jpg files that it downloads are empty.
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
}
}
Any help / insight is appreciated.
Thanks

Related

How to store image uploaded from form as featured image in post?

I have an html form in front end in WordPress page. A user uploads the image in the form which should be set as featured image in CPT.
This is the upload field in the form:
<input id="uploadBtn" type="file" class="upload" name="uploadBtn"/>
I have tried this code :
// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png';// Define the image URL here
$image_name = 'wp-header-logo.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name); // Generate unique name
$filename = basename( $unique_file_name ); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $new_post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $new_post_id, $attach_id );
It works well if I have image url, name and such. However, I need to make it work for any image that user uploads. Is there any way to get image url and name from $_FILES? Any help would be appreciated. Thanks!
You need either post object or post ID for the set_post_thumbnail() function. The function wp_insert_post() will return post id on success. You can use that post id to set the thumbnail image.
Here is the modification for your last couple of lines
$post_id = wp_insert_post( $my_post );
if(!$post_id){
// post insertion was failed. Handle it here
}
//Set Image as thumbnail
set_post_thumbnail($post_id, $attach_id);

How do I link to external images in my WP posts

I am scraping a site and putting data in my WP site.
There are lots of images in those posts.
I want that when importing that scraped data into my WP site,
I want to link images into my site directly from that external URL instead of downloading image to my server.
I am grammatically importing scraped data to my site.
Here is that part of adding image
// for image
$ins_q = "INSERT INTO wpxw_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, "
. "comment_status, ping_status,"
. "post_password, post_name, to_ping, pinged, post_modified,post_modified_gmt, post_content_filtered,post_parent,"
. "guid,menu_order,post_type,"
. "post_mime_type,comment_count) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$sth = $conn->prepare($ins_q);
if (!$sth->execute(array(
$post_author, $date, $date, "", sanitize_title_with_dashes($image_name), "", "inherit", "open", "closed", '',
str_replace(".", "-", $image_name), '', '', $date, $date, '', $post_id,
"http://photos2.zillowstatic.com/p_f/ISdc6hruhctopo0000000000.jpg"
, 0, "attachment", "image/jpeg", 0
))) {
echo "<h1>Error</h1>";
print_r($sth->errorInfo());
exit();
}
}
MY PROBLEM is that when adding external link to image, images do not show on my post. How can I show images from external resources?
// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

Copy image to my server direct from URL and upload it to Wordpress uploads folder?

I am trying to upload an image through PHP script as mentioned below. I am taking image from the URL;
I have taken reference from this post Actually in my case I want to upload it to WordPress upload folder where post images get upload and you know WordPress creates folder on run-time inside 'wp-content/uploads/' and it uploads image there. So path ($save_path) is not decided on run time.
$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);
I am trying to use WordPress function "media_handle_upload" to upload image instead of "file_put_contents" but I am not getting how I pass file object to this function once i get the file contents ($contents=file_get_contents($url);). Kindly assist.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
100% working this code:
include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imageurl = '<IMAGE URL>';
$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 );
echo $attach_id;
Here is complete example :
// $filename should be the path to a file in the upload directory.
$filename = '/path/to/uploads/2013/03/filename.jpg';
// The ID of the post this attachment is for.
$parent_post_id = 37;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );
You can check wp_insert_attachment() for more info

Wordpress - Upload image programmatically, width and height are 0

I made a function which allows users to upload image to my wordpress site. Uploading works fine, but when I open a post with this uploaded image, the image doesn't show up. When I opened it in Firebug I noticed that image width and height is 0.
How can I upload image so it show up like I uploaded it with Media Library form.
This is my code:
if(isset($_FILES["image"])) {
if (!function_exists('wp_handle_upload')) require_once(ABSPATH . 'wp-admin/includes/file.php');
$uploadedfile = $_FILES['image'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile) {
$wp_filetype = $movefile['type'];
$filename = $movefile['file'];
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $wp_filetype,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename);
set_post_thumbnail($pageid, $attach_id);
}
}
Edit:
When I manually add width: 100% in Firebug, the image show up
I found a solution for this problem.
After the image was uploaded, meta data was not updated. So at the end of this function I added this:
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
This code updates the meta data for this image, therefore, Wordpress can find its dimensions.

wp_generate_attachment_metadata returning an empty array

I'm writing a Wordpress plugin to download remote images on my blog.
I made a function to upload a remote image locally, then returning its ID.
All seems OK except that
$attach_data = wp_generate_attachment_metadata( $attach_id, $local_file );
returns me an empty array - and it should not.
wp_generate_attachment_metadata is, among others, responsible of generating the thumbnails of the uploaded image. But I have no thumbnails created when I run my code.
I checked the values I send to the function and they seems correct : I have an ID and an absolute path to the uploaded file, as documented in the codex.
Still, I can't manage to have my code working :
$attach_data should not be empty...
Can anyone help ?
function upload_from_remote_url($url,$post_id){
$url = $this->validate_remote_media_url($url); //check file is not on local server
if (!$url) return false;
if ($existing_id = $this->media_already_exists($url)) return $existing_id; //url already has been downloaded
$upload_dir = wp_upload_dir();
$wp_mime_types = wp_get_mime_types();
//fetch image
$response = wp_remote_get( $url );
//get filename without extension
$filename = basename( $url ); //get filename & extension
$filename_strip = preg_replace('/\.[^.]*$/', '', $filename); //strip extension
//get extension from content type,
//because wp_upload_bits needs an extension and certain url don't have one.
$file_type = wp_remote_retrieve_header( $response, 'content-type' );
$extensions = array_search($file_type,$wp_mime_types);
$extensions_arr = explode('|',$extensions);
$extension = $extensions_arr[0];
$new_filename = $filename_strip.'.'.$extension; //full name
$new_filename = wp_unique_filename($upload_dir['path'], $new_filename); // be sure this name do not exist already
$uploaded = wp_upload_bits($new_filename, '', wp_remote_retrieve_body( $response ) );
if ($uploaded['error']) return false;
$local_file = $uploaded['file'];
$local_filename = basename($local_file);
$local_filetype = wp_check_filetype( $local_filename, null );
//Attachment options
$attachment = array(
'post_title'=> $local_filename,
'post_mime_type' => $local_filetype,
'post_status' => 'inherit'
);
// Add the image to your media library
$attach_id = wp_insert_attachment( $attachment, $local_file, $post_id );
if (!$attach_id) return false;
$attach_data = wp_generate_attachment_metadata( $attach_id, $local_file );
wp_update_attachment_metadata( $attach_id, $attach_data );
//save source link so we do not import several times the same media
update_post_meta($attach_id, 'grm_source', $url);
return $attach_id;
}
BTW, if any WP gourou had anything to say about this code... I'll be happy to read it, as the WP documentation about uploading files is a bit messy. I needed some specific stuff here, as being able to retrieve the file extension. I ended up to this but maybe you have some better ideas !
I've had a similar problem where mime type was missing. Since I use only one mime type, it was fixed by
'post_mime_type' => 'image/jpeg'
After that, it was still not updating the metadata, but forcing the update with "wp_update_attachment_metadata" solved the problem:
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
This is, what finally fixed it for me:
apply_filters('wp_handle_upload', array(
'file' => $file_path,
'url' => $file_url,
'type' => $file_type),
'upload');
Explanation: I'm not quite sure why this fixed the error for me, but I assume that this either has something to do with plugins using the wp_handle_upload hook or that the filters add meta-data to the attachment, which otherwise would be missing in the wp_generate_attachment_metadata function.
Full function:
function add_to_media_lib($file_url, $file_path, $parent_post_id)
{
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
// Check the type of tile. We'll use this as the 'post_mime_type'.
$file_type = wp_check_filetype(basename($file_url), null);
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($file_url),
'post_mime_type' => $file_type['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($file_url)),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $parent_post_id
);
// Insert the attachment.
$attach_id = wp_insert_attachment($attachment, $file_url, $parent_post_id);
// apply filters (important in some environments)
apply_filters('wp_handle_upload', array('file' => $file_path, 'url' => $file_url, 'type' => $file_type), 'upload');
// Generate the metadata for the attachment, and update the database record.
if ($attach_data = wp_generate_attachment_metadata($attach_id, $file_path)) {
wp_update_attachment_metadata($attach_id, $attach_data);
} else {
echo '<div id="message" class="error"><h1>Failed to create PDF-thumbnail Meta-Data</h1><pre>' . print_r($attach_data) . '</pre></div>';
}
return $attach_id;
}
I know the topic is old but I was facing a similar issue and what worked for me was enabling the Crop thumbnail to exact dimensions (normally thumbnails are proportional) under Settings >> Media. I am using the media_handle_sideload() function by the way.

Categories