What is the best way to post XML from a form using Curl.
I have a HTML Form and i post the data to a new php page and all the fields are collected. How do i collect these fields in XML Format.
I can process it from a xml file, how do i alter my current codeso it doesnt use a file , but builds it on the same page then sends it.
$filename = "data.xml";
$handle = fopen($filename, "r");
$XPost = fread($handle, filesize($filename));
fclose($handle);
$url = "http://test.com/webservicerequest.asmx";
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_VERBOSE, 1); // set url to post to
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_HEADER, "http://test.com/webservicerequest/SubmitLead");
curl_setopt($ch, CURLOPT_TIMEOUT, 99999999); // times out after 4s
curl_setopt($ch, CURLOPT_POSTFIELDS, $XPost); // add POST fields
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch); // run the whole process
if (empty($result)) {
// some kind of an error happened
die(curl_error($ch));
curl_close($ch); // close cURL handler
} else {
$info = curl_getinfo($ch);
curl_close($ch); // close cURL handler
if (empty($info['http_code'])) {
die("No HTTP code was returned");
} else {
// load the HTTP codes
$http_codes = parse_ini_file("response.inc");
// echo results
echo "The server responded: \n";
echo $info['http_code'] . " " . $http_codes[$info['http_code']];
}
}
echo "</br>";
var_dump($result) ;
$data = array(
"line1" => "sample data",
"line2" => "sample data 2",
);
$data_string = json_encode($data);
$url = "http://test.com/webservicerequest.asmx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
var_dump($result) ;
?>
Related
My requirement is to upload a file to my google drive using Php cURL and then rename the upload file and move the file to a specific folder.
For this, I have done oAuth and successfully uploaded a file from my website to google drive using the below code.
$image = "../../../".$name;
$apiURL = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media';
$mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
$folder_id = "1WBkQQ6y0TPt2gmFR3PKCzSip_aAuuNEa";
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $apiURL);
curl_setopt($ch1, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, file_get_contents($image));
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: '.$mime_type, 'Authorization: Bearer ' . $access_token) );
// execute cURL request
$response=curl_exec($ch1);
if($response === false){
$output = 'ERROR: '.curl_error($ch1);
} else{
$output = $response;
}
// close first request handler
curl_close($ch1);
$this_response_arr = json_decode($response, true);
The file is uploaded as Untitled and I used the below code to rename it to a proper filename as per my requirement.
if(isset($this_response_arr['id'])){
$this_file_id = $this_response_arr['id'];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files/'.$this_file_id);
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'PATCH');
$post_fields = array();
$this_file_name = explode('.', $name);
$post_fields['name'] = $this_file_name[0];
curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response2 = curl_exec($ch2);
if($response2 === false){
$output2 = 'ERROR: '.curl_error($ch2);
} else{
$output2 = $response2;
}
curl_close($ch2);
$this_response2 = json_decode($response2, true);
}
Now I want to move this uploaded file in the Google drive root folder to a specific folder. I tried adding the “Parents” , “addParents”, “removeParents” parameters in post body along with "Name" parameter and and also as a separate cURL Patch request but none of them is working.
if($this_response2['id']){
$this_f_id = $this_response2['id'];
$ch3 = curl_init();
curl_setopt($ch3, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files/'.$this_f_id);
curl_setopt($ch3, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch3, CURLOPT_POST, 1);
$post_fields1 = array();
$post_fields1['addParents'] = $folder_id;
$post_fields1['removeParents'] = "root";
curl_setopt($ch3, CURLOPT_POSTFIELDS, json_encode($post_fields1));
curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch3, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response3 = curl_exec($ch3);
if($response3 === false){
$output3 = 'ERROR: '.curl_error($ch3);
} else{
$output3 = $response3;
}
curl_close($ch3);
}
Any help would be appreciated.
Documentation for uploading,renaming and moving the file in gdrive is not properly documented for Php cURL and there are not much examples available too.
There is no need to send an additional cURL request for moving the file to a specific folder. This can be done in the second cURL request itself.
The mistake in your code is, you are sending the addParents and removeParents in Request Body instead of sending this as query parameters.
You can modify the second cURL as below to update the name of uploaded file and for moving the file inside a specific folder.
if(isset($this_response_arr['id'])){
$this_file_id = $this_response_arr['id'];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files/'.$this_file_id.'?addParents='.$folder_id.'&removeParents=root');
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'PATCH');
$post_fields = array();
$this_file_name = explode('.', $name);
$post_fields['name'] = $this_file_name[0];
curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response2 = curl_exec($ch2);
if($response2 === false){
$output2 = 'ERROR: '.curl_error($ch2);
} else{
$output2 = $response2;
}
curl_close($ch2);
$this_response2 = json_decode($response2, true);
}
Let me know if this works.
I don't know much about how to use cURL.I am trying to convert Speech to Text using IBM Watson API. When I try to convert it without using parameters(Translate English
Audio File), I get a response without any error.
But when I add
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'model'=>'ja-JP_NarrowbandModel'
))
It returns
{ "code_description": "Bad Request", "code": 400, "error": "unable to
transcode data stream audio/flac -> audio/x-float-array " }
I am not sure if there is an issue in my Syntax or something else is going wrong there.
I read docs from : https://console.bluemix.net/docs/services/speech-to-text/http.html#http
<?php
$ch = curl_init();
$file = file_get_contents('audio-file.flac');
curl_setopt($ch, CURLOPT_URL, 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $file);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'apikey' . ':' . 'MY_API_HERE');
$headers = array();
$headers[] = 'Content-Type: audio/flac';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'model'=>'ja-JP_NarrowbandModel'
));
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
print_r($result);
You are setting CURLOPT_POSTFIELDS twice, once with the content of your file and a second time with an array containing 'model'=>'ja-JP_NarrowbandModel'.
According to the documentation, you can pass the model as a query parameter.
Try something like this (not tested):
<?php
$file = file_get_contents('audio-file.flac');
$url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize';
$model = 'ja-JP_NarrowbandModel';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?model=' . $model);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $file);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'apikey' . ':' . 'MY_API_HERE');
$headers = array();
$headers[] = 'Content-Type: audio/flac';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
print_r($result);
i've create a php function to make a post json data request using curl
My Code :
$url = 'http://77.42.154.142:90/home/test/GetNewCustomer';
$data = array("UpdatedOn" => "1/23/2004 1:00AM","CreatedOn" => "1/23/2015 1:00AM");
$fields = json_encode($data);
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'sduser: 34EE0A61-F3A5-4E21-86D3-C7B7DAF9C8F9913982A9-3025-4C37-8093-B664B9310F91',
'Content-Length:'.strlen($fields)
));
curl_setopt($post, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($fields)));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($post, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($post);
// for debugging
var_dump(curl_getinfo($post), $result);
// if(false === $result) { // request failed
// die('Error: "' . curl_error($post) . '" - Code: ' . curl_errno($post));
// }
curl_close($post);
But i've got this response The parameters dictionary contains a null entry for parameter
Any Suggestion ?
I have params like
$A='ZAXGHGN';
$INPUT='<?xml version="1.0" encoding="utf-8"?><a><b>test data</b></a>';
$array= array('A:'.$A,'INPUT:'.$INPUT);
Below is my curl code
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$array );
$data = curl_exec($ch);
if(curl_errno($ch))
print curl_error($ch);
else
curl_close($ch);
echo "<pre>"; print_r($data);exit;
When i try to execute the code i am getting below error.
Output :
Bad Request - Invalid Header
HTTP Error 400. The request has an invalid header name.
try something like this
$A = 'ZAXGHGN';
$INPUT = '<?xml version="1.0" encoding="utf-8"?><a><b>test data</b></a>'; // is this a valid XML???
$headers = array(
"Content-type: text/xml",
"Content-length: " . strlen($INPUT),
"A: " . $A,
// like this if you want to have this value in the header ... but to put the xml inside the header info...
"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $INPUT); // send xml data using POST
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch))
print curl_error($ch);
else
curl_close($ch);
echo "<pre>";
print_r($data);
exit;
I'm using Drupal 7 and the services module and I'm trying to update a user profile using PHP & Curl.
Do I always have to login before sending a "PUT/update" ?
This is my code so far :
<?php
// REST Server URL
$request_url = 'http://mywebsite/end/user/login';
// User data
$user_data = array(
'username' => 'user2',
'password' => 'pass1',
);
// cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
print $response;
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check if login was successful
if ($http_code == 200) {
// Convert json response as array
$logged_user = json_decode($response);
}
else {
// Get error msg
$http_message = curl_error($curl);
die($http_message);
}
print_r($logged_user);
// REST Server URL
$request_url = 'http://mywebsite.com/end/user/8&XDEBUG_SESSION_START=netbeans-xdebug';
$user_data = array('current_pass' => 'pass1', 'pass' => 'pass2');
// Define cookie session
$cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;
// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json',
'Content-type: application/json')); // Accept JSON response
curl_setopt($curl, CURLOPT_PUT, TRUE);
curl_setopt($curl, CURLOPT_HEADER, TRUE); // FALSE); // Ask to not return Header
curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session"); // use the previously saved session
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
// Emulate file.
$serialize_args = json_encode($user_data);
$putData = fopen('php://temp', 'rw+');
fwrite($putData, $serialize_args);
fseek($putData, 0);
curl_setopt($curl, CURLOPT_INFILE, $putData);
curl_setopt($curl, CURLOPT_INFILESIZE, drupal_strlen($serialize_args));
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check if login was successful
$ret;
if ($http_code == 200) {
// Convert json response as array
$ret = json_decode($response);
}
else {
// Get error msg
$http_message = curl_error($curl);
die($http_message);
}
print_r($ret);
curl_close($curl);
}
?>
What am I missing here?
Nothing happens to my profile.
Any answer is welcomed!
Hope this can help u.
$service_url = 'http://mywebsite/end/user/login'; // .xml asks for xml data in response
$post_data = array(
'username' => 'user2',
'password' => 'pass1',
);
$post_data = http_build_query($post_data, '', '&'); // Format post data as application/x-www-form-urlencoded
// set up the request
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // have curl_exec return a string
curl_setopt($curl, CURLOPT_POST, true); // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$response = curl_exec($curl);
curl_close($curl);
// parse the response
$xml = new SimpleXMLElement($response);
$session_cookie = $xml->session_name .'='. $xml->sessid;
if(empty($xml->session_name) && empty($xml->sessid)){
echo 'Wrong';exit;
}
$service_url = 'http://mywebsite/end/user/token'; // .xml asks for xml data in response
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_POST, true); // do a POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // POST this data
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // have curl_exec return a string
curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
// make the request
curl_setopt($curl, CURLOPT_VERBOSE, true); // output to command line
$csrf_token = curl_exec($curl);
curl_close($curl);
$xml = new SimpleXMLElement($csrf_token);
$csrf_token = $xml->token;
$csrf_header = 'X-CSRF-Token: ' . $csrf_token;
// REST Server URL
$request_url = 'http://mywebsite/end/user/8&XDEBUG_SESSION_START=netbeans-xdebug';
$user_data = array('current_pass' => 'pass1', 'pass' => 'testing');
// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json',
'Content-type: application/json',$csrf_header)); // Accept JSON response
curl_setopt($curl, CURLOPT_PUT, TRUE);
//curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, TRUE); // FALSE); // Ask to not return Header
curl_setopt($curl, CURLOPT_COOKIE, "$session_cookie"); // use the previously saved session
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
// Emulate file.
$serialize_args = json_encode($user_data);
$putData = fopen('php://temp', 'rw+');
fwrite($putData, $serialize_args);
fseek($putData, 0);
curl_setopt($curl, CURLOPT_INFILE, $putData);
curl_setopt($curl, CURLOPT_INFILESIZE, strlen($serialize_args));
$response = curl_exec($curl);
curl_close($curl);
You can achieve this by using "CURLOPT_COOKIEJAR" for writing and preserving cookies but you also need to set "CURLOPT_COOKIEFILE" for reading. More info can be found at http://php.net/manual/en/function.curl-setopt.php
define('COOKIE_FILE', "/tmp/sess" . time() . $user_data['username']);
curl_setopt ($curl, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($curl, CURLOPT_COOKIEFILE, COOKIE_FILE);