Upload a remote photo to an upload - php

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
}

Related

WordPress / PHP 'Trying to get property 'feeds' of non object when trying to upload image from remote url

I'm trying to scrape some JSON data (that part works fine), but when I try and add the featured image, (a blank icon appears in the media library, with correct filename, but the url field says 'false' & I get this error:-
Notice: Trying to get property 'feeds' of non-object in
/Users/macbook/Documents/www/news_test/wp-includes/post.php on line
4482
Fatal error: Uncaught Error: Call to a member function
using_permalinks() on null in
/Users/macbook/Documents/www/news_test/wp-includes/link-template.php:423
Stack trace: #0
/Users/macbook/Documents/www/news_test/wp-includes/link-template.php(147):
get_attachment_link(Object(WP_Post), false) #1
/Users/macbook/Documents/www/news_test/wp-includes/post.php(4105):
get_permalink(Object(WP_Post)) #2
/Users/macbook/Documents/www/news_test/wp-includes/post.php(5740):
wp_insert_post(Array, false) #3
/Users/macbook/Documents/www/news_test/wp-content/plugins/code-snippets/php/snippet-ops.php(446)
: eval()'d code(92): wp_insert_attachment(Array, '/Users/macbook/...',
293) #4
/Users/macbook/Documents/www/news_test/wp-content/plugins/code-snippets/php/snippet-ops.php(446):
eval() #5
/Users/macbook/Documents/www/news_test/wp-content/plugins/code-snippets/php/snippet-ops.php(534):
execute_snippet('ini_set('displa...', 6) #6
/Users/macbook/Documents/www/news_test/wp-includes/class-wp-hook.php(287):
execute_active_snippets('') #7 /Users/ma in
/Users/macbook/Documents/www/news_test/wp-includes/link-template.php
on line 423 There has been a critical error on your website. Please
check your site admin email inbox for instructions.
Here's the code:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
global $wpdb;
$json = "http://newsapi.org/v2/top-headlines?country=ie&apiKey=**************";
$response = file_get_contents($json);
$mydecode = json_decode($response, true);
$mydecode = $mydecode['articles'];
// error_log(printf($mydecode));
foreach ($mydecode as $key => $value) {
$title = str_replace("&", "&", $value['title']);
$content = str_replace("&", "&", $value['content']);
//error_log("LOG: " . $title[0]);
// $description = str_replace("&", "&", $mydecode.articles->description);
// $article_url = $mydecode.articles->url;
$image_url = $value['urlToImage'];
// $content = $mydecode.content;
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(2),
'post_type' => 'post'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
// add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Add Featured Image to Post
// Add Featured Image to Post
// $image_url = $urlToImage; // Define the image URL here
//now to try and get actual image name
$headers = wp_get_http_headers( $image_url );
$mime_type = $headers['content-type'];
$ext = '';
foreach ( wp_get_mime_types() as $exts => $mime ) {
if ( $mime == $mime_type ) {
$ext = $exts;
break;
}
}
//now to apply extension if it didn't have one
if( $ext ){
$exts = explode('|', $ext);
$ext = '.'.$exts[0];
}
$image_name = 'image';
$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 . $ext ); // Generate unique name
$filename = basename( $unique_file_name ); // Create image file name
error_log("Filenames: ".$filename);
// 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;
}
error_log("file: ".$file);
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = $exts[0];
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype,
'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 );
}
I'm working on WordPress 5.5, and using the snippets plugin to execute the code.
tl;dr
This is happening because you are calling wp_update_post too early in WordPress lifecycle. Hook your update logic to init and you will be fine.
Long story
This warning is coming from WordPress trying to find a pretty slug for the post, but being unable to do so because the Permalink logic has not loaded yet.
The warning comes from this line: https://github.com/WordPress/WordPress/blob/master/wp-includes/post.php#L4776
As you can see, the $wp_permalink global is populated kinda late in the lifecycle, AFTER plugins_loaded and before init: https://github.com/WordPress/WordPress/blob/master/wp-settings.php#L473-L479
So if you call wp_update_post on a plugin without a hook, the permalink global will not be populated yet.
So you should change your code flow to make sure it only runs wp_update_post after init has fired.

Upload Image within Wordpress Front-End Form via the Image's URL

