passing json data as post - php

i am new to api so i may be completely wrong.
i was going through some docuementaion in github but could not find some answers so i am here
i want to pass url of these functions to api.php
after validating these key and secret.when i echo these data i get key, secret and url but how to get these details in php as its not a post and i cant use _post function to manipulate data based on url submitted and give the result
public function __construct($key = '', $secret = '', $timeout = 30,
$proxyParams = array()) {
$this->auth = array(
"auth" => array(
"api_key" => $key,
"api_secret" => $secret
)
);
$this->timeout = $timeout;
$this->proxyParams = $proxyParams;
}
public function url($opts = array()) {
$data = json_encode(array_merge($this->auth, $opts));
// echo $data;
$response = self::request($data, 'http://somesite.com/a/api.php', 'url');
return $response;
}
here is request function
private function request($data, $url, $type) {
$curl = curl_init();
if ($type === 'url') {
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
}
curl_setopt($curl, CURLOPT_URL, $url);
// Force continue-100 from server
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_FAILONERROR, 0);
curl_setopt($curl, CURLOPT_CAINFO, __DIR__ . "/cacert.pem");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
if (isset($this->proxyParams['proxy'])) {
curl_setopt($curl, CURLOPT_PROXY, $this->proxyParams['proxy']);
}
$response = json_decode(curl_exec($curl), true);
if ($response === null) {
$response = array (
"success" => false,
"error" => 'cURL Error: ' . curl_error($curl)
);
}
curl_close($curl);
return $response;
}
}
output of echo data is sufficient but its not post and i tried json_decode but nothing is coming to api.php
here is output of echo
{"auth":{"api_key":"be8fgdffgrfffrffc4b3","api_secret":"1b59fsfvfrgfrfvfb29d6e555a1b"},"url":"https:\/\/i.ndtvimg.com\/i\/2017-06\/modi-at-kochi-metro-station_650x400_81497685848.jpg","wait":true}
i tried these in api.php to get the data but nothing is working
$gggss['url'] = json_decode($data, true); //this returns an array
or
$gggss=$_POST['data'];
any help will be great

I think you are trying get urlencoded data, while your JSON string located in body of request. Try use this instead:
$entityBody = file_get_contents('php://input');

Related

PHP cUrl Handle resource is replaced by an integer

