cURL Passing Parameters - PHP - Laravel - php

I am using this cURL function to send a set of data that has to be received by the api. However the api receives null.
public static function httpPost($url,$type,$params)
{
$postData = '';
foreach ($params as $k => $v) {
$postData .= $k . '=' . $v . '&';
}
$postData = rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
I have tried outputting the data before sending and it shows correct data. The other curl part works. Any idea why data is not being sent through curl?

Since you do not need to use POST, unset that curl option and use PHP http_builder to build the URL
public static function httpPost($url,$type,$params)
{
// Clean URL + append "?" at the end of URL + append the query
$url = rtrim($url,"?") . "?" . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}

Related

Saving a curl response into database

I am getting this response
[{"id":15702671,"payment_id":15702666,"amount":20,"metadata":{},"source":{"id":"347862165","name":"Test Test","type":"collector"},"date_created":"2018-08-28T08:11:15.000-04:00","unique_sequence_number":null,"status":"approved"}]
This is my Code
$url = "https://api.mercadopago.com/v1/payments/".$paymeny_id."/refunds?access_token=TEST-4015220099523401-082300-232be80199d9b1a9b0bac72d6af99fd2-347862165";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$output = curl_exec($ch);
curl_close($ch);
how to save response value in variable ?
try this
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$var = curl_exec($ch)
Hope this works!
to get the id
$var = json_decode($var);
$id = $var[0]->id;
you need to add CURLOPT_RETURNTRANSFER option in your curl object to get the response using curl as
$url = "https://api.mercadopago.com/v1/payments/".$paymeny_id."/refunds?access_token=TEST-4015220099523401-082300-232be80199d9b1a9b0bac72d6af99fd2-347862165";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);

Can't hit Web API from php

I'm trying to call this
[Route("CreateHL7TestFile")]
[HttpPost]
public IActionResult CreateHL7TestFile([FromBody] JObject data)
{
// Code here
}
from a php function using cUrl. When I try and call the API without passing any data it works fine. It's when I try and add the '$data' that I cannot hit the API. When I call the API with data from Postman it also works fine. So I'm assuming my error is on the php side?
My php function looks like this.
public function CallAPI($method, $url, $data = false)
{
$data = array("value1" => "some value");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('test1' => 'value1', 'test2' => 'value2')));
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
}
http://localhost:50999/api/ParticipantAPI/CreateHL7TestFile
Any help would be much appreciated.
Thanks,
Adam
Use a proper model on the asp.net-core server to bind incoming data
public class MyData {
public string value1 { get; set;}
}
And update action accordingly
[Route("CreateHL7TestFile")]
[HttpPost]
public IActionResult CreateHL7TestFile([FromBody] MyData data) {
// Code here
}
Referencing the following article POSTing JSON Data With PHP cURL
Try the following on the PHP side
$data = array("value1" => "some value");
$data_string = json_encode($data);
$ch = curl_init($url);
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);
print_r($result);
curl_close($ch);
For your real requests refactor the expected data model accordingly.
Try something like this:
public function CallAPI($method, $url, $data = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('test1' => 'value1', 'test2' => 'value2')));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
}
http://php.net/manual/en/function.http-build-query.php
If you want to send json, then I think you'll have to set the header, something like:
public function CallAPI($method, $url, $data = false)
{
$dat = array("TEST1","TEST2");
$data = json_encode($dat);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
}

connecting to an api using php and curl with username, password and cookies [duplicate]