I am using the Board Game Geek API in order to pull in various data. One piece of data I want is the image.
For example, here is an API call for a particular board game:
https://boardgamegeek.com/xmlapi2/thing?id=169786&stats=1
When I get the response via my ajax call, I am able to grab the image url within the xml via:
var image_url = $(data).find("image")[0].textContent;
However: at that point I'm stumped. I want to upload the image that is located at that url, but I do not know how to upload the image via a form.
In wordpress: the only way I know how to upload images is if the image already exists on my computer. In that scenario, I have the following input:
<label for='board_game_image></label>
<input type="file" name="board_game_image" id="board_game_image" multiple="false"></input>
This input creates the "Choose Files" button to upload an image from your computer. Once the form is submitted, I use media_handle_upload to save the image within the uploads directory and create the relevant database records. Unfortunately: this process appears to not work when the image does not already exist on your computer, but instead exists somewhere on the internet (i.e. the image exists via the url).
Question: How can I upload an image via a wordpress front-end form when the image does not exist on my computer? Instead: all I have is the url of where the image exists on the internet.
You should include the image link on your form,
e.g.
var image_url = $(data).find("image")[0].textContent;
//assign the value to hidden input
$('#imgURL').val( image_url );
then add something like this on your form
<input type="hidden" id="imgURL" name="imageURL">
I'm not sure how you handle your form submission, but you can do something like below to process the image after submission.
First, save the image on uploads folder
$imgurl = $_REQUEST['imageURL']; // get the img url from the submitted data
$imginfo = pathinfo($imgurl); //get the url information
$filename = $imginfo['filename'].'.'.$imginfo['extension']; // extract the image filename
$updir = wp_upload_dir(); // get upload directory
$uploadedfile = $updir['path'] . '/' . $filename; // create upload image location & file name
$image= file_get_contents( $imgurl ); // get the image actual content
$saved = fopen($uploadedfile, 'w'); // open the image file
fwrite($saved, $image); // write image conent
fclose($saved); // close image
Your image is now uploaded and stored on wp-content uploads folder, and the exact location is at $uploadedfile
However, the image is still not added on media library as it doesn't have any database entry connected to that image,
Now simply use wp_insert_attachment function to link that image into a database and it will show on media library,
just check that documentation and you'll see an example of linking $uploadedfile file to media library, you can do something like,
$filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$img_id = wp_insert_attachment( $attachment, $uploadedfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $img_id, $uploadedfile );
wp_update_attachment_metadata( $img_id, $attach_data );
can you please check below 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;

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;
}

Front end file upload returning wrong attachment url

So I'm making a simple file uploader with wordpress where users don't need to go into wp-admin to add a file.
I have it working great, it uploads the file to the correct folder..etc but the only problem I'm running into is its returning the wrong file url.
For example when uploading a file it goes to '/wp-content/uploads/2014/01/file.png' but it returns the attachment URL as '/uploads/file.png'
My code:
define('WP_USE_THEMES', false);
require_once($_SERVER['DOCUMENT_ROOT']. '/wp-load.php');
include_once($_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/media.php');
include_once($_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/file.php');
include_once($_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/image.php');
if(!$_FILES) exit;
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
//define variables
if(isset($_FILES['fileUpload']))
{
$files = $_FILES['fileUpload'];
}
$upload_dir = wp_upload_dir();
$file_name = $files['name'];
$file_vars = array('test_form' => FALSE); //Allows form submission
$file_post = wp_handle_upload($files, $file_vars); //Posts File
$file_link = $file_post['url']; //Full URL
$file_type = wp_check_filetype(basename($file_link), null); //File Extension
$post_name = preg_replace('/\.[^.]+$/', '', basename($file_link)); //Post Name
$attachment = array(
'guid' => $file_link,
'post_mime_type' => $file_type['type'],
'post_title' => $post_name,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $file_name);
//Generates meta
$attach_data = wp_generate_attachment_metadata($attach_id, $file_name);
//Updates meta
$attach_final = wp_update_attachment_metadata($attach_id, $attach_data);
Any idea what I'm doing wrong?
I've figured out what I was doing wrong!
Basically when generating attachment metadata I was giving it the wrong path..
I was giving it the path of the actual file '/wp-content/uploads/2014/01/file.png'
but really it needed the path of the folder the file was in '/wp-content/uploads/2014/01/'

Upload base64 encoded images using Facebook sdk?

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.

Categories