I'm using PHP curl to send a series of requests to a 3rd party server which requires login and then persisting the session cookie for that login.
So I wrapped the curl operation into this class:
class SoapCli {
private $ch;
private $id;
private $rc;
function __construct() {
$this->rc=0;
$this->id=bin2hex(random_bytes(8));
$this->ch = curl_init();
$time=microtime(true);
error_log(PHP_EOL.PHP_EOL."Instance id $this->id created ($time): \$this->ch = ".print_r($this->ch,true).PHP_EOL,3,"log.txt");
curl_setopt($this->ch, CURLOPT_AUTOREFERER,1);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, "");
curl_setopt($this->ch, CURLOPT_ENCODING, "");
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->ch, CURLOPT_VERBOSE, 1);
}
function Request(string $method, string $url, array $headers = array(), $postdata = "", $referer = null) {
$resp = new stdClass();
$resp->id = $this->id;
$this->rc++;
$time=microtime(true);
error_log("Instance id $this->id before request $this->rc ($time): \$this->ch = ".print_r($this->ch,true).PHP_EOL,3,"log.txt");
try {
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
if (isset($referer)) curl_setopt($this->ch, CURLOPT_REFERER, $referer);
if (preg_match("/^POST$/i",$method)===1) curl_setopt($this->ch, CURLOPT_POSTFIELDS, $postdata);
$resp->body = curl_exec($this->ch);
$resp->err_message = curl_error($this->ch);
$resp->err_number = curl_errno($this->ch);
$resp->info = curl_getinfo($this->ch);
}
catch (Exception $exception) {
$resp->err_message = $exception->getMessage();
$resp->err_number = $exception->getCode();
$resp->info = $exception->getTrace();
}
$time=microtime(true);
error_log("Instance id $this->id before request $this->rc ($time): \$this->ch = ".print_r($this->ch,true).PHP_EOL,3,"log.txt");
return $resp;
}
}
However, after the 3rd request, the protected variable that stored the curl handle resource has its content replaced by the value of 0 (integer) and I really can't figure out why. I could only collect this log:
Instance id 1cb893bc5b7369bd created (1547852391.7976): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 1 (1547852391.8025): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 1 (1547852392.0723): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 2 (1547852392.0778): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 2 (1547852392.357): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 3 (1547852392.3616): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 3 (1547852392.6225): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 4 (1547852393.0264): $this->ch = 0
Instance id 1cb893bc5b7369bd before request 4 (1547852393.0758): $this->ch = 0
Instance id 1cb893bc5b7369bd before request 5 (1547852394.8992): $this->ch = 0
Instance id 1cb893bc5b7369bd before request 5 (1547852394.9461): $this->ch = 0
EDIT: This is the code that consumes class SoapCli:
// index.php
$postdata = filter_input_array(INPUT_POST);
if ($_SESSION["logged_in"]===true) {
echo file_get_contents("main.html");
} else if (isset($postdata) && isset($postdata["action"])) {
$action = $postdata["action"];
if ($action==="Login" && isset($postdata["usrcpf"]) && isset($postdata["usrpwd"])) {
$username=$postdata["username"];
$password=$postdata["password"];
$sc=new SoapCli(); //instantiated here
$_SESSION["sc"]=$sc;
$login_response = $sc->Request(
"GET",
BASEURL."/login",
array(
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
"Cache-Control: max-age=0"
)
);
if ($login_response->err_number) {
echo file_get_contents("login_server_error.html");
} else {
$dom = new DOMDocument;
$dom->loadHTML($login_response->body);
$xdom = new DOMXPath($dom);
$csrf_token_nodes = $xdom->query("//input[#name='_csrf_token']/#value");
if ($csrf_token_nodes->length<1) {
echo file_get_contents("login_server_error.html");
} else {
$csrf_token = $csrf_token_nodes->item(0)->textContent;
$postdata = "_csrf_token=$csrf_token&_username=$username&_password=$password&_submit=Login";
$login_check_response = $sc->Request(
"POST",
BASEURL."/login_check",
array(
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Content-Type: application/x-www-form-urlencoded",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1"
),
$postdata,
BASEURL."/login"
);
if ($login_check_response->err_number) {
echo file_get_contents("login_server_error.html");
} elseif (strpos($login_check_response->body, "api.js")) {
echo file_get_contents("login_auth_error.html");
} else {
$route_userinfo = $sc->Request(
"POST",
BASEURL."/route",
array(
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Accept: */*",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Content-Type: application/json",
"X-Requested-With: XMLHttpRequest",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
),
USERINFO_JSON,
BASEURL."/"
);
if ($route_userinfo->err_number) {
echo file_get_contents("login_server_error.html");
} else {
$_SESSION["logged_in"]=true;
$_SESSION["user_info"]=json_decode($route_userinfo->body);
header("Location: ".$_SERVER["PHP_SELF"], true, 303);
}
}
}
}
} else {
http_response_code(400);
}
} else {
echo file_get_contents("login.html");
}
and
// ajax.php (called by JS in main.html, which is loaded after login)
if ($_SESSION["logged_in"]===true) {
$postdata = filter_input_array(INPUT_POST);
if (isset($postdata)) {
if (isset($postdata["content"])) {
if ($postdata["content"]==="tasks") {
$sc=$_SESSION["sc"];
$route_tasks = $sc->Request(
"POST",
BASEURL."/route",
array(
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Accept: */*",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Content-Type: application/json",
"X-Requested-With: XMLHttpRequest",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
),
TAKS_JSON,
BASEURL."/"
);
if ($route_tasks->err_number) {
echo file_get_contents("ajax_server_error.html");
} else {
$tarefas=json_decode($route_tasks->body);
if (isset($tarefas) && is_array($tarefas->records)) {
foreach($tarefas->records as $i=>$tarefa){
echo "<p>".$tarefa->especieTarefa->nome."</p>";
}
} else {
http_response_code(500);
}
}
}
} else {
http_response_code(400);
}
} else {
http_response_code(400);
}
} else {
http_response_code(403);
}
Since the variable SoapCli::ch is not accessible out of the class, I really can't see how its content could be changed without a statement. I coundn't find any information about a kind of http request/response which would destroy the handle, either.
Additional info
Whatever it is, it doesn't have to do with the request, because i tried to repeat request #3, which is valid and receives a valid response, and its repetition fails because of the handle is gone.
Plus, what I'm trying to implement in PHP is already done by a fully functional .NET desktop (winforms) application, so it's not like it can't be done for external reasons. I'm just trying to do with PHP curl what I did with System.Net.HttpWebRequest, and stumbled upon the problem described at this post.
How can I preserve the handle as long as I need it?
I'm using PHP 7.2 on IIS Express/Windows 10.
Short answer is: the handle does not exist when you are trying to use it inside ajax.php
Inside ajax.php, take a look at the following line:
$sc=$_SESSION["sc"];
And then you call:
$route_tasks = $sc->Request(
...
);
So you instaciated your class inside index.php and all the 3 calls made there where succesfull, then you write an object into the $_SESSION["sc"] variable and apparently the object gets encoded and decoded correctly by php's session handler which is why you are still able to call the method Request inside ajax.php after retrieving the object.
While you are indeed using an object in ajax.php it is not the same instance of the object that was created by index.php as that instance belongs to the index.php thread along with the curl handle; calling ajax.php from index.php will create a diffrent thread to handle it and will require a new curl handle as well.
Change $sc=$_SESSION["sc"]; to $sc=new SoapCli(); so the curl handle can be created before used.
I'm posting this answer just to show how I went around the problem that was described and explained by #Solrac in his answer (which is correct and I'll accept):
class SoapCli {
private $ch;
private $cookiepot;
function __construct() {
$this->cookiepot=tempnam(sys_get_temp_dir(),"CookieJar");
$this->reconstruct();
}
function reconstruct() {
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_AUTOREFERER, true);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookiepot);
curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookiepot);
curl_setopt($this->ch, CURLOPT_ENCODING, "");
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->ch, CURLOPT_HEADER, true);
curl_setopt($this->ch, CURLINFO_HEADER_OUT, true);
curl_setopt($this->ch, CURLOPT_MAXREDIRS, 32);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_VERBOSE, true);
}
function Request(string $method, string $url, array $headers = array(), $postdata = "", $referer = "") {
if (!is_resource($this->ch)) {
$this->reconstruct();
}
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($this->ch, CURLOPT_REFERER, $referer);
if (preg_match("/^POST$/i",$method)===1) curl_setopt($this->ch, CURLOPT_POSTFIELDS, $postdata);
$response=curl_exec($this->ch);
list($headers,$body)=preg_split("/\r\n\r\n(?!HTTP)/", $response, 2);
$resp_obj = (object) array(
"body"=>$body,
"headers"=>$headers,
"err_number"=>curl_errno($this->ch),
"err_message"=>curl_error($this->ch),
"info"=>curl_getinfo($this->ch)
);
return $resp_obj;
}
function log(string $text) {
file_put_contents($this->id."log.txt",$text.PHP_EOL,FILE_APPEND|FILE_TEXT|LOCK_EX);
}
}

