Uploading Photos from Hard Drive to Facebook using the API - php

wondering if anyone can help me. I've been searching for a few days for help on how to publish photos to Facebook using the API. I came across the following script that seems to work for everyone however I am unsure how to connect this to a form where users can select the photo from their hard drive and upload it. Can anyone point me in the right direction?
PHP Code:
$token = $session['access_token'];
$file= 'photo.jpg';
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos?access_token='.$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);
Code for the form:
<form action="<?=$PHP_SELF;?>" enctype="multipart/form-data" method="POST">
<input name="MAX_FILE_SIZE" type="hidden" value="10000000" />
<input id="file" name="file" type="file" />
<input name="submit" type="submit" value="Upload" />
</form>

Clark,
The php script receives the file and its details in the $_FILES variable.
For Eg. If you are uploading a file names Image1.jpg then the $_FILES array would have the following values
array(1) {
["file"]=> array(5) {
["name"]=> string(21) "Image1.jpg"
["type"]=> string(10) "image/jpeg"
["tmp_name"]=> string(23) "C:\wamp\tmp\phpD1DF.tmp
["error"]=> int(0)
["size"]=> int(355315)
}
}
Here, name = actual file name
type = file type
tmp_name = path of the temp location where the file is uploaded on the server
size = file size
For uploading the file to facebook the values that you should be interested in the "name" and the "tmp_name".
So the arguments that you should send to facebook for the photo upload should look something like this
$args = array(
'message' => 'Photo from application',
);
$args[$_FILES['file']['name']] = '#' . $_FILES['file']['tmp_name'];
I think this should work for you.
Btw, i checked out the facebook doc for photo upload # http://developers.facebook.com/docs/reference/api/photo they say the file name should be passed in the param "source", so if the above arguments dont work for you, you can try
$args = array(
'message' => 'Photo from application',
'source' => '#' . $_FILES['file']['tmp_name']
);
Give it a try :)
Hope this helps.

Related

fetching imgur cURL to json_decode php upload form

i'm trying to use imgur as a uploading backend - i guess it secure my website if there's upload picture (is it right?) so
i went with this way :
<?php
$client_id = 'xxxxx';
$file = file_get_contents($_FILES["imgupload"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
if ($error = curl_error($curl)) {
die('cURL error:'.$error);
}
$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;
curl_close ($curl);
?>
HTML form
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="imgupload" /><br>
<input type="submit" value="Upload to Imgur" />
</form>
when i click on submit the result is fine as i guess ^^
Result: {"data":{"id":"TvFtE29","title":null,"description":null,"datetime":1585015712,"type":"image\/png","animated":false,"width":900,"height":940,"size":48902,"views":0,"bandwidth":0,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":0,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"Z9xFH8mrSH8lRDB","name":"","link":"https:\/\/i.imgur.com\/TvFtE29.png"},"success":true,"status":200}
but my problem i want to collect the https://i.imgur.com/TvFtE29.png into specific variable like $uploaded = 'https://i.imgur.com/TvFtE29.png'; to added into my database -> user pic
i went with json_decode but it's not completed with me in the right way, if someone can help with this issue 🌹
thanks.
json_decode worked fine here:
$json_returned = json_decode($json_returned, true);
$uploaded = $json_returned['data']['link'];

CURLOPT_POSTFIELDS array of folder content

i'm making a curl post to Google text to speech. I have a set of .flac files, that i want to send to Google Text to Speech service, in order to have the content wrote in a txt file.
This is the code i wrote to do this and it works:
$url = 'https://www.google.com/speech-api/v2/recognize?output=json&lang=it-IT&key=xxx';
$cont2 = array(
'flac/1.flac',
'flac/2.flac',
'flac/3.flac'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: audio/x-flac; rate=44100'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
foreach ($cont2 as $fn) {
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($fn));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
//var_dump($info);
if ($result === false) {
die(curl_error());
}else{
echo "<br />".$fn." upload ok"."<br />";
file_put_contents("pum.txt", $result, FILE_APPEND);
}
}
It works like a charm, in the "pum.txt" i have all the file content wrote and it's ok.
My problem is that i don't want to add to the the array "cont2", each time, the new name o the files i need to pass to, that there are in the "flac folder".
To avoid that, i use "scandir" method, remove "." and ".." string from the array and give that array to the CURL_OPT_POSTFIELD, but the call to GTT return a empty content.
This is the code i wrote to do that (instead $cont2 array)
$directory = 'flac/';
$cont = array_diff(scandir($directory), array('..', '.', '.DS_Store'));
Print_r of that is the same as $cont2 array:
array(3) {
[3]=>
string(6) "1.flac"
[4]=>
string(6) "2.flac"
[5]=>
string(6) "3.flac"
}
But Google TTS return empty result.
Does anyone please tell me where i'm making mistake?
Kind Regards
Brus
EDIT: use "$cont = glob("$directory/*.flac");" solved the issue. Hope help some others.
scandir() won't include full path information - it'll only return filenames. SO when you're building your array of filenames to loop on and send to google, you'll have to include that directories yourself.
e.g.
$dir = 'flac';
$files = scandir($dir);
foreach($files as $key => $file);
$files[$key] = $dir . '/' . $file;
}
e.g. scan dir will return file1.flac, but you need to have flac/file1.flac. Since you're not including the path information, you're trying to do file_get_contents() on a filename which doesn't exist, and are sending a boolean false (file_get failed) over to google.
As Marc B states you need the directory to the files which is missing. I would just use glob as it will return exactly what you need:
$cont = glob("$directory/*.flac");

File not getting uploaded through curl in php

I have an HTML code that allows me to upload the file successfully in server.
<form action="http://aa.bb.ccc.dd/xxx/upload.php" method="post" enctype="multipart/form-data">
<label for="text">Campaign:</label>
<input type="text" name="campaign" value="abcde" readonly="readonly"/><br/>
<label for="file">Upload type:</label>
<input type="text" name="filename" value="0.csv" readonly="readonly"/><br/>
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/><br/>
<input type="submit" name="submit" value="Submit" />
</form>
I am writing an equivalent code in php to upload a file via curl. But the file does not get uploaded. Can anyone please help me on this. My php server code is as follows:
<code>$target_url = 'http://aa.bb.ccc.dd/xxx/upload.php';
$file_name_with_full_path = realpath('./upload/abc.txt');
$post = array('campaign' => 'abcde','file'=>'#'.$file_name_with_full_path,'filename'=>'5.csv');
$header = array('Content-Type: multipart/form-data');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
echo "Result: ".$result."\n";</code>
The result also gives 1, but the file is not uploaded when I check in the server. What is that I am missing?
Any help would be greatly appreciated!
I am interested in using PHP 'cURL'. This looks like a fairly standard requirement.
I looked at some of the 'cURL PHP examples on the web'.
Actually, using the code you have posted, there isn't anything really amiss that i can see.
Whatever, i have used your code and created similar scripts. Alas, you didn't post your 'upload.php' script. I have created one that does validation as mentioned in the PHP manual: http://www.php.net/manual/en/features.file-upload.php.
Although this example is for a 'localhost'. I have run it using a ' real' external host and it works fine.
Tested on PHP 5.3.18 on windows and Linux with PHP 5.3.28.
The Html form, was some confusion with labels as regards 'for':
<form action="process_uploaded_file.php" method="post" enctype="multipart/form-data">
<label for="text">Campaign:</label>
<input type="text" name="campaign" value="abcde" readonly="readonly"/><br/>
<label for="filetype">Upload type:</label>
<input type="text" name="filetype" value="0.csv" readonly="readonly"/><br/>
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/><br/>
<input type="submit" name="submit" value="Submit" />
</form>
cURL Script:
<?php
$target_url = 'http://localhost/testmysql/process_uploaded_file.php';
$full_path_to_source_file = __DIR__ .'/sourcefiles/testupload1.csv' ;
$post = array('campaign' => 'abcde', 'file'=>'#'. $full_path_to_source_file, 'filename' => 'curl1.csv');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
var_dump($result);
Notice, no special 'enctype' header was required. Used the 'RETURNTRANSFER' option explicitly although the information was returned anyway.
Process Uploaded File script:
Implements a lot of recommended checks.
<?php session_start();
define('BIGGEST_FILE', 256 * 1024); // max upload file size
define('UPLOAD_DIRECTORY', 'P:/developer/xampp/htdocs/uploadedfiles'); // my data upload directory
if (empty($_FILES)) { // process the uploaded file...
die('no input file provided... '. __FILE__.__LINE__);
}
/* */
// validate the data -- see http://www.php.net/manual/en/features.file-upload.php
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if ( !isset($_FILES['file']['error'])
|| is_array($_FILES['file']['error'])) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['file']['error'] value.
switch ($_FILES['file']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// You should also check filesize here.
if ($_FILES['file']['size'] > BIGGEST_FILE) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['file']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $_FILES['file']['tmp_name']);
/* */
if (false === $fileExt = array_search($mimeType,
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'csv' => 'text/plain',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// check 'campaign' for safe in filename...
if (preg_match('/\w/', $_POST['campaign']) !== false) {
$campaign = $_POST['campaign'];
}
else {
$campaign = md5($_POST['campaign']); // sort of useful
}
// Now move the file to my data directory
// You should name it uniquely.
// DO NOT USE $_FILES['file']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its 'campaign' and 'tmp_name'.
$destFilename = sprintf('campaign_%s_%s.%s',
$campaign,
sha1_file($_FILES['file']['tmp_name']),
$fileExt);
if (!move_uploaded_file($_FILES['file']['tmp_name'],
UPLOAD_DIRECTORY .'/'. $destFilename)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo $_FILES['file']['tmp_name'], ' uploaded to: ', UPLOAD_DIRECTORY .'/'. $destFilename;
} catch (RuntimeException $e) {
echo $e->getMessage();
}

PHP: Uploading multiple images to imgur at once

I've got the following code and it works perfectly fine for uploading one image to Imgur using their API:
$client_id = $myClientId;
$file = file_get_contents($_FILES["file"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
$json_returned = curl_exec($curl); // blank response
$json = json_decode($json_returned, true);
curl_close ($curl);
However I need to upload multiple images at once. On the client side, the user will have multiple <input type="file" /> fields. I'm completely stuck now with figuring out where and how I will need to modify this code in order to handle multiple image upload when they come through to the server in the form of an array. Does anyone have any ideas?
Change the markup as follows:
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="file[]" type="file" multiple="multiple" /><br />
<input type="submit" value="Send files" />
</form>
Now, you can loop through the $_FILES array using a foreach, like so:
foreach ($_FILES['file']['tmp_name'] as $index => $tmpName) {
if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
{
// $tmpName is the file
// code for sending the image to imgur
}
}

Multiple file uploads with cURL

I'm using cURL to transfer image files from one server to another using PHP. This is my cURL code:
// Transfer the original image and thumbnail to our storage server
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://' . $server_data['hostname'] . '.localhost/transfer.php');
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
'upload[]' => '#' . $tmp_uploads . $filename,
'upload[]' => '#' . $tmp_uploads . $thumbname,
'salt' => 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$resp = curl_exec($ch);
This is the code in transfer.php on the server I'm uploading to:
if($_FILES && $_POST['salt'] == 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q')
{
// Save the files
foreach($_FILES['upload']['error'] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
move_uploaded_file($_FILES['upload']['tmp_name'][$key], $_FILES['upload']['name'][$key]);
}
}
}
All seems to work, apart from one small logic error. Only one file is getting saved on the server I'm transferring to. This is probably because I'm calling both images upload[] in my post fields array, but I don't know how else to do it. I'm trying to mimic doing this:
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
Anyone know how I can get this to work? Thanks!
here is your error in the curl call...
var_dump($post)
you are clobbering the array entries of your $post array since the key strings are identical...
make this change
$post = array(
'upload[0]' => '#' . $tmp_uploads . $filename,
'upload[1]' => '#' . $tmp_uploads . $thumbname,
'salt' => 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q'
);
The code itself looks ok, but I don't know about your move() target directory. You're using the raw filename as provided by the client (which is your curl script). You're using the original uploaded filename (as specified in your curl script) as the target of the move, with no overwrite checking and no path data. If the two uploaded files have the same filename, you'll overwrite the first processed image with whichever one got processed second by PHP.
Try putting some debugging around the move() command:
if (!move_uploaded_file($_FILES['upload']['tmp_name'][$key], $_FILES['upload']['name'][$key])) {
echo "Unable to move $key/";
echo $_FILES['upload']['tmp_name'][$key];
echo ' to ';
echo $_FILES['upload']['name'][$key];
}
(I split the echo onto multiple lines for legibility).

Categories