cURL POST to REST Service - php

I am trying to post to a REST service using PHP cURL but I'm after running into a bit of difficulty (this being that I've never used cURL before!!).
I've put together this code:
<?php
error_reporting(E_ALL);
if ($result == "00")
{
$url = 'http://127.0.0.1/xxxxxx/AccountCreator.ashx'; /*I've tried it a combination of ways just to see which might work */
$curl_post_data = array(
'companyName' =>urlencode($companyName),
'mainContact' =>urlencode($mainContact),
'telephone1' =>urlencode($telephone1),
'email' => urlencode($email),
'contact2' => urlencode($contact2),
'telephone2' => urlencode($telephone2)
'email2' => urlencode($email2);
'package' => urlencode($package)
);
foreach($curl_post_data as $key=>$value) {$fields_string .=$key. '=' .$value.'&';
}
rtrim($fields_string, '&');
die("Test: ".$fields_string);
$ch = curl_init();
curl_setopt ($ch, CURLOPT, $url);
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
Following this, my code sends an email and performs an IF statement. I know this works okay, I only started running into trouble when I tried to insert this cURL request.
I've tried this however it doesn't run. As I am integrating with payment partners, it just says:
Your transaction has been successful but there was a problem connecting back to the merchant's web site. Please contact the merchant and advise them that you received this error message. Thank you.
The exact error that was received was a HTTP 500 error.
Thanks.

foreach($curl_post_data as $key=>value) {$fields_string .=$key. '=' .value.'&';
value here is missing a dollar i guess
foreach($curl_post_data as $key => $value) {$fields_string .=$key. '=' .$value.'&';
have you tried die($fields_string); to see what are you actually sending to the merchant?

First of all: are you testing locally? Because that IP you're using is not a valid server address.
The constant to set the URL is called CURLOPT_URL:
curl_setopt ($ch, CURLOPT_URL, $url);
Also CURLOPT_POST must be true or false ( http://php.net/curl_setopt ), not a number (except for 1 maybe):
curl_setopt ($ch, CURLOPT_POST, true);
Here's some POST sample code: PHP + curl, HTTP POST sample code?

It would be best if you can provide your PHP version.
As of PHP 5, some handy functions are bundled in the core instead of separate PECL libraries.
// If you are working with normal HTTP requests, simply do this.
$curl_post_data = http_build_query($curl_post_data);
curl_setopt($ch, CURLOPT, $url);
// This is a boolean option, although passing non-zero integer
// will be type-casted to TRUE, count() is not the proper way.
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_post_data);
// If you really want the next statement be meaningful, do this.
// Otherwise your HTTP response will be passed directly into
// the output buffer.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
Keep in mind that CURLOPT_POSTFIELDS in PHP supports file uploads, by adding a '#' character followed by a full file path as the value.
You don't want to call http_build_query() on such situations.
Sample code for file upload
$curl_post_data = array('file1' => '#/home/user/files_to_be_uploaded');
While you can optionally specify MIME type, see the documentation for more information.
As said, check your PHP version first. This feature only works in PHP 5, AFAIK there are companies still hosting PHP 4.x in their servers.

Have a look at http_build_query

Related

json-encoded string got cut off when sent by POST over cURL (SSL enabled)

I have PHP code that uses CURL for sending 3 different arrays from one server to another over POST request. One of those arrays may contain variable number of records, and others - always one record. Prior to sending each array is json-encoded. 3 different POST-parameters then used, 1 for each array. SSL is enabled.
So everything works just fine while the 'variable-size' array is NOT bigger then 50 records (app 15 kB).
But as soon as I try to send say 51 or more records - json decoding error ('Syntax error') occurs on the receiving server when decoding that array.
Can someone please give me any idea/suggestion on what can get wrong when transmitted data is grown bigger and how can this be avoided/fixed?
Note: both servers have identical config: Win7, Apache2.4, PHP7.0, SSL enabled.
Here is the code I use for sending data:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://$targIP/curl.php");
curl_setopt($ch, CURLOPT_CAINFO, $pathCer . "xxx.crt");
curl_setopt($ch, CURLOPT_SSLCERT, $pathCer . "yyy.pem");
curl_setopt($ch, CURLOPT_SSLKEY, $pathCer . "zzz.key");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // "2": Check that the common name exists and matches the host name of the server
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array ('action' => "newupl", 'data0' => $inPart0, 'data1' => $inPart1, 'data2' => $inPart2 ));
$result = curl_exec($ch);
Code used on the receiving server:
...
$data2 = $_POST['data2'];
$data2 = html_entity_decode($data2);
$inputData2 = json_decode($data2); // NOTE: this line produces 'Syntax error' when $data2 grows beggir then app 15 kB.
...
Thanks in advance to Everyone!

CSV file upload in Php using curl

I am using Php as a frontend and Java as a backend. I have created an Post API for uploading file and using curl for api request.
I have hit my Api using Postman at that time it works fine but i am facing prodblem when i request api using Curl i don't eble to get what i am doing wrong.
Here is the curl requested data :-
$data2 = array(
'file' =>
'#' . $data1->file->tmp_name
. ';filename=' . $data1->file->name
. ';type=' . $data1->file->type
);
This is how i am sending curl request:-
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch,CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_HEADER, 1); //parveen
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //parveen
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data2);
$headers = array(
'Content-Type:'.$this->service->contentType,
'Launcher:'.$this->serverName,
'domain:'.$this->service->domain,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$this->responseBody=curl_exec($ch);
Links where i find this solution:-
enter link description here
I search a lot to find the solution but nothing is worked for me so please help me .
Thanks
the way you're trying to upload the file hasn't been supported since the PHP5 days, and even in 5.5+ you'd need CURLOPT_SAFE_UPLOAD to upload with #. use CURLFile when uploading files, like
$data2 = array(
'file' => new CURLFile($data1->file->name,$data1->file->type,$data1->file->tmp_name)
);
also, don't use CURLOPT_CUSTOMREQUEST for POST requests, just use CURLOPT_POST. (this is also true for GET requests and CURLOPT_HTTPGET )
also, check the return value of curl_setopt, if there was a problem setting your option, it returns bool(false), in which case you should use curl_error() to extract the error message. use something like
function ecurl_setopt($ch,int $option,$value){
if(!curl_setopt($ch,$option,$value)){
throw new \RuntimeException('curl_setopt failed! '.curl_error($ch));
}
}
and protip, whenever you're debugging curl code, use CURLOPT_VERBOSE, it prints lots of useful debugging info

PHP & CURL not sending file, even with # prepended

I am using PHP (WAMPServer) to receive a form submission, and then CURL to pass the file to another server for processing.
Here is an example to illustrate (not the actual code):
$data = array(
'file' => '#'.$_FILES['key']['tmp_name']
);
Here's what I'm using for CURL... and as I was pasting the code I noticed that I still have http_build_query() in my code... so, that must be the problem.
$CURL = curl_init();
curl_setopt($CURL, CURLOPT_URL, $operation['callback']);
$query_string = http_build_query($arguments);
curl_setopt($CURL, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($CURL, CURLOPT_POST, TRUE);
curl_setopt($CURL, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($CURL);
curl_close($CURL);
return $result;
My problem is that the last server isn't receiving the file. Instead, the data is passed as a key-value pair.
$_POST contains 'file' => '#c:\wamp\tmp\xyz.tmp'
What I would prefer, is that the files was transferred, and $_FILES has information about it.
Don't build an http query for the CURLOPT_POSTFIELDS. Curl can directly accept an array of fields and do its own encoding/mangling.
By building your own query, you're 'hiding' the # that indicates a file upload and CURL will not trigger its upload mechanisms.
In other words, this will fix things:
$data = array(
'file' => '#'.$_FILES['key']['tmp_name']
);
curl_setopt($CURL, CURLOPT_POSTFIELDS, $data);
if you add your CURL method code, we could better answer you...
Try to transfer the file as binary, and add the filesize in the header in your curl.

Why does cURL always return a status code?

I have some PHP code that calls into the cURL library. I'm using it to get JSON data.
I have set cURL opt 'CURLOPT_RETURNTRANSFER' to 1, but still get status code..
Code follows:
<?php
function fetch_page($url)
{
$ch = curl_init();
$array = array(
'include'=>'ayam'
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
$return = fetch_page(MY_LINK_URL);
echo json_decode($return);
?>
The code looks totally correct. Try var_dump($result) before returning it to see what it is exactly.
Also, set CURLOPT_HEADER to 1 and check the view source of the output in your browser; both of these can help debug the issue. Edit the question and post the results if so we can help more effectively.
Update: Since you are using HTTPS, also add
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
That looks correct. I actually have the same problem, but when I added
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
it returns json code correctly instead of returning 1(True).
According to the PHP docs,
Returns TRUE on success or FALSE on
failure. However, if the
CURLOPT_RETURNTRANSFER option is set,
it will return the result on success,
FALSE on failure.
So that means you should get
success: the result
failure: FALSE (which is echoed as 0)
Also, if you are fetching JSON, and need to access it, use json_decode() not json_encode().
Well, you should tell us wich url you're pointing (and wich version of php you are running).
I've tried with php 5.3 on "www.google.com" and it worked as expected ($result contains the whole webpage)
Might of had a similar problem:
- cURL on local dev network problem with virtual host naming
Before you close your curl handle output this:
$result = curl_exec ($ch);
print_r(curl_getinfo($ch));
curl_close ($ch);
Here was my solution for getting around the virtual host
// This is your Virtual Hosts name
$request_host = 'dev.project';
// This is the IP
$request_url = '192.168.0.1';
$headers = array("Host: ".$request_host);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $request_url.'?'.$request_args);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
There seems to be a number of reasons why CURLOPT_RETURNTRANSFER can be ignored, and SSL certificate checking is only one of them:
In my case the culprit was CURLOPT_POST which I had set to true. I was expecting to get back a string consisting of the HTTP response header plus the response itself. Instead I was getting status code 1. Go figure. Thankfully I did not need the HTTP header so the solution for me was:
curl_setopt($ch, CURLOPT_HEADER, false);
If I did need the header info, I don't know what I would do. I've wasted an insane amount of time tracking down the problem.
Damn you PHP curl! (waves fist in anger)

Scraping a Webpage for Results Using PHP cURL - Post Not Working

I'm new to using cURL, but from what I have read, the following should post the variables to the page, then print the result. The result prints, but it doesn't seem like the POST variables went because no results are generated. FireBug doesn't show anything going either. Any ideas what I'm doing wrong?
Thanks for your help!
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://butlercountyclerk.org/bcc-11112005/ForeclosureSearch.aspx");
$data = array(
'Search:btnSearch' => 'Search',
'Search:ddlMonth' => '1',
'Search:ddlYear' => '2011'
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
echo $output;
Based on the coding of the site, it appears that you're missing a number of variables. Take for example, the actual post request made to the search page:
__VIEWSTATE=dDwtMjk2Mjk5NzczO3Q8O2w8aTwxPjs+O2w8dDw7bDxpPDE+Oz47bDx0PDtsPGk8Mz47aTwxOT47PjtsPHQ8dDw7cDxsPGk8MD47aTwxPjtpPDI+O2k8Mz47aTw0PjtpPDU+Oz47bDxwPDIwMDY7MjAwNj47cDwyMDA3OzIwMDc+O3A8MjAwODsyMDA4PjtwPDIwMDk7MjAwOT47cDwyMDEwOzIwMTA+O3A8MjAxMTsyMDExPjs+Pjs+Ozs+O3Q8QDA8Ozs7Ozs7Ozs7Oz47Oz47Pj47Pj47Pj47PmVlaXw5JK161vti9TC+QMdeTNQI&Search:ddlMonth=1&Search:ddlYear=2011&Search:txtCompanyName=&Search:txtLastName=&Search:txtCaseNumber=&Search:btnSearch=Search
This is post-feeding though URLDecode by the way. What this means though, is that your array of 3 values is missing data. At the very least, I'd suspect that Search:btnSearch=Search is missing, and would suggest that you implement all fields into your POST request.

Categories