Cannot extract the data from the website using PHP cURL

I am working on a project which needs to get the data from other webpage:
https://eth.ethfans.org/#/miner?0x2998850087633a4806191960c94ed535d97da598
I am trying to use the function cRUL:
<?php
$url = "https://eth.ethfans.org/#/miner?0x2998850087633a4806191960c94ed535d97da598";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>
However, I can only get the layout of the site, but I cannot get the data inside.
Can anyone help for this ?
Thanks in Advance.
Regards,
Alex
Use str_get_html to fetch the data from the layout:
$get_html = str_get_html($contents);
Example:
function check()
{
$url = "https://stackoverflow.com/questions/49248329/cannot-extract-the-data-from-the-website-using-php-curl";
$get_html = $this->get_curl($url);
#print_r($get_html); exit;
$get_html = str_get_html($get_html);
$fb = NULL;
foreach ($get_html->find('a') as $v) { // you can get what data from the layout
if(strpos($v->href, 'facebook'))
{
echo $fb = $v->href;
echo "\n";
break;
}
}
unset($get_html);
}
public function get_curl($url)
{
ob_start();
$ch = curl_init($url);
$headers = [
'Accept-Language: en-US,en;q=0.5',
'Cache-Control: no-cache',
'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/51.0',
];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_URL, $url);
$response = curl_exec ($ch);
curl_close ($ch);
ob_end_flush();
return $response;
}
you're hitting the wrong url, the page you're hitting only contains the layout and the javascript required to fetch the actual data, then the javascript fetch the data from https://eth.ethfans.org/api/page/miner?value=2998850087633a4806191960c94ed535d97da598 , so, do as the javascript does, and fetch that url.

