Facebook PHP upload file from memory - php

I'm reading an image from my S3 bucket in AWS and want to upload it to Facebook.
This is the reading function:
/**
* Get a file from the s3 storage
*/
private function uploadPicture() {
$picture = new FacebookPicture();
$file = $this->s3Manager->getFile($this->subEndPoint,$this->verb);
$picture->pictureContent = $file["Body"];
$facebookAlbum = new FacebookAlbum();
$facebookAlbum->album = new Album();
$facebookAlbum->album->facebookAccessToken = "myAccessToken";
$facebookAlbum->id = "myAlbumId";
$facebookManager = new FacebookManager();
$facebookManager->uploadPicture($facebookAlbum,$picture);
}
This is the uploading to Facebook function
/**
* #param $facebookAlbum FacebookAlbum the album to upload the picture to
* #param $picture FacebookPicture the picture to upload
*/
public function uploadPicture($facebookAlbum,$picture)
{
$this->facebook->setAccessToken($facebookAlbum->album->facebookAccessToken);
$this->facebook->setFileUploadSupport(true);
$args = array();
$args["message"] = $picture->description;
$args["source"] = "#" . $picture->pictureContent;
$data = $this->facebook->api('/'. $facebookAlbum->id . '/photos', 'post', $args);
var_dump($data);
}
I keep getting :
curl_setopt_array(): The usage of the #filename API for file uploading is deprecated. Please use the CURLFile class instead in <b>acebook-php-sdk-master/src/base_facebook.php</b> on line <b>1005</b><br />
I think that the problem is that the image content is saved in the memory.
How can I use the variable in my memory in order to post it to Facebook ?

#filename has been deprecated in PHP >= 5.5.0 as stated here under the CURLOPT_POSTFIELDS description , So thats the reason why you got the error .
you have your answer here at this stack overflow thread, where different solutions are discussed . Also here is a snippet from RFC for the code.
Currently, cURL file uploading is done as:
curl_setopt($curl_handle, CURLOPT_POST, 1);
$args['file'] = '#/path/to/file';
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $args);
This API is both invonvenient and insecure, it is impossible to send
data starting with '#' to the POST, and any user data that is being
re-sent via cURL need to be sanitized so that the data value does not
start with #. In general, in-bound signalling usually vulnerable to
all sorts of injections and better not done in this way.
Instead of using the above method, the following should be used to
upload files with CURLOPT_POSTFIELDS:
curl_setopt($curl_handle, CURLOPT_POST, 1);
$args['file'] = new
CurlFile('filename.png', 'image/png'); curl_setopt($curl_handle,
CURLOPT_POSTFIELDS, $args);

Related

php telegram sendPhoto not working (url & file location)

I need some help if possible with php sendPhoto api, I've been using the sendPhoto method in php on my apache server to auto send images into telegram, I've been using this same method for almost 6-7 months and from few days ago suddenly the api method stopped working. I tried passing photo= using the absolute path of file in url and in php using the files directory+filename but sends me an error msg from the api as shown below, first part is my php method which doesnt return any errors, just shows blank
# my php telegram code
$dir = "Attachments/2022/04/09/imagename.jpeg";
$chat_id = '(groupchatid)';
$bot_url = "https://api.telegram.org/bot(mybotapi)/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id ;
$post_fields = array('chat_id' => $chat_id,
'photo' => new CURLFile(realpath($dir)),
'caption' =>'Test Image', );
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type:multipart/form-data" ));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
When i execute this script as it used to work before recently this is the response i get from the API
{
"ok": false,
"error_code": 400,
"description": "Bad Request: invalid file HTTP URL specified: Unsupported URL protocol"
}
If I replace the image URL to another server it send the image successfully, but im unable to send anything only from my server, If I try access the file directly using the URL of my servers image file I can access it from any pc no issue, only problem is telegram fetching the image, please help, appreciate it
Excuse, I don't usually use curl, so I can give you another option:
function sendPhoto($id, $photo, $text = null){
GLOBAL $token;
$url = 'https://api.telegram.org/bot'.$token."/sendPhoto?
chat_id=$id&photo=$photo&parse_mode=HTML&caption=".urlencode($text);
file_get_contents($url);
}
Just declare the sendPhoto function in this way, put the variabile in which you stored the token instead of "$token" and use the parameters in this way:
$id = the id of the user (the one you declared like this: $id = $update['message']['from']['id'];)
$photo = absolute path of the image you want to send
$text = OPTIONAL caption for the image

Need to retrieve the uploaded image from folder and send the image as form data to api

