Sending File with cURL - php

I've sent some post data with cURL and am now trying to send a file, getting lost along the way. I'm using a form with a file input. Then would like cURL to send it off to my server. Here is my upload page.
<form action="curl_page.php" method="post" enctype="multipart/form-data">
Filename: <input type="file" name="file" id="file" /> <br />
<input type="submit" name="submit" value="Submit" />
</form>
Here is my curl page with some issues.
<?php
$tmpfile = $_FILES['file']['tmp_name'];
$filename = basename($_FILES['file']['name']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://my_server/file_catch.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
?>
The file_catch.php on my server looks like this.
<?php
$folder = "audio/";
$path = $folder . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Thanks for any help!

You are not sending the file that you got through the post request. Use the below code for posting the file through CURL request.
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '#'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)
curl_exec($ch);
For more reference check the below link
Send file via cURL from form POST in PHP

Related

Using cURL how to post a file

I'm using AnonFiles website to upload files directly to my account using their API
https://anonfiles.com/docs/api
I created an account and they gave me a API key, and with this key I can upload straight into my account by appending for example ?token=5846e48082XXXXXX to the upload request.
Request Example
curl -F "file=#test.txt" https://api.anonfile.com/upload
Now i want a simple form with PHP code that allows me to pick a file and upload it to my anonfiles account.
Here is my try to write this request in PHP using cURL function
<?PHP
if (isset($_POST['submit'])) {
$url = 'https://anonfile.com/api/upload?token=5846e48082XXXXXX';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => curl_file_create(
$_FILES['file']['tmp_name'],
$_FILES['file']['type'],
$_FILES['file']['name']
),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$result = json_decode($json);
if (is_object($result) && $result->status) {
echo "OK!";
} else {
echo "Error";
}
}
?>
HTML FORM
<form action="' . $_SERVER['PHP_SELF'] . '" method="post" enctype="multipart/form-data">
File: <input type="file" name="file" id="file">
<br/>
<input type="submit" name="submit" id="submit" value="Send">
</form>
But this seems not working and print out Error message rather than ok and no file is uploaded.
You can do it like this:
<?PHP
if (isset($_POST['submit'])) {
$url = 'https://anonfile.com/api/upload?token=5846e48082XXXXXX';
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "#$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
$json = curl_exec($ch);
$result = json_decode($json);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if ($info['http_code'] == 200) {
if (is_object($result) && $result->status) {
$msg = "OK!";
}
}
}
else
{
$msg = curl_error($ch);
}
curl_close($ch);
}
else
{
$msg = "Please select the file";
}
echo $msg;
}
?>

Download file from url to server

I have this code but it's not working, can someone tell me what to do? I don't know PHP, just started to learn PHP. I'm trying to put url in form and get that file downloaded from url to my server.
$prevod = $_POST['prevod'];
$url = file_get_contents("$prevod");
$fp = fopen("prevodi/", "w");
fwrite($fp, $url);
fclose($fp);
<form action="prevod.php" method="post">
<input name="prevod" type="text"/>
<input type="submit" value="Pronađi"/>
</form>
Try this and please avoid quotes for variables
$prevod = $_POST['prevod'];
$url = file($prevod);
you have to give path before filename then it will work if it was protected then you have to access by curl
$urldata = realpath('../severname/folder/'.$prevod.'');
$fp = fopen('../foldername/subfolder','w');
$newfile = realpath('../foldername/subfolder/'. $prevod .'');
file_put_contents($newfile, $urldata);
<form action="prevod.php" method="post">
<input name="prevod" type="text"/>
<input type="submit" value="Pronađi"/>
</form>
Create prevod.php then add following code. Please create "prevodi" directory also. You can change file name by variable $with_extension. Now it is for gif file.
<?php $ch = curl_init();
$source = $_POST['prevod'];
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$with_extension="filename.gif";
$destination = "prevodi/". $with_extension;
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
?>

PHP cURL setup to send to remote host