file_get_contents not retrieving page contents

OK, before saying this is a duplicate just read a bit....
I have been trying to echo contents of URL that has allow_url_fopen disabled for HOURS now, I have tried every solution posted on stack overflow. EXAMPLE:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
curl_close($ch);
Doesn't WORK
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Doesn't WORK
$url = "http://www.google.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
Doesn't WORK
fopen("cookies.txt", "w");
$url="http://adfoc.us/1575051";
$ch = curl_init();
$header=array('GET /1575051 HTTP/1.1',
'Host: adfoc.us',
'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language:en-US,en;q=0.8',
'Cache-Control:max-age=0',
'Connection:keep-alive',
'Host:adfoc.us',
'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,0);
curl_setopt( $ch, CURLOPT_COOKIESESSION, true );
curl_setopt($ch,CURLOPT_COOKIEFILE,'cookies.txt');
curl_setopt($ch,CURLOPT_COOKIEJAR,'cookies.txt');
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
$result=curl_exec($ch);
curl_close($ch);
Doesn't WORK
// create the Gateway object
$gateway = new Gateway();
// set our url
$gateway->init($url);
// get the raw response, ignore errors
$response = $gateway->exec();
Doesn't WORK
$file = "http://www.example.com/my_page.php";
if (function_exists('curl_version'))
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $file);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($curl);
curl_close($curl);
}
else if (file_get_contents(__FILE__) && ini_get('allow_url_fopen'))
{
$content = file_get_contents($file);
}
else
{
echo 'You have neither cUrl installed nor allow_url_fopen activated. Please setup one of those!';
}
This doesn't work.
The page I am trying to use file_get_contents on is not on my website. I am trying to use file_get_contents so i can make a simple API for the site owner by reading a page and checking if a certain word is present on the page.
But yeah if anyone has any suggestions PLEASE post below :)
You can check first weather the site is available or not for example a sample code
Code taken from here:
<?php
$cURL = curl_init('http://www.technofusions.com/');
curl_setopt ( $cURL , CURLOPT_RETURNTRANSFER , true );
// Follow any kind of redirection that are in the URL
curl_setopt ( $cURL , CURLOPT_FOLLOWLOCATION , true );
$result = curl_exec ( $cURL );
// Getting HTTP response code
$answer = curl_getinfo ( $cURL , CURLINFO_HTTP_CODE );
curl_close ( $cURL );
if ( $answer == ' 404 ' ) {
echo ' The site not found (ERROR 404)! ' ;
} else {
echo ' It looks like everything is working fine ... ' ;
}
?>
For a full answer you can got to this tutorial Curl IN PHP

Recaptcha Request is returning Null

I'm trying to implement this Recaptcha request into my sign-up form, however it isn't working. The cURL/JSON request returns null when I successfully validate the Recaptcha on my website.
I tried using var_dump on the "error-codes": from the JSON request, and it only returns null; whereas in this document it shows that it is clearly meant to output two items in the JSON request.
Thanks in advance, I haven't done much work with JSON/cURL, so be easy on me.
Here's my code:
PHP
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$recaptcha = $_POST['g-recaptcha-response'];
if(!empty($recaptcha)) {
function getCurlData($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
$curlData = curl_exec($curl);
curl_close($curl);
return $curlData;
}
$google_url = "https://www.google.com/recaptcha/api/siteverify";
$secret = 'You will never know >:D';
$ip = $_SERVER['REMOTE_ADDR'];
$url = $google_url . "?secret=" . $secret . "&response=" . $recaptcha . "&remoteip=" . $ip;
$res = getCurlData($url);
$res = json_decode($res, true);
// var_dumping returns null
var_dump($res);
//reCaptcha success check
if($res['success'] == true) {
echo "Recaptcha was successfully validated";
} else {
echo "Recaptcha was not validated, please try again";
}
} else {
echo "You didn't validate the Recaptcha";
}
}
?>
HTML
<form action="home.php" method="post">
<div class="g-recaptcha" data-sitekey="I removed it for this post"></div>
<input class="btn btn-primary" type="submit" name="submit" value="SIGN UP" />
</form>
Here is my code running without problem:
Client Side:
<div class="g-recaptcha" data-sitekey="PUBLIC_KEY"></div>
Server Side:
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
$privatekey = "SECRET_KEY";
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => $privatekey,
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
);
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data
);
$ch = curl_init();
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
curl_close($ch);
}
$jsonResponse = json_decode($response);
if ($jsonResponse->success === true) {
doSomething();
}
else {
doSomeOtherThing();
}
Working here! :)
Your problem is probably with the SSL certificate.
You can put this line to let curl ignore it:
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false)
However, you can put this to test on your localhost but when uploading your website, it is better to have an SSL certificate and this line removed.
Api says: METHOD: POST, you are sending "GET" request.
Check CURLOPT_POST and CURLOPT_POSTFIELDS option on http://php.net/manual/en/function.curl-setopt.php
EDIT:
I just checked the API, it work with GET too. I don't see any error in your code. Could you temporary change your function to:
function getCurlData($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
$curlData = curl_exec($curl);
if (!$curlData) {
throw new \Exception('Curl error: ' . curl_error($curl));
}
curl_close($curl);
return $curlData;
}

JSON decode curl issue

Hi I'm trying to make this api call from wikipedia using this url, however it says it's null when I dump the variable. This function works for my other json api calls but not for this, I tested it in the broswer manually it gives me a result. Here is my attempt
$url = 'http://en.wikipedia.org/w/api.php?action=query&format=json&titles=Image:Romerolagus diazi (dispale) 001.jpg&prop=imageinfo&iiprop=url';
$result = apicall($url);
var_dump($result);
function apicall($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'MyBot/1.0 (http://www.mysite.com/)');
$result = curl_exec($ch);
if (!$result) {
exit('cURL Error: '.curl_error($ch));
}
$var = json_decode($result);
return $var;
}
urlencode() problem, modify like this
<?php
$url = 'http://en.wikipedia.org/w/api.php';
$titles = urlencode('Image:Romerolagus diazi (dispale) 001.jpg');
$queryStr = 'action=query&format=json&titles='.$titles.'&prop=imageinfo&iiprop=url';
$url = $url . '?' . $queryStr;
$result = apicall($url);
var_dump($result);
function apicall($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
$result = curl_exec($ch);
if (!$result) {
exit('cURL Error: '.curl_error($ch));
}
var_dump($result);
$var = json_decode($result);
return $var;
}
You should consider using http_build_query() to build the URL:
$url = 'http://en.wikipedia.org/w/api.php?' . http_build_query(array(
'action' => 'query',
'format' => 'json',
'titles' => 'Image:Romerolagus diazi (dispale) 001.jpg',
'prop' => 'imageinfo',
'iiprop' => 'url',
));

Categories