I'm trying to connect to this webpage of the steam api. The market_hash_name parameter is the item I want to search. And as you can see, the response is in the format json. My code is this one:
$url = "http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=" . urlencode($hash_name);
$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data, true);
if ($data['success'] == true) {
echo $url . "<br>";
echo "Data Found: " . $data;
} else {
"Data not found";
}
Sometimes I get the correct response and everything, but sometimes I get this characters <Ê+ÍÉÿÿOüË% as the $data variable. But it still gets inside the if! So it does have the 'success' key in that JSON response, although it's not readable.
EDIT: So I've seen that sometimes the url decides to return null instead of the JSON response. I think I get this weird characters when I get the null return. But this doesn't explain why It enters to the if sentence :/
You need add this to your CURL:
curl_setopt($ch, CURLOPT_ENCODING, '');
See the explanation here : PHP curl returning strange characters
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 am using file_get_contents to get the json from URLs. The same URL works sometimes and sometimes it doesn't. When it doesn't, file_get_contents does not return any error and just stops the whole script. It's too confusing.
What's error you get? It's warning or Fatal Error?
if it's warning, please add # to befor file_get_contents like: #file_get_contents
if other, please check data before execute other process
$jsondata =#file_get_contents('YOur URl');
if($jsondata){
// Process your code
}else{
//do nothing
}
What a URL is returning when the correct data is not outputted ?
1)
$json_data =file_get_contents('URl');
if($json_data){
//parse the data
}else{
//show error
}
2 to find what exactly the url returns
$json_data =file_get_contents('URl');
var_dump($json_data);
3 use cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
var_dump($obj)
First part of the question solved. Please look at EDIT 2
I have the following problem:
I get a username out of my database with a htmlspecialchar, in this case: exámple. I parse it via cUrl to the Riot-Games API.
$url = 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/exámple?api_key=<my-api-key>'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
return $output;
curl_close($ch);
My result is: { "status": { "message": "Not Found", "status_code": 404 } }
But the user exists! I can open the URL in my browser and it works...
I think cUrl can't parse the á in the string, if i copy the url and open it in browser
á is converted to %C3%A1
Is it somehow possible to convert the URL in PHP to a sendable request?
Thanks in advance ;)
EDIT
If i use ex%C3%A1mple instead of exámple in my user-database it works!
EDIT 2
I now use urlencode to the username. However I'm despairing...
My simple script:
echo urlencode($row["username"]) . " " . urlencode('exámple');
The $row["username"] outputs me guaranteed 'exámple'. It's an SQL request.
The output i get:
ex%E1mple ex%C3%A1mple
Solved:
urlencode(utf8_encode($row["username"]))
use urlencode function to encode name. See below code:
$name='exámple';
$encoded_name = urlencode('exámple'); //output: ex%C3%A1mple
$url = 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/'.$encoded_name.'?api_key=<my-api-key>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
echo $output;
I have a frontend code
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
//make the request
$responseJSON = curl_exec($ch);
$response_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_status == 200) { // success
// remove any "problematic" characters from the json string and then decode
if (debug) {
echo "----finish API of getAPI inside basic_function with status==200---";
echo "<br>";
echo "-------the json response is-------" ; //.$responseJSON;
var_dump($responseJSON);
//print_r($responseJSON);
echo "<br>";
}
return json_decode( preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $responseJSON ) );
}
and I have a backend code which executed when cURL fired its operation with its URL. The backend code would therefore activated. So, I know cURL is operating.
$output=array (
'status'=>'OK',
'data'=>'12345'
)
$output=json_encode($output)
echo $output;
and $output shown on browser as {"status":"OK","data":"12345"}
However, I gone back to the frontend code and did echo $responseJSON, I got nothing. I thought the output of {"status":"OK","data":"12345"} would gone to the $responseJSON. any idea?
Here's output on Browser, something is very odd! the response_status got 200 which is success even before the parsing of API by the backend code. I expect status =200 and json response after the {"status":"OK","data":"12345"}
=========================================================================================
inside the get API of the basic functions
-------url of cURL is -----http://localhost/test/api/session/login/?device_duid=website&UserName=joe&Password=1234&Submit=Submit
----finish API of getAPI inside basic_function with status==200---
-------the json response is-------string(1153)
"************inside Backend API.php******************
---command of api is--/session/login/
---first element of api is--UserName=joe
--second element of api is---Password=1234
---third element of api is----Submit=Submit
----fourth element of api is---
-------inside session login of api-------------
{"status":"OK","data":"12345"}
Have you tried with curl_setopt($ch, CURLOPT_TIMEOUT, 10); commented?
See what happends if you comment that line.
Also try with the a basic code, if that works, smthing you added later is wrong:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Try var_dump($responseJSON)
If it returns false try
curl_error ( $ch )
Returns a clear text error message for the last cURL operation.
Are you sure your $url is correct?
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.