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"];
Related
So i am trying to get values of json object from a url, when i hit that url on post man i get something like this
{
"error": "0",
"errorString": "",
"reply": {
"nonce": "5e415334832a8",
"realm": "VMS"
}
}
So, i am trying to write a php code that displays the value of nonce in the browser but it is not working
i have the following code
$getNonceUrl = "https://example.com/api/getNonce";
$getContect = file_get_contents($getNonceUrl);
$jsonNoce = json_decode($getContect, true);
$dd = $jsonNoce->reply[0]->nonce;
echo $dd;
I also did this
$ch = curl_init("https://example.com/api/getNonce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
echo $ch->reply[0]->nonce;
But it does not seem to work still.
Below your 2 code samples with suggested corrections.
Using file_get_contents : remove 2nd argument of json_decode
$getNonceUrl = "https://example.com/api/getNonce";
$getContect = file_get_contents($getNonceUrl);
$jsonNoce = json_decode($getContect); // note removal of 2nd parameter
$dd = $jsonNoce->reply[0]->nonce;
echo $dd;
Using curl : you forgot to parse curl output with json_decode
$ch = curl_init("https://example.com/api/getNonce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data); // added this line, because curl doesn't decode json automatically
echo $ch->reply[0]->nonce;
I'm trying to implement reCAPTCHA in my website, everything seems working fine, except the return from file_get_contents().
Here is my code:
if ($_REQUEST["send"] == 1){
// access
$secretKey = 'my_key';
$captcha = $_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
echo ($responseKeys);exit;
if(intval($responseKeys["success"]) !== 1) {
$message = 'Invalid reCAPTCHA';
} else {
$msg = 'content';
send_mail('send_to',"Subject",$msg);
header("location:index.php?send=1");exit;
}
}
My variable response is returning empty.
I tried to open https://www.google.com/recaptcha/api/siteverify? inserting manually the variables and it seems to work fine.
Am I forgeting something?
Thanks
Their API waiting for a POST request. Your code send GET request.
See answer here How to post data in PHP using file_get_contents?
My wrappers were disabled, reason why I couldn't reach the URL and get the return.
As I don't have access to php.ini the workaround was send the request with curl, here is the code:
$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
echo "\n<br />";
$response = '';
} else {
curl_close($ch);
}
if (!is_string($response) || !strlen($response)) {
echo "Failed to get contents.";
$contents = '';
}
$responseKeys = json_decode($response,true);
I am currently writing a piece of code to interface with an API in Python. Supplied by the company that hosts the API is a PHP script that logs into the API given the correct username and password, retrieved the current event ID (JSON format), and then logs out. This works perfectly.
Currently, I am in the process of writing a script in Python to do the very same thing, the current code is shown below. It logs in and out successfully, however, when it tries to retrieve the current event ID I get the status code 404, suggesting that the URL doesn't exist, despite this same URL working with the PHP code.
PHP Code:
define('BASE_URL', 'https://website.api.com/');
define('API_USER', 'username');
define('API_PASS', 'password');
$cookiefile = tempnam(__DIR__, "cookies");
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
$loginParams = array(
'username' => API_USER,
'password' => API_PASS
);
$obj = CurlPost($ch, BASE_URL . '/api/login', $loginParams);
if( $obj->success )
{
echo 'API login successful.' . PHP_EOL;
}
$obj = CurlGet($ch, BASE_URL . '/api/current-event-id');
echo 'API current event ID: ' . $obj->currentEventId . PHP_EOL;
// logout of the API
$obj = CurlGet($ch, BASE_URL . '/api/logout' );
if( $obj->success )
{
echo 'Logged out successfully.' . PHP_EOL;
}
curl_close($ch);
exit(0);
// -------------------------------------------------------------------------
// Functions
// -------------------------------------------------------------------------
// Run cURL post and decode the returned JSON object.
function CurlPost($ch, $url, $params)
{
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($query));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$output=curl_exec($ch);
$obj = json_decode($output);
return $obj;
}
// Run cURL get and decode the returned JSON object.
function CurlGet($ch, $url)
{
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
$output=curl_exec($ch);
$obj = json_decode($output);
return $obj;
}
Python Code:
import requests
BASE_URL = 'https://website.api.com/';
API_USER = "username";
API_PASS = "password";
headers = {'content-type': 'application/json'}
PARAMS = {'username':API_USER,'password':API_PASS}
session = requests.Session()
# Login
resp = session.post(BASE_URL + '/api/login',data=PARAMS)
if resp.status_code != 200:
print("*** ERROR ***: Login failed.")
else:
print("API login successful.")
resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
print(resp.status_code)
print(resp.text)
# Logout
resp = session.get(BASE_URL + '/api/logout')
if resp.status_code != 200:
print("*** ERROR ***: Logout failed.")
else:
print("API logout successful.")
It's ideal to change BASE_URL to:
'https://website.api.com'
the code looks fine to me when compared to php and should normally work.(Shouldn't you be passing some kind of authentication like a token?).
try debugging your API using postman.
It turns out that my API will only accept cookies transferred in the header, so I wrote a slight hack that dumped the cookiejar into a string that could be sent in the header file.
cookies = json.dumps(requests.utils.dict_from_cookiejar(resp.cookies));
cookies = cookies.replace('"', '')
cookies = cookies.replace('{', '')
cookies = cookies.replace('}', '')
cookies = cookies.replace(': ', '=')
cookies = cookies.replace(',', ';')
headers = {'Cookie':cookies}
resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
I am trying to get the latest commit from github using the api, but I encounter some errors and not sure what the problem is with the curl requests. The CURLINFO_HTTP_CODE gives me 000.
What does it mean if I got 000 and why is it not getting the contents of the url?
function get_json($url){
$base = "https://api.github.com";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $base . $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CONNECTTIMEOUT, 1);
$content = curl_exec($curl);
echo $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $content;
}
echo get_json("users/$user/repos");
function get_latest_repo($user) {
// Get the json from github for the repos
$json = json_decode(get_json("users/$user/repos"),true);
print_r($json);
// Sort the array returend by pushed_at time
function compare_pushed_at($b, $a){
return strnatcmp($a['pushed_at'], $b['pushed_at']);
}
usort($json, 'compare_pushed_at');
//Now just get the latest repo
$json = $json[0];
return $json;
}
function get_commits($repo, $user){
// Get the name of the repo that we'll use in the request url
$repoName = $repo["name"];
return json_decode(get_json("repos/$user/$repoName/commits"),true);
}
I use your code and it will work if you add an user agent on curl
curl_setopt($ch, CURLOPT_USERAGENT,'YOUR_INVENTED_APP_NAME');
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.