I have a few elementary questions about cURL that I can't find answered in the cURL docs (probably because they are obvious to everyone else...). I have a file type input in a form that needs to send that file to a remote server. Does the cURL code go on the page with the form, or is the cURL on the page that the form sends you to, then it gets sent to the remote server?
Here is the form html:
<form action="send.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
The cURL php I have so far which I don't even know if it's correct for what I'm trying to do, or if this goes on the same page or the send.php file the form goes to:
$ch = curl_init("http://remoteServer/upload_file.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CUROPT_POSTFIELDS, array('fileupload' => '#'.$_FILES['theFile'] ['tmp_name']));
echo curl_exec($ch);`
And on the remote server I have this file to receive it:
$folder = "files/";
$path = $folder . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
Is this even remotely close?
you don't need curl to upload a file from a browser, you can submit the form directly to the remote server to upload - just make sure the form submits to whatever file has that third block of code
Try this
$curlPost = array('fileupload' => '#'.$_FILES['theFile'] ['tmp_name']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://remoteServer/upload_file.php');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec();
curl_close($ch);
Another Example
How to upload image file to remote server with PHP cURL
http://www.maheshchari.com/upload-image-file-to-remote-server-with-php-curl/

IMGUR file upload via PHP and cURL

I'm trying to upload an image to IMGUR via PHP.
This is the code:
<?
$filename = "image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'mykey' => IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
?>
This is the error message I receive:
Warning: fopen(image.jpg) failed to open stream: No such file or directory
I don't understand the part: $filename = "image.jpg";
Where does the filename come from since it's a base64 generated string?
Thanks,
Bob
That warning is because fopen is trying to read in the file image.jpg from the directory from which your script is running.
A good example on how to transfer a file through curl can be seen here
Send file via cURL from form POST in PHP
Where they have $localFile = $_FILES[$fileKey]['tmp_name']; you would put $localFile = '/path/to/image.jpg'; As well as change the server info and add in any other variables you may need to pass to imgur.
Change line 1 from:
$filename = "image.jpg";
To:
$filename = $_FILES['uploaded_file']['tmp_name'];
Then, to post... I recommend a form similar to this:
<form enctype="multipart/form-data" method="post" action="upload.php" target="my_iframe">
Choose your file here:
<input name="uploaded_file" type="file"/>
<input type="submit" value="Upload It"/>
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<script language="JavaScript">
<!--
function autoResize(id){
var newheight;
var newwidth;
if(document.getElementById){
newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
}
document.getElementById(id).height= (newheight) + "px";
document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>
<IFRAME name="my_iframe" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>
If you put all your php into upload.php and then have that form on a page in the same directory, it's pretty close to being functional... Except you don't yet have an API_KEY in your source.
You can get an API KEY here: https://imgur.com/register/api_anon
In the end your php should look like this:
<?
if( isset($_FILES['uploaded_file']) )
{
$IMGUR_API_KEY = 'u432ewriuq3oirefuie'; //put your api key here
$filename = $_FILES['uploaded_file']['tmp_name'];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
//$data is file data
$pvars = array('image' => base64_encode($data), 'key' => $IMGUR_API_KEY);
#$pvars = array('key' => $IMGUR_API_KEY);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
#curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/gallery.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
$xmlsimple = new SimpleXMLElement($xml);
echo '<img height="180" src="';
echo $xmlsimple->links->original;
echo '">';
curl_close ($curl);
}
?>

Twitter API -> updating profile bg image with php

So far I have been trying to update the twitter profile bg image thr the twitter api with php... and without success
Many examples on the web, including this one:
Updating Twitter background via API
and this one
Twitter background upload with API and multi form data
do not work at all, most ppl throw out answers without actually testing the code.
I found that directly submit the image to the twitter.com thr html form, it will work:
<form action="http://twitter.com/account/update_profile_background_image.xml" enctype="multipart/form-data" method="post">
File: <input type="file" name="image" /><br/>
<input type="submit" value="upload bg">
</form>
(although the browser will prompt you for the twitter account username and password)
However, if I want to go thr the same process with php, it fails
<?php
if( isset($_POST["submit"]) ) {
$target_path = "";
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
// "The file ". basename( $_FILES['myfile']['name']). " has been uploaded<br/>";
} else{
// "There was an error uploading the file, please try again!<br/>";
}
$ch = curl_init('http://twitter.com/account/update_profile_background_image.xml');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, $_POST['name'] . ':' . $_POST['pass']);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode(file_get_contents($target_path))));
$rsp = curl_exec($ch);
echo "<pre>" . str_replace("<", "<", $rsp) . "</pre>";
}
?>
<form enctype="multipart/form-data" method="post">
<input type="hidden" name="submit" value="1"/>
name:<input type="text" name="name" value=""/><br/>
pass:<input type="password" name="pass" value=""/><br/>
File: <input type="file" name="myfile" /><br/>
<input type="submit" value="upload bg">
</form>
The strange thing of this code is that.. it successfully returns the twitter XML, WITHOUT having the profile background image updated. So at the end it still fails.
Many thanks for reading this. It will be great if you can help. Please kindly test your code first before throwing out answers, many many thanks.
This is what works for me (debug stuff left in):
$url = 'http://twitter.com/account/update_profile_background_image.xml';
$uname = 'myuname';
$pword = 'mypword';
$img_path = '/path/to/myimage.jpg';
$userpwd = $uname . ':' . $pword;
$img_post = array('image' => '#' . $img_path . ';type=image/jpeg',
'tile' => 'true');
$opts = array(CURLOPT_URL => $url,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $img_post,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => $userpwd,
CURLOPT_HTTPHEADER => array('Expect:'),
CURLINFO_HEADER_OUT => true);
$ch = curl_init();
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
$err = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
echo $err . '<br />';
echo '----------------' . '<br />';
print_r($info);
echo '----------------' . '<br />';
echo htmlspecialchars($response) . '<br />';
echo '</pre>';
Have you confirmed that the image you expect is present and being sent (i.e. echo out the base64 encoded data for verification)? Is it GIF/PNG/JPG and under the 800 kilobyte limit set by the API?
I think you're using the CURLOPT_POSTFIELDS method wrong. You need to put and # sign in front of the full path to the file according to the documentation for curl PHP. You are not supposed to output the whole file contents.
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.
This is an example from the documentation.
<?php
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
I hope this helps.
Right now no one can actualy update the profile background image nor the profile image.
Twitter is working to fix that issue till then there is no fix.

Categories