CURL PHP - missing output and unknown error - php

I'm using the code below to query an api however I'm not seeing any output. The header is returned however I also get an error - "An error has occurred:" with nothing else - not very helpful to say the least. Does anyone know what I'm doing wrong here? (NB I've had to remove the user details for obvious reasons)
//Required Call Information;
$username = "xxxxxxxxxxxxx";
$password = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
$remote_url = 'https://xxxxxxxxxxxxx.com/xx.json';
// init the resource
$ch = curl_init();
//Header Information;
$headr = array();
$headr[] = "Authorization: Basic " . base64_encode("$username:$password");
$headr[] = "X-Page:" . $pages;
// set curl options
curl_setopt($ch, CURLOPT_URL,$remote_url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headr);
curl_setopt($ch, CURLOPT_HEADER, true);
// execute
$output = curl_exec($ch);
// echo
echo $output;
// echo
print $output;
// free
curl_close($ch);
// check status of server being called vis crul
var_dump(curl_getinfo($ch));
//if error
if (!curl_exec($ch)) {
// if curl_exec() returned false and thus failed
echo 'An error has occurred: ' . curl_error($ch);
}
else {
echo 'everything was successful';
}

Adding the RETURN_TRANSFER curl opt will return data rather than a boolean when $output = curl_exec($ch); is called.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

Add in the following curl opt and see what you get back:
curl_setopt($ch, CURLOPT_VERBOSE, true);

Related

Retrieving data of curl post in PHP