I have uploaded an image to a local folder using the below code using ajax and php after some cropping and image zooming functionality.
After this function, the cropped image is sanded to a local folder called upload. But the image is processed with base64 encode and decode model. I want to send the cropped/saved image to an api with out base64 data all I want is send the image as form data/file.
The code that used for image upload is image data is sent as form data and is base64 encoded format
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function(){
var base64data = reader.result;
formData.append('image', base64data);
$.ajax({
url:'<?php echo get_template_directory_uri(); ?>/upload.php?>',
method:'POST',
data:formData
and in upload.php
if(isset($_REQUEST['image'])) {
$data = $_REQUEST['image'];
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$image_name = 'upload/' . time() . '.png';
file_put_contents($image_name, $data);
}
i want to take this image from folder and send this data to an api as file/multipart formdata with out encryption/decrypted format
Please help me to solve this. Thank you in advance.
Once you have the image on your drive you can use curl with curlFile option for the purpose. Docs for curl and curlFile
From the docs you can see its usage
/**
* #param string $file -> full file path
* #return CURLFile
*/
function makeCurlFile($file)
{
## Create the curl file for upload
$mime = mime_content_type($file);
$info = pathinfo($file); # or simply use $name = basename($file);
$name = $info['basename'];
$output = new CURLFile($file, $mime, $name);
return $output;
}
$file = '/path/to/your/upload/directory/picture.png';
$ch = curl_init("https://example.com/api_url");
$photo = makeCurlFile($file);
## Construct your post data in an array
$postData = [
'fileObject' => $photo, # fileObject is the name of the file which your api is expecting
'desc' => 'your custom description' # Any other field that need to be sent along with the file, use as many needed
];
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$result = curl_error($ch);
}
curl_close($ch);
Note:
This applies to php >= 5.5.0. For versions prior to that you cannot use curlFile and need to use # and build the body of the content manually. Read this answer or here to see how its done.
I have not set the Content-Type header. cUrl appends this header automatically as it deems fit. At least in my case whenever we ask curl to post an array it uses the Content-Type multipart/form-data. If there is an issue you will need to check headers are setup correctly.
CURLOPT_SAFE_UPLOAD A comment in the docs (here) suggest we set the CURLOPT_SAFE_UPLOAD to true for all versions >= 5.5. However, the docs is silent on the issue except this page. So I am assuming the default for this for versions >= 5.6 is true and hence you do not need to explicitly set it when using curlFile. For at least php 7.2 I can confirm it works without setting this to true.
Uploads using the #file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to false. CURLFile should be used instead.
Make use of curl_error and curl_getinfo to debug

Convert image to pdf php

I am using csxi to make scanning for documnets as image, but I have to upload pdf files to server. How can I convert image to PDF in php ? or is there any way to make csxi scan documents as PDF not image
If you have ImageMagick installed on your machine you could use the ImageMagick bindings for PHP to execute some simple PHP code to do this task:
$im=new Imagick('my.png');
$im->setImageFormat('pdf');
$im->writeImage('my.pdf');
Alternatively if you don't have ImageMagick available you could use a commercial API such as Zamzar which supports image to PDF conversion via PHP (more info in the docs).
Code to use this would be:
<?php
// Build request
$endpoint = "https://api.zamzar.com/v1/jobs";
$apiKey = "YOUR_API_KEY";
$sourceFilePath = "my.png";
$targetFormat = "pdf";
$sourceFile = curl_file_create($sourceFilePath);
$postData = array(
"source_file" => $sourceFile,
"target_format" => $targetFormat
);
// Send request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);
// Process response (with link to converted files)
$response = json_decode($body, true);
print_r($response);
?>
Wrap your image inside HTML and use some HTML to PDF converter like fpdf or mpdf
You can use convertapi service, easy to install:
composer require convertapi/convertapi-php
require_once('vendor/autoload.php');
use \ConvertApi\ConvertApi;
//get api key: https://www.convertapi.com/a/si
ConvertApi::setApiSecret('xxx');
$result = ConvertApi::convert('pdf', ['File' => '/dir/test.png']);
# save to file
$result->getFile()->save('/dir/file.pdf');
to convert multiple files and other options check https://github.com/ConvertAPI/convertapi-php
Here, Php 7.4, Laravel 7+, ImageMagick-7.1.0-Q16, and Ghostscript gs10.00.0 is used.
If any files are contained in the folder JpgToPdf then delete them. And so on.
/**
* jpg To pdf WEB
*
* #method convertJpgToPdf
*/
public function convertJpgToPdf(Request $request)
{
try {
//get list of files
$files = Storage::files('JpgToPdf');
/*get count of files and ,
* check if any files contain
* if any files contains
* then
* get the files name
* delete one by one
*/
if(count($files) >1 )
{
foreach($files as $key => $value)
{
//get the file name
$file_name = basename($value);
//delete file from the folder
File::delete(storage_path('app/JpgToPdf/'. $file_name));
}
}
if ($request->has('jpeg_file'))
{
$getPdfFile = $request->file('jpeg_file');
$originalname = $getPdfFile->getClientOriginalName();
$path = $getPdfFile->storeAs('JpgToPdf', $originalname);
}
// file name without extension
$filename_without_ext = pathinfo($originalname, PATHINFO_FILENAME);
//get the upload file
$storagePath = storage_path('app/JpgToPdf/' . $originalname);
$imagick = new Imagick();
$imagick->setResolution(300, 300);
$imagick->readImage($storagePath);
$imagick->setImageCompressionQuality( 100 );
$imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$imagick->writeImage( storage_path('app/JpgToPdf/') . $filename_without_ext .'.pdf' );
return response()->download(storage_path('app/JpgToPdf/') . $filename_without_ext .'.pdf' );
} catch (CustomModelNotFoundException $exception) {
// Throws error exception
return $exception->render();
}
}
For just a few images, do it manually and easily with the Chrome web browser. You wont need an internet connection.
Save the following with .html extension in the same folder of your image:
<html>
<body>
<img src="image.jpg" width="100%">
</body>
</html>
Open the html file with Google Chrome,
Crtl + P, to open the print dialog
Choose Save as PDF, to save it locally
Alternatively, you could send a copy to your smatphone via Google Cloud Print

PHP Upload Image from URL to Facebook [duplicate]

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

PHP - Upload a web hosted photo to facebook album via Graph API

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

Categories