I been trying to log into barnesandnoble.com mobile site with curl
and have had no luck so far. I get back the page with no errors
and it defaults my email into the email input form box of the login page again (in the form returned from print $result).
The same code can actually let me go into ebay correctly
by changing the LOGINURL to point to ebay's login
The only difference being that barnesandnobles is https://
and ebay login was http://
Also, I believe that barnes website is asp/aspx so I don't know
how that would handle cookies and _state differently
Any help would be appreciated as I been trying to debug this for the
past 16hrs
also, my cookie.txt is writable and working
<?php
$cookie_file_path = "C:/test/cookie.txt";
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";
$ch = curl_init();
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$content = curl_exec($ch);
curl_close($ch);
unset($ch);
// NAME="path_state" value="6657403">
if(stristr($content,"path_state")){
$array1 = explode('path_state" value="',$content);
$content1 = $array1[1];
$array2 = explode('">',$content1);
$content2 = $array2[0];
}
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$POSTFIELDS = "d_hidPageStamp=V_3_17&hidViewMode=opSignIn&stage=signIn&previousStage=mainStage&path_state=" . $content2 . "&emailAddress=YOUREMAILHERE#gmail.com&acctPassword=YOURPASSWORD";
$reffer = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$ch = curl_init();
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $reffer);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
$result = curl_exec($ch);
print $result;
?>
Here is a working example I created from your code. This uses a function getFormFields that I wrote for a similar question (first reference at the bottom of this post) which logs into the Android market.
I think there may have been a couple of things in your script that were preventing the login from working. First, you should urlencode the URL parameters such as email and password in the post string (cURL will not do this for you). Second, I think the x value used as part of the login URL may be required.
Here is a solution that logs in successfully. Note, I re-used the original cURL handle. This is not necessary, but if you specify keep-alive, it will actually re-use the same connection, and it also saves you from having to specify the same options over and over.
Once you have the cookies, you can create a new cURL object and specify the COOKIEFILE and COOKIEJAR and you will be logged in without performing the first steps.
<?php
// options
$EMAIL = 'you#yoursite.com';
$PASSWORD = 'yourpassword';
$cookie_file_path = "/tmp/cookies.txt";
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";
// begin script
$ch = curl_init();
// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
// execute session to get cookies and required form inputs
$content = curl_exec($ch);
// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['emailAddress'] = $EMAIL;
$fields['acctPassword'] = $PASSWORD;
// get x value that is used in the login url
$x = '';
if (preg_match('/op\.asp\?x=(\d+)/i', $content, $match)) {
$x = $match[1];
}
//$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn";
$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?x=$x";
// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);
// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
// perform login
$result = curl_exec($ch);
print $result;
function getFormFields($data)
{
if (preg_match('/(<form action="op.*?<\/form>)/is', $data, $matches)) {
$inputs = getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
This worked for me, hope that helps get you going.
Here are some other cURL answer I have that may help learn:
Retrieve Android Market mylibrary with curl
multiple actions with curl
sending xml and headers via curl
Login to Google with PHP and Curl, Cookie turned off?
Pinterest login with PHP and cURL not working

curl post data and get result

This is my code :
<?php
$url = 'http://huaweiunlockcalculator.com/v201-huawei-unlock-calculator-v3';
$fields = array('imei' => $_POST['imei']);
//url-ify the data for the POST
$fields_string="";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, 'http://huaweiunlockcalculator.com/v201-huawei-unlock-calculator-v3');
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
$output=preg_match_all("/Unlock \(V[123]\): ([0-9]+)/",$result, $matches);
echo $matches[0];
//print_r($matches[0][2]);echo "<br>";
//print_r($matches[0][1]);echo "<br>";
//print_r($matches[0][0]);echo "<br>";
curl_close($ch);
//close connection
It brings a wrong result :(
I need to send IMEI and get result in my own site. How can I do that ?
some web page need whole post data whether null of the value. A function called http_build_query() function can easily build a post or get query string , you just give a parameter type array .
$url = "http://www.example.com/api/WalletVerification";
$params = array();
$inputs = array();
$inputs['rid']=100;//$retailer_id;
$inputs['merchantid']="B170127CT3D9H2XJAQUYF0L";
$inputs['amount']=10;//$wallet_raminfo;
$params =json_encode($inputs);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$output= json_decode($result);
// print_r($output);
if($output->status=='000'){
$raminfostrans_id= $output->transactionid;
$payment_status=TRUE;
}else{
$payment_status=false;
$failure_msg="insuffient balance";
}

curl url is not working in Yii

i am using curl in my yii application first time.
following is my code
$ch = curl_init();
$u='admin';
$p='admin123';
$postvars = '';
foreach($string as $key=>$value) {
$postvars .= $key . "/" . $value . "/";
}
curl_setopt($ch, CURLOPT_URL, 'http://localhost:83/Working-copy/tradiecom/ServiceTypeMaster/Create' );
curl_setopt($ch, CURLOPT_USERPWD, $u.':'.$p);
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($string));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
$json = curl_exec($ch);
if ($json === false)
{
echo 'test';
}
print_r($json);
Now i don't know how to access post variables in ServiceTypeMaster/create action??
And i don't know whether my action is called or not?
How can i know that.

Categories