I am trying to senddata to a url by using curl with codeigniter. I have successfully implemented the code for sending the data as below.
function postToURL($reg_no, $data)
{
$url = 'http://localhost/abcSystem/Web_data/viewPage';
$send_array = array(
'reg_no' =>$reg_no,
'data' =>$data,
);
$fields_string = http_build_query($send_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$post_data = 'json='.urlencode(json_encode($send_array));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if (curl_errno($ch)) {
die('Couldn\'t send request: ' . curl_error($ch));
} else {
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
print_r('success'); // this is outputting
return $output;
} else {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
}
The out put is success. I want to see if this post data can be retrieved. So I tried to change the above url controller file as below.
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
But nothing is printing. I want to get the data of posting. Please help me on this.
Your Written code
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
is not to Print or capture Posted Data . Because you are dealing with Current Page PHP INPUT Streaming , whereas you are posting data on Other URL . So what you need to do is just Put a log of posted data in File. Use below code after $output = curl_exec($ch)
file_put_contents("posted_data.txt", $post_data );
This way you will be able to write your each post in file Posted_data.txt File - Make sure you give proper File Permission. If you want to keep trace of each POST than just make the file name dynamic so per API Call it can write a log.
Another option is to save the $post_data in DATABASE - Which is not suggestable from Security point of view.
Where ever you are calling your postToURL() function, you need to output the result of it.
For example:
$output = postToURL('Example', array());
echo $output;
This is because you are returning the curl output rather outputting it.

Get JSON generated by a webhook hosted online

I am making a card payment and then it communicates to the server of the company via webhook, the response is then recorded in RequestBin, which generates a JSON response in their website, how do I extract the information from the website to my PHP code?
The webpage looks like this:
my requestb.in online webhook
What I need is to get that raw JSON.
You could try using CURL to retrieve the JSON object. Are you using CURL to send the payment payload out to the processor, etc? Below is an example (Obviously you would need to fill in the appropriate PHP variables where applicable).
$reqbody = json_encode($_REQUEST);
$serviceURL = "http://www.url.com/payment_processor";
$curl = curl_init($serviceURL);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $reqbody);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$headers = array(
'Content-type: application/json',
"Authorization: ".$hmac_enc,
"apikey: ".$apikey,
"token: ".$token,
"timestamp: ".$timestamp,
"nonce: ".$nonce,
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $serviceURL failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
echo "<hr/><br/><strong>PROCESSOR RESPONSE:</strong><br/>";
echo "<pre>";
print_r($response);
echo "</pre>";
You could get the json from requestbin and resend it to your localhost using a request client like Postman.
if (!empty($_POST)) {
$data = json_decode($_POST);
}
I found the solution, first you download HTML dom and then you just change the fields. The reason the for loop goes from 0-19 is because requestb.in saves 20 entries, for the rest just substitute the variables.
include('../simple_html_dom.php');
// get DOM from URL or file
// asegurese de incluir el ?inspect en el URL
$html = file_get_html('https://requestb.in/YOURURL?inspect');
for ($x = 0; $x <= 19; $x++) {
$result = $html->find('pre[class=body prettyprint]', $x)->plaintext;
if($result){
$json_a = str_replace('"', '"', $result);
$object = json_decode($json_a);
if(isset($object->type)) echo $object->type . "<br>";
if(isset($object->transaction->customer_id)) echo $object->transaction->customer_id . "<br>";
}
}

how to post the value in url using PHP

I am creating a web service. I have tried to write an URL but its throwing error. I am not getting where I am going wrong. I want to pass these variable values in url and depending on this i want to call the web service
<?php
if($_POST["occupation"] == '1'){
$occupation = 'Salaried';
}
else{
$occupation = 'Self+Employed';
}
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?interestRateType='.$_POST["interestRateType"]'.&occupation='.$_POST["occupation"].'&offeringTypeId='.$_POST["offeringID"].'&city='.$_POST["city"].'&loanAmt='.$_POST["loanAmt"].'&age='.$_POST["age"];
echo $url;
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$json = json_decode($result, true);
//print_r($json);
//echo $json['resultList']['interestRateMin'];
$json_array = $json['resultList'];
print_r($json_array);
?>
Try below code. You have syntax error before &occupation
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?interestRateType='.$_POST["interestRateType"].'&occupation='.$_POST["occupation"].'&offeringTypeId='.$_POST["offeringID"].'&city='.$_POST["city"].'&loanAmt='.$_POST["loanAmt"].'&age='.$_POST["age"];
Copy this because there is some ' and . error
$url = 'http://www.aaa.com/ajaxv2/getCompareResults.html?
interestRateType='.$_POST["interestRateType"].'&
occupation='.$_POST["occupation"].'&
offeringTypeId='.$_POST["offeringID"].'&
city='.$_POST["city"].'&
loanAmt='.$_POST["loanAmt"].'&
age='.$_POST["age"];

Unnecessary warning for invalid tokens when calling file_get_contents

The following code tries to run file_get_contents for a facebook url based on access token:
$access_token=$ret["oauth_token"];
$fbid=$ret["oauth_uid"];
$url ="https://api.facebook.com/method/friends.getAppUsers?format=json&access_token=$access_token";
try {
$content = file_get_contents($url);
if ($content === false) {
$common_friends = array("error_code" => "something");
} else {
$common_friends = json_decode($content,true);
}
} catch (Exception $ex) {
//Who cares
}
All the Facebook settings are correct, the only potential problem is that the access token is no longer valid. In that case I receive the warning of
file_get_contents(): php_network_getaddresses: getaddrinfo failed:
Name or service not known
How can I upgrade my code, so if the facebook user access token is expired/invalid, file_get_contents will not give a warning, but fail gracefully?
EDIT:
$content = #file_get_contents($url);
still shows the same warning, however, I want to get rid of it. NetBeans also warns me that error control operator is misused. I have modified my code as follows:
try {
User::checkFacebookToken();
//file_get_contents sends warning message when token does not exist
//the problem is already handled, therefore these warnings are not needed
//this is why we set scream_enabled to false temporarily
ini_set('scream.enabled', false);
$content = file_get_contents($url);
ini_set('scream.enabled', true);
if ($content === false) {
$common_friends = array("error_code" => "something");
} else {
$common_friends = json_decode($content,true);
}
} catch (Exception $ex) {
//Who cares
}
I hope that scream.enabled is only temporarily changed to false.
You could alternatively use cURL which has better server response handling and you can display the error gracefully.
$access_token = 'your_access_token';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.facebook.com/method/friends.getAppUsers?format=json&access_token=$access_token");
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($curl);
$response = curl_getinfo($curl);
echo '<pre>';
print_r($response);
if(!curl_errno($curl)){
// Server request success, but check the API returned error code
$content = json_decode($content, true);
print_r($content);
echo $content['error_code'];
echo $content['error_msg'];
}else {
// Server request failure
echo 'Curl error: ' . curl_error($curl);
}
curl_close($curl);
PhpFiddle
SOLUTION 1 : ensure that warnings will not be printed on main output
just add '#' to 'file_get_contents()' to suppress warning since you catched the error correctly by :
error_reporting(E_ERROR | E_PARSE);
if(#file_get_contents() === FALSE) {
// handle this error/warning
}
SOLUTION 2 : verify that you have a valid Facebook token before doing your request, Using Facebook API
$ch = curl_init();
// you should provide your token
curl_setopt($ch, CURLOPT_URL, "http://graph.facebook.com/me?access_token=52524587821444123");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
$output = json_decode("[" . curl_exec($c) . "]");
if(is_array($output) && isset($output[0]->error)) {
print "Error Message : " . $output[0]->error->message . "<br />";
print "Error Type : " . $output[0]->error->type . "<br />";
print "Error Code : " . $output[0]->error->code . "<br />";
}else {
// do your job with file_get_contents();
}
curl_close($c);

Trying to use curl to do a GET, value being sent is allows null

I'm trying to use curl to do a simple GET with one parameter called redirect_uri. The php file that gets called prints out a empty string for $_GET["redirect_uri"] it shows red= and it seems like nothing is being sent.
code to do the get
//Get code from login and display it
$ch = curl_init();
$url = 'http://www.besttechsolutions.biz/projects/facebook/testget.php';
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_GET,1);
curl_setopt($ch,CURLOPT_GETFIELDS,"redirect_uri=my return url");
//execute post
print "new reply 2 <br>";
$result = curl_exec($ch);
print $result;
// print "<br> <br>";
// print $fields_string;
die("hello");
the testget.php file
<?php
print "red-";
print $_GET["redirect_uri"];
?>
This is how I usually do get requests, hopefully it will help you:
// create curl resource
$ch = curl_init();
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Set maximum redirects
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
// Allow a max of 5 seconds.
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
// set url
if( count($params) > 0 ) {
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, "$url?$query");
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
// $output contains the output string
$output = curl_exec($ch);
// Check for errors and such.
$info = curl_getinfo($ch);
$errno = curl_errno($ch);
if( $output === false || $errno != 0 ) {
// Do error checking
} else if($info['http_code'] != 200) {
// Got a non-200 error code.
// Do more error checking
}
// close curl resource to free up system resources
curl_close($ch);
return $output;
In this code, the $params could be an array where the key is the name, and the value is the value.

Categories