Upload base64 encoded images using Facebook sdk? - php

It's possible to upload base64 encoded images directly without saving it using Facebook PHP SDK 3.1.1?
$facebook->setFileUploadSupport(true);
$facebook->api('/me/photos', 'POST', array(
'source' => '#/mycoolpic.png', // No need to use FS, base64 encoded image
'message' => "I'm cool",
));

You can do as follow in PHP :
function base64_to_jpeg( $base64_string, $output_file ) {
$ifp = fopen( $output_file, "wb" );
fwrite( $ifp, base64_decode( $base64_string) );
fclose( $ifp );
return( $output_file );
}
$facebook->setFileUploadSupport(true);
$image = base64_to_jpeg( $your_base64_string, 'tmp.jpg' );
$args = array('message' => 'Some message');
$args['image'] = '#' . realpath( $image );
$data = $facebook->api('/your_user_id/photos', 'post', $args);
unlink($image);

No, not that I have been aware of, or found out searching. Make sure you use realpath() around the image name, to give the absolute path to the image.

Related

Base64 image string into image file using PHP

I need code to convert a base64 image string into an image file and write into local directory using PHP. I tried:
function user_profile_photo(){
$input = urldecode(file_get_contents('php://input'));
$received = json_decode($input, true);
$user_id = $received['user_id'];
$img = $received['imagecode'];
$imagedata = base64_decode($img);
$image_path='uploads/images/'.$user_id;
$path = '/var/www/html/empengapp/uploads/images/'.$user_id;
if (!file_exists($path)) {
mkdir($path, 0755, true);
}
$new_name = date('ymd').time().'.jpg';
$pathwithfile = '/var/www/html/empengapp/uploads/images/'.$user_id.'/'.$new_name;
$success = file_put_contents($pathwithfile, $imagedata);
var_dump($imagedata);exit;
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($resp, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}//end of function user_profile_photo
It is writing a file with given extension, but when you try to open file it shows an invalid file error.
I figure it out the solution.
$pathwithfile = 'your file path with image name';//e.g '/uploads/test.jpg'
$ifp = fopen( $pathwithfile, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $imagedata );
$success = fwrite( $ifp, base64_decode( $data[ 1 ] ) ); // clean up the file resource
fclose( $ifp );
I was sending over the API to PHP server. You need to encode your image base64 string and your image base64 string must include "data:image/jpeg;base64". We are splitting it on PHP server But don't think to send image base54 without "data:image/jpeg;base64".
But remember one thing you have to use image base64 including

WordPress 5.x: Programatically Images upload is not working

I'm creating a custom plugin on WordPress to upload my products from my database to WooCommerce. All the logic works perfectly, but when it comes to upload the images and attach them to the product, it is not working.
I have tried using the regular copy from source to a local directory and then creating the media post, but it didn't work.
This is what I'm trying currently:
$image_id = media_sideload_image(
urlencode( $item['ImgPath1'] ),
$post_id,
$item['Title'],
'id'
);
add_post_meta( $post_id, '_thumbnail_id', $image_id );
I have also tried:
$filename = basename( $source ); // Get the filename including extension from the $fileurl e.g. myimage.jpg
$destination = WP_CONTENT_DIR. '/uploads/product_images/' . $filename; // Specify where we wish to upload the file, generally in the wp uploads directory
copy( $source, $destination ); // Copy the file
$filetype = wp_check_filetype( $destination ); // Get the mime type of the file
$attachment = array( // Set up our images post data
'guid' => get_option( 'siteurl' ) . '/wp-content/uploads/product_images/' . $filename,
'post_mime_type' => $filetype['type'],
'post_title' => $filename,
'post_author' => 1,
'post_content' => ''
);
I expect to at least see the images on ftp, but nothing is reported and my product import continues without any issues.
Your second example appears to be incomplete, so I'm gonna ignore it and focus on fixing the first.
The issue with your first example is that media_sideload_image() is designed to be used with an external URL, not a filepath on the same server. However, most of the inner workings of that function actually happen in media_handle_sideload(), which gets called once the file has been downloaded to a temporary location on the local server.
The following code was written mostly from memory and hasn't been tested, but should work:
function insert_media_from_path( $file_path, $attach_to = 0, $title = null, $delete_original = false ) {
if( !file_exists( $file_path ) ) {
return false;
}
$file_array = array(
'name' => basename($file_path),
'tmp_name' => $file_path
);
$id = media_handle_sideload( $file_array, $attach_to, $title );
if( $id && $delete_original ) {
unlink( $file_path );
}
return $id;
}

convert base64 image to jpg then upload to server not working

I am new to base64 and I have never needed to convert it so I am not sure what is going on here. I have my base64 string in $socialmedia_image. I create a random file name with rand. I plug it into the function which I got off stack and....nothing. It does not convert or transfer over with move_uploaded_file and I have no idea who to check for an error.
Can someone tell me what I am doing wrong?
///// base64 string /////
$socialmedia_image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg.....";
$rand = rand(000000000000000,999999999999999);
$output_file = $rand.".jpg";
$socialmedia_image = base64_to_jpeg( $socialmedia_image, $output_file );
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen( $output_file, 'w' );
$data = explode( ',', $base64_string );
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
fclose( $ifp );
return $output_file;
}
move_uploaded_file($socialmedia_image, "../tickets/attachments/".$output_file);
How about that?
file_put_contents($output_file, $data);

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.

Upload a remote photo to an upload

Is it possible to upload a remote picture to Facebook using the Facebook PHP Library??
Instead of using
$facebook->setFileUploadSupport(true);
$args = array('message' => 'My Caption');
$args['image'] = '#' . realpath($file);
$data = $facebook->api('/me/photos', 'post', $args);
Instead of a realpath($file) I would like to use a remote path to an image for example:
http://myserver.com/image.jpg
I tried to replace the realpath($file) with a http link but I got the following error:
Uncaught CurlException: 26: couldn't open file "http://mydomain.com/fb_images/EwrTsUqEuG.jpg"
Use file_get_contents() to download the file to your server, then file_put_contents() to store it in a temporary, local file for the upload FB transfer process, then unlink() to delete the file afterwards.
<?php
# The URL for the Image to Transfer
$imageURL = 'http://server.com/the_image.jpg';
# Folder for Temporary Files
$tempFilename = $_SERVER['DOCUMENT_ROOT'].'/tempFiles/';
# Unique Filename
$tempFilename .= uniqid().'_'.basename( $imageURL );
# Get the Image
if( $imgContent = #file_get_contents( $imageURL ) ){
if( #file_put_contents( $tempFilename , $imgContent ) ){
$facebook->setFileUploadSupport(true);
$args = array('message' => 'My Caption');
$args['image'] = '#' . realpath( $tempFilename );
$data = $facebook->api('/me/photos', 'post', $args);
# Once done, delete the Temporary File
unlink( $tempFilename );
}else{
# Failed to Save Image
}
}else{
# Failed to Get Image
}

Categories