I'm trying to send a .txt file via php curl post request to get its contents but no success.
The point is that if I make a var_dump($_FILES) as $result being $result the curl_exec($ch) response it shows me an empty array but if I try it with $_POST:
array(
[uploaded_file] =>
[name] => 'absolute/path/to/file.txt'
[mime] => 'text/plain'
[postname] => 'file.txt'
)
How can I pass that file as a $_FILES variable?
This is my curl send.php curl script:
$filedata = curl_file_create('../path/to/file.txt', 'text/plain', 'file.txt');
$array = array(
'file' => $filedata
)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://domain_name.com/url/to/script.php');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
$result = curl_exec($ch);
curl_close($ch);
This is the receive.php script:
if(file_exists($_FILES['uploaded_file']['tmp_name']) && is_uploaded_file($_FILES['uploaded_file']['tmp_name'])){
$contents = file_get_contents($_FILES['uploaded_file']['tmp_name']);
$data = explode('/',$contents);
}
but it's never entering the if statement...
You can't pass the file via cURL to make it appear in the $_FILES variable.
That is because the $_FILES variable is used for uploaded files using an HTML form submission.
For security reasons, the file must be encrypted first, and decrypted in the receiver page.
I suggest you to use an encryption method that let you to choose the encryption's key, such as sha1.
You can find more informations here: https://stackoverflow.com/a/15200804/2342558
Related
I have created a file on bluehost server test.php and used this file send curl request from another server ( godaddy ).
$url = 'http://dev.testserver.com/test.php';
$data_string = json_encode($fields);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS,$data_string );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
How to capture posted data on test.php and process it ?
I am trying with $_POST but its showing blank.
The question is close to this one How to send raw POST data with cURL? (PHP)
I've slightly modified your client code to follow recommendations:
<?php
$fields = ['a' => 'aaaa', 'b' => 'bbbb'];
$url = 'http://localhost/test.php';
$data_string = json_encode($fields);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, urlencode($data_string));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$curl_response = curl_exec($curl);
echo 'Response: '.$curl_response.PHP_EOL;
I do urlencode for the sent data and set headers.
The logic how to read data is explained in the question How to get body of a POST in php? I made a simple test.php file with the following code
<?php
$body = file_get_contents('php://input');
if (!empty($body)) {
$data = json_decode(urldecode($body), true);
var_export($data);
}
We read the data, decode it and parse JSON.
As one might expect the test output from the client script is the following
$ php client.php
Response: array (
'a' => 'aaaa',
'b' => 'bbbb',
)
Try to replace this, direct send array not json
curl_setopt($curl, CURLOPT_POSTFIELDS,$data_string );
With
curl_setopt($curl, CURLOPT_POSTFIELDS,$fields );
Check this : http://php.net/manual/en/function.curl-setopt.php
With curl from linux bash I can download a webpages passing some variables
curl --data "var1=val1&var2=val2&var3=&var4=val4&btnSubmit=btnName" https://<url> -o "<fileToSave>"
I need to do the same things but to get the full html code of that page into a php variable.
I'm trying with this:
<?php $ch = curl_init();
$post_data = array (
"var1" => "val1",
"var2" => "val2",
"var3" => "",
"var4" => "val4",
"btnSubmit" => "btnName"
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
?>
The problem is that from bash I can retrieve the html pages and save it with this code my $response value is empty.
What's wrong?
Use http_build_query() over the $post_data, otherwise curl will assume to POST multipart/form-data posting based on the Array Data type(that's why it is not working for you).
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
http_build_query() converts the array into key1=value1&key2=value2 formated string with automatic urlencode().
Seems like you are connecting to a HTTPs URL. You should enable this cURL parameter.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
I'm trying to post a photo to Foursquare API using the /photos/add method, and I'm having a little difficulites. I either get a 401 (missing file) or 502 (foursquare is down). Here is my code:
$ch = curl_init();
// file image name and it's located in the same folder
$image = "cupcakes.jpg";
// I've tried all of these and no luck
$s = array("file" => "#".$image, "photo" => "#".$image, "image" => "#".$image);
// I've also tried to send raw data:
//curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($image));
$url = "https://api.foursquare.com/v2/photos/add?oauth_token=TOKENHERE&checknId=4fecf6abe4b0369bc7389903";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $s);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// image/jpeg type
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: image/jpeg"));
$result = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// I get either 502 / 401 (Foursquare is down or File is missing)
echo $result;
Anyone have any idea what I'm doing wrong? The documentation for the endpoint is here: https://developer.foursquare.com/docs/photos/add -- in particular it implies that the photo data should be body of the POST request?
I've fixed the problem, turns out the param that you need to send to foursquare is "photo". All the other params must be included in the POST array as well.
Even though the content-type is requested as "image/jpeg", I've just put in "Except:" and it works fine. I'm not 100% sure why that goes through, but it does. Updated code below:
$s = array("photo" => "#".$image, "checkinId" => "4fecf6abe4b0369bc7389903");
$url = "https://api.foursquare.com/v2/photos/add?oauth_token=TOKENHERE&v=20120609";
.....
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
Everything else can stay the same. Happy posting!
I am trying to pass a json data as param for cURL POST. However, I am stuck at grabbing it and saving it on db.
cURL file:
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$url = 'http://localhost/project/test_curl';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
//based on http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl
test_curl file:
$order_info = $_POST; // this seems to not returning anything
//SAVE TO DB... saving empty...
What did I miss? Weew....
You are sending the data as raw JSON in the body, it will not populate the $_POST variable.
You need to do one of two things:
You can change the content type to one that will populate the $_POST array
You can read the raw body data.
I would recommend option two if you have control over both ends of the communication, as it will keep the request body size to a minimum and save bandwidth over time. (Edit: I didn't really emphasize here that the amount of bandwidth it will save is negligible, only a few bytes per request, this would only be a valid concern is very high traffic environments. However I still recommend option two because it is the cleanest way)
In your test_curl file, do this:
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
$postedJson = json_decode($rawData);
var_dump($postedJson);
If you want to populate the $_POST variable, you will need to change the way you send the data to the server:
$data = array (
'name' => 'Hagrid',
'age' => '36'
);
$bodyData = array (
'json' => json_encode($data)
);
$bodyStr = http_build_query($bodyData);
$url = 'http://localhost/project/test_curl';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($bodyStr)
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr);
$result = curl_exec($ch);
The raw, undecoded JSON will now be available in $_POST['json'].
Use following php function for posting data using php curl function in x-www-form-urlencoded format.
<?php
$bodyData = http_build_query($data); //for x-www-form-urlencoded
?>
I am trying to upload a file to imageshack using following script:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://post.imageshack.us/');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
'fileupload'=> '#../../resources/images/cancel.png',
'optsize' => 'resample',
'rembar' => '1'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
However, I get following error from imageshack:
Wrong file type detected for file cancel.png:application/octet-stream.
Why is that, and how can it be fixed? Thanks in advance!
EDIT:
It does work when I use JPGs or GIFs (even animated ones, although Imageshack then de-animates them, I think by only using the first frame), but not with PNGs.
EDIT 2:
I found out how to fix it. As stated earlier, it does only accept JPGs and GIFs. So I take the location of the image I need to upload, copy it to a temporary location with the ending .jpg, upload the file, and then, upon completion, I remove the file from the temporary location.
Set the Content-type to the type of the file.
According to the manual, it must be an array or object. So here
$arr = array('Content-type: text/plain') ;
curl_setopt ( $ch , CURL_HTTPHEADER , $arr );