cURL call not working with no errors visible (WampServer 3) - php

I use curl with the Riot API. Everything is working fine on my live server but isn't in local. The curl extension is enabled in WampServer and I don't get any error messages, it's just a blank page.
Here's my code even if it's not actually relevant.
<?php
$private_key = "XXX";
function summoner_name($summoner, $server, $private_key) {
$summoner_encoded = rawurlencode($summoner);
$summoner_lower = strtolower($summoner_encoded);
$curl_url = 'https://' . $server . '.api.pvp.net/api/lol/' . $server . '/v1.4/summoner/by-name/' . $summoner . '?api_key='.$private_key;
$curl = curl_init($curl_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
function summoner_info_array_name($summoner) {
$summoner_lower = mb_strtolower($summoner, 'UTF-8');
$summoner_nospaces = str_replace(' ', '', $summoner_lower);
return $summoner_nospaces;
}
$summoner = "Test";
$server = "euw";
$summoner_info = summoner_name($summoner, $server, $private_key);
$summoner_info_array = json_decode($summoner_info, true);
$summoner_info_array_name = summoner_info_array_name($summoner);
$summoner_id = $summoner_info_array[$summoner_info_array_name]['id'];
$summoner_name_display = $summoner_info_array[$summoner_info_array_name]['name'];
$summoner_icon = $summoner_info_array[$summoner_info_array_name]['profileIconId'];
echo '<img src="http://ddragon.leagueoflegends.com/cdn/6.9.1/img/profileicon/'.$summoner_icon.'.png" /><br/><hr>'.$summoner_name_display;
?>
And here's my phpinfo() for curl extension.
Thanks in advance!
.

So, first, as #MaksimVolkob pointed out, and as we discussed in the comments, the first step to resolving these errors is to see what the error message actually is. curl_error() will give you this information.
Specifically, you're getting an SSL/TLS error:
SSL certificate problem: unable to get local issuer certificate' (length=63)
If you don't care about security (I do not recommend this for production applications, ever.), you can disable the SSL verification step that is failing:
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
The better way is to fix your CA certificate information by setting CURLOPT_CAINFO. This blog post explains this pretty well.
Edit: As OP discovered, this question has more specifics about getting cURL to recognize the proper CA certificate.

You can always call curl_getinfo() and curl_error() functions to check the problems on latest curl query.
Like this:
$result = curl_exec($curl);
if ($result === false) {
echo "Something is wrong here!\n".var_export(curl_error($curl), true)
. "\nQuery:".var_export(curl_getinfo($curl), true); exit();
}

Related

Url not loading error on geocoding requests

I previously had a Google geocoding script working to extract longitude and latitude using local addresses in a database.
In the last 6 months I've switched hosts, and apparently Google has implemented a new forward geocoder. Now it just returns the url not loading error from the xml script call.
I've tried everything to get my code working. Even sample coding from other websites won't work on my server. What am I missing? Is there possibly a server side setting that is blocking this from executing properly?
Attempt # 1:
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?new_forward_geocoder=true&address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";
echo $request_url;
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
return $status;
Simply returns url not loading. I have tried with and without the new_forwad_geocoder. I have also tried with and without https.
The $request_url string DOES return proper results if you simply copy and paste it to a browser.
Also tried this just to see if I could get a file to return. Attempt 2:
$request_url = "http://maps.googleapis.com/maps/api/geocode/json?new_forward_geocoder=true&address=1600+Amphitheatre+Parkway,+Mountain+View,+CA";//&sensor=true
echo $request_url."<br>";
$tmp = file_get_contents($request_url);
echo $tmp;
Any idea what could be causing the connection failure?
I wasn't ever able to get this working with XML again and the file_get_contents call was the culprit I'm almost positive.
I've posted what I did get to work with JSON/Curl (below) in case anyone has similar issues.
Ultimately I think the problems I ran into had to do with an upgrade to our Apache version on the server; and some of the default settings related to file_get_contents and fopen being more restrictive. I haven't confirmed this though.
This code does work though:
class geocoder{
static private $url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=";
static public function getLocation($address){
$url = self::$url.$address;
$resp_json = self::curl_file_get_contents($url);
$resp = json_decode($resp_json, true);
//var_dump($resp);
if($resp['status']='OK'){
//var_dump($resp['results'][0]['geometry']['location']);
//echo "<br>";
//var_dump($resp['results'][0]['geometry']['location_type']);
//echo "<br>";
//var_dump($resp['results'][0]['place_id']);
return array ($resp['results'][0]['geometry']['location'], $resp['results'][0]['geometry']['location_type'], $resp['results'][0]['place_id']);
}else{
return false;
}
}
static private function curl_file_get_contents($URL){
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
}
$Address = "1600 Amphitheatre Parkway, Mountain View, CA";
$Address = urlencode(trim($Address));
list ($loc, $type, $place_id) = geocoder::getLocation($Address);
//var_dump($loc);
$lat = $loc["lat"];
$lng = $loc["lng"];
echo "<br><br> Address: ".$Address;
echo "<br>Lat: ".$lat;
echo "<br>Lon: ".$lng;
echo "<br>Location: ".$type;
echo "<br>Place ID: ".$place_id;

cURL not getting HTML source of URL

I am trying to make a simple web crawler with PHP and I am having issues getting the HTML source of a given URL. I am currently using cURL to get the source.
My code:
$url = "http://www.nytimes.com/";
function url_get_contents($Url) {
if (!function_exists('curl_init')) {
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
if ($output === false) { die(curl_error($ch)); }
curl_close($ch);
return $output;
}
echo url_get_contents($url);
?>
Right now nothing gets echoed and there aren't any errors, so it is a bit of a mystery. Any suggestions or fixes will be appreciated
Edit: I added
if ($output === false) { die(curl_error($ch)); }
to the middle of the function and it ended up giving me an error (finally!):
Could not resolve host: www.nytimes.com
I still do not really know what the problem is. Any ideas?
Thanks
Turns out that it was not a cURL problem
My host server (Ubuntu VM) was working off of a "host-only" network adapter which blocked access to all other IPs or domains outside of it's host machine making it impossible for cURL to connect to URLs.
Once it was changed to "bridged" network adapter I had access to the outside world.
Hope this helps.
Variable case mismatch ($url vs. $Url). Change:
function url_get_contents($Url) {
to
function url_get_contents($url) {

Using cPanel API to create mySQL database and user in PHP

I am trying to create a mysql user and assign it to the created database.
I have tried setting $db_host as IP address, FQD, localhost (since I am running from the same server) etc. All of these has no success.
Any advice on what I'm doing wrong? (xmlapi.php is being incuded fine)
include("xmlapi.php");
$db_host = "usingfullyqualifieddomain";
$cpuser = "myuser";
$cppass = "mypass";
$xmlapi = new xmlapi($db_host);
$xmlapi->set_port(2083);
$xmlapi->password_auth($cpuser,$cppass);
$xmlapi->set_debug(1);
//create database
print $xmlapi->api1_query($cpuser, "Mysql", "adddb", 'myDatabaseName');
//create user
print $xmlapi->api1_query($cpuser, "Mysql", "adduser", array('user' => 'myDBUser','pass'=>'myDBPwd'));
The error is probably related to the way you're making your first service call, to create the database. Here is how I do it, on CPanel 11:
$auth_user = 'XXXXXX';
$auth_pass = 'XXXXX';
$server = 'XXXXXXXX.com';
$json_client = new \xmlapi($server);
$json_client->set_output('json');
$json_client->set_port(2083);
$json_client->password_auth($auth_user, $auth_pass);
$json_client->set_debug(1);
# Create Database
$result = $json_client->api1_query( $auth_user, 'Mysql', 'adddb', array($shop->alias));
var_dump($result);
Note that the fourth parameter should be an array with the parameters, and not a string as you are doing it.
Also notice that the print on the api call result is not very useful for debugging. Try var_dump'ing it, as it will show you some more interesting information to work on.
currently, cpanel support the cpanel json api..
here you can use this code ..
this worked for me well
<?php
$cpanelusername = "cpanelusername";
$cpanelpassword = "cpanelpassword";
$domain = 'mydomain.com';
$query = "https://$domain:2083/json-api/cpanel?cpanel_jsonapi_module=Mysql&cpanel_jsonapi_func=adddb&cpanel_jsonapi_apiversion=1&arg-0=DBNAME";
$curl = curl_init(); // Create Curl Object
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0); // Allow self-signed certs
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0); // Allow certs that do not match the hostname
curl_setopt($curl, CURLOPT_HEADER,0); // Do not include header in output
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); // Return contents of transfer on curl_exec
$header[0] = "Authorization: Basic " . base64_encode($cpanelusername.":".$cpanelpassword) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // set the username and password
curl_setopt($curl, CURLOPT_URL, $query); // execute the query
$result = curl_exec($curl);
if ($result == false) {
error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
// log error if curl exec fails
}
curl_close($curl);
print $result;
?>

XAMPP 1.7.7 in Windows 7 returns nothing using curl

I have a problem working with
curl_getinfo
I have already checked the php.ini for curl extension and everything seems to be fine and inside phpinfo();, curl is enable so I know that It shouldn't have any problem.
This function runs fine in my web server. It is my local machine with XAMPP 1.7.7 that gives me a hard time. Could this be because of firwall settings of my laptop?
Please note that the jpg file exists inside the Amazon s3 URL and I have checked the Amazon URL on the browser and it shows the image...
/////////////////// Edited //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
here is my code which is a function or method inside a class:
public function pictureExistence($id){
$url = AMAZON_S3_URL . $id . '.jpg';
//var_dump($url);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
//var_dump($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//var_dump($code);
if($code == 200){
$status = true;
}else{
$status = false;
}
curl_close($ch);
return $status;
}
Try the following code and check whether it's working for you. It has been tested to work fine on XAMPP 1.7.7 .
<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');
// Execute
curl_exec($ch);
// Check if any error occured
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}
// Close handle
curl_close($ch);
?>
I know this is old but i think you have the same problem i have. The problem is the httpS requets. In some way it doesn't work in xampp for windows, i remove the S and it works fine for me

post to wordpress with CURL

I tried to post to wordpress blog from extrnal php code , all of my files are in the same directory, public_html.
this is my code:
function wpPostXMLRPC1($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') {
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$content = array(
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category)
);
$params = array(0,$username,$password,$content,true);
$request = xmlrpc_encode_request('metaWeblog.newPost',$params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
but its wrong, the error is
Fatal error: Call to undefined function xmlrpc_encode_request()
i can post to my wordpress blog with microsoft word(publish->blogPost), so Help me
PHP's xmlrpc extension seems to be not enabled on your server.
Wordpress using http://scripts.incutio.com/xmlrpc/ as xmlrpc server, you don't need xmlrpc extension to post to your wp. Just follow the instruction http://scripts.incutio.com/xmlrpc/advanced-client-construction.php.
But if you want to post on another way, such as posting by email you can follow this tutorial codex.wordpress.org/Post_to_your_blog_using_email
I struggled with the same. I found a similar problem somewhere else on the net and tweaked to to fit Wordpress. Mind you Wordpress install (wordpress.org), not the blog hosting service at wordpress.com. This should be working provided you have curl and xmlwriter enabled:
<?php
class atompub
{
//public $parae = '';
function __construct($one, $two, $three, $four)
{
$this->author=$one;
$this->title=$two;
$this->categories=$three;
$this->body=$four;
}
function create_post()
{
$xmlwriter = new XMLWriter();
$xmlwriter->openMemory();
$xmlwriter->startDocument("1.0", "UTF-8");
$xmlwriter->startElement('entry');
$xmlwriter->writeAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$xmlwriter->startElement('author');
$xmlwriter->writeElement('name', $this->author);
$xmlwriter->endElement();
$xmlwriter->writeElement('title', $this->title);
$xmlwriter->startElement('content');
$xmlwriter->writeAttribute('type', 'html');
$xmlwriter->text($this->body);
$xmlwriter->endElement();
$xmlwriter->startElement('category');
$xmlwriter->writeAttribute('term', $this->categories);
$xmlwriter->endElement();
$xmlwriter->endElement();
$xmlwriter->endDocument();
return $xmlwriter->outputMemory();
}
function __destruct()
{
}
}
$target = "<URL til your WordPress installation>/wp-app.php/posts";
// Note that the directory "posts" are used for posting (POST method)
// "service" is used to pull info via the GET method (not shown here)
$user = "XXX"; // Substitue XXX with your WordPress username
$passwd = "YYY"; // Substitue XXX with your WordPress password
$author='Your Name';
$title='The title of your choice for your new entry';
$array_of_categories='Category';
$body='This is the main body. All the text goes in here';
$xml_post = new atompub($author,$title,$array_of_categories,$body);
$post = $xml_post->create_post();
$headers = array("Content-Type: application/atom+xml ");
$handle = curl_init($target);
$curlopt_array = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERPWD => $user.':'.$passwd,
CURLOPT_FOLLOWLOCATION => true,
CURLINFO_HEADER_OUT => true);
curl_setopt_array($handle, $curlopt_array);
$result = curl_exec($handle);
//var_dump($result);
$header_sent=curl_getinfo($handle);
//var_dump($header_sent);
if ($result === false) {
print "Got " . curl_errno($handle) . " : " . curl_error($handle) . "\n";
curl_close ($handle);
return;
}
$response_http_code = curl_getinfo ($handle, CURLINFO_HTTP_CODE);
if ($response_http_code != 201) {
print("HTTP status code: $response_http_code \n");
curl_close($handle);
return;
}
curl_close($handle);
?>
This should work directly, but you need to change the strings indicated (Blog URL, username, password, author, etc...). Beware that the login in insecure. This is only for demonstrating the functionality. You may also want to change the response code handling (which isn't mine, it came along with the original example which this is based upon).
On success Wordpress returns XML to you with details of the post event.
Fatal error: Call to undefined function xmlrpc_encode_request()
some times this error appear because xmlrpc extension is disabled.
execute phpinfo() to see if xmlrpc module displays or not.
If not, you need to enable it from php.ini by removing the semicolon, like
;extension=php_xmlrpc.dll to extension=php_xmlrpc.dll
and then restart Apache

Categories