File Upload to Slim Framework using curl in php [duplicate] - php

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Failing to upload file with curl in heroku php app
After handling a file upload in php, I am trying to send that file using curl to my rest api which uses Slim Framework. However, $_FILES is always empty once it reaches the function in Slim.
sender.php
if(move_uploaded_file($_FILES['myFile']["tmp_name"], $UploadDirectory . $_FILES['myFile']["name"] ))
{
$ch = curl_init();
$data = array('name' => 'test', 'file' => $UploadDirectory . $_FILES['myFile']["name"]);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/slimlocation/upload/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
}
And the function to receive the request in Slim:
$app->post('/upload/', function() use ($app) {
if(isset($_FILES)){
// count is always zero
echo count($_FILES);
}
});
Am I sending the file incorrectly and / or is it possible to do what I am attempting? Any help is appreciated.

As far as i know, you need to use more options for a file upload with curl. See here.
Look at the CURLOPT_UPLOAD option and the description of CURLOPT_POSTFIELDS, it says that you need to use an # before the file name to upload (and use a full path).

These were the changes I needed and it worked:
$filepath = str_replace('\\', '/', realpath(dirname(__FILE__))) . "/";
$target_path = $filepath . $UploadDirectory . $FileName;
$data = array('name' => 'test', 'file' => '#'.$target_path);

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

Is there a simple way to verify if a file has been uploaded correctly to Amazon S3?

I use the tpyo Amazon S3.php class from https://github.com/tpyo/amazon-s3-php-class to upload files like this:
# START AMAZON S3
$s3 = new S3('KEY', 'SECRET');
$uploadfile = 'user-' . $uid . '/' . $new_file;
S3::putObject(
S3::inputFile('/home/username/www/images/'.$uid.'/'.$file_name, false),
'bucketname',
$uploadfile,
S3::ACL_PUBLIC_READ,
array(),
array(),
S3::STORAGE_CLASS_STANDARD
);
#END AMAZON S3
I've noticed that out of maybe 10,000 files that are uploading, it fails to upload maybe 10 or 20 for various reasons like network problems, server problems, etc. Is there any way to easily verify if the file has been uploaded correctly?
The solution I found is to grab the image with a class like this:
function ranger($url){
$headers = array(
"Range: bytes=0-983040"
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
And then check the dimensions of the image and know it exists if the width and the height are >1, but this method is really slow especially for big images.
I see no class built into the tpyo S3.php file to verify if the file exists. Anybody has a better idea?
Thanks :)
I'm so stupid. There's an option called getObjectInfo.

Upload script returning blank data

I have the Uploadify jQuery plugin set up on my site to manage file uploads. Within the onUploadSuccess event, I have this code:
'onUploadSuccess' : function(file, data, response) {
console.log("Upload complete for file " + file.name + ". Script returned: " + data);
}
This is meant to show me whatever the upload script spits out. Now, usually the response is something like this:
Upload complete for file test.jpg. Script returned:
{"status":1,"file":{"id":"v8rwlxj3","name":"test.jpg"}}
The upload script is first accepting the file, then uploading it to Rapidshare using cURL like so:
// Move uploaded file
move_uploaded_file($_FILES['Filedata']['tmp_name'], $targetDir . '/' . $id);
// Get the RapidShare server to upload to
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=nextuploadserver');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(!$uploadServer = trim(curl_exec($ch))) {
error('nextuploadserver failed');
}
if(strstr($uploadServer, 'ERROR:')) {
error('nextuploadserver failed');
}
// Upload the file to RapidShare
$uploadID = mt_rand(1000000000, 9999999999);
$url = 'http://rs' . $uploadServer . '.rapidshare.com/cgi-bin/rsapi.cgi?uploadid=' . $uploadID;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
$postFields = array('sub' => 'upload',
'login' => 'login',
'password' => 'password',
'uploadid' => $uploadID,
'filename' => $_FILES['Filedata']['name'],
'filecontent' => '#' . $targetDir . '/' . $id);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
if(!$resp = curl_exec($ch)) {
error('upload call failed');
}
when it's uploaded, the upload script spits out a JSON response like so:
// Output
echo json_encode(array('status' => 1, 'file' => array('id' => $id, 'name' => $uploadDetails[1])));
This works fine for smaller files. When I upload my 30MB test file however, I get this response:
Upload complete for file 30mb.txt. Script returned:
At first I thought PHP was hitting the max execution time, but I have this at the top of my script:
set_time_limit(21600); // 6 hours
And besides, I'd see the PHP error being returned. But it's just not returning anything. What could cause this? Thanks.
Are you sure your upload_max_filesize is set to above 30M? That one has caused me some headaches in the past.
PHP may be not hitting time limit, but ajax may be reaching connection timeout while waiting for the response.
Remove uploadid post parameter. Uploadid parameter with resume upload.
Yes nice answer, although it was in comment but helped me.
http://www.uploadify.com/documentation/uploadify/successtimeout/
set successTimeout to some high value. lets say 1 hour.

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).

how to send / get files via web-services in php

is this possible ?
what is the correct way to send files ?
thanks
I don't if you want your webservice to upload/download files. Anyway you can use curl(http://fr.php.net/curl ) to upload/download file from other webserver.
To get some file uploaded to the webservice from the user it's pretty much the same as gettings it from a form, please use the superglobal variable:$_FILES (doc) to get upload files.
for uploading from php to a webservice
$fullflepath = 'C:\temp\test.jpg';
$upload_url = 'http://www.example.com/uploadtarget.php';
$params = array(
'photo'=>"#$fullfilepath",
'title'=>$title
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);
the webservice to get a file
$uploads_dir = '/uploads';
foreach ($_FILES["photo"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["photo"]["tmp_name"][$key];
$name = $_FILES["photo"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
PS: sorry for some reason stackoverflow doesn't like to make a link of $_FILES ... so I have linked the superglobals page instead
You use this php program based on nusoap : http://biclim.com/WSClients.action
You can debug the response of your php service and check the file upload from iphone using this app - http://itunes.apple.com/us/app/rest-client/id503860664?ls=1&mt=8
It was really helpful to debug serverside code.
Hello Here Example Image upload
<?php
$path="aa/";// Set your path to image upload
if(!is_dir($path)){
mkdir($path);
}
$roomPhotoList = $_POST['image'];
$random_digit=date('Y_m_d_h_i_s');
$filename=$random_digit.'.jpg';
$decoded=base64_decode($roomPhotoList);
file_put_contents($path.$filename,$decoded);
?>
it can be quick image upload code in php for ios and android

Categories