How to select documentDB database azure using php? - php

I am trying to connect with documentDB Azure using php but I didn't get it to work. Now I am using the code given here but even that is not working. I can connect to the documentDB account but the problem is I can't select the database in my account. This is the selectDB function I am using
public function selectDB($db_name)
{
$rid_db = false;
$object = json_decode($this->listDatabases());
$db_list = $object->Databases;
foreach ($db_list as $value)
{
if ($value->id === $db_name)
{
$rid_db = $value->_rid;
}
}
if (!$rid_db)
{
$object = json_decode($this->createDatabase('{"id":"' . $db_name . '"}'));
$rid_db = $object->_rid;
}
if ($rid_db)
{
return new DocumentDBDatabase($this, $rid_db);
}
else
{
return false;
}
}
I tried to debug it and find that listDatabases() function is not working (not selecting the databases in account) Here is the listDatabase() function:
public function listDatabases()
{
$headers = $this->getAuthHeaders('GET', 'dbs', '');
$headers[] = 'Content-Length:0';
$options = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HTTPGET => true,
);
return $this->request("/dbs", $options);
}
Can someone help me with this issue?

Regarding to your issue, you can add var_dump(curl_error($curl)); in the request function in phpdocumentdb.php you required for troubleshooting the curl issues.
If you are developing on local or some dev environment, you may occur the SSL certificate issue. The curl error may output the message: SSL certificate problem: unable to get local issuer certificate.
And for developing, you can simple add sentence curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); in the request function in phpdocumentdb.php to bypass the SSL verification.
If you are in prod env, you should create SSL certificate in your PHP runtime. Refer to https://blogs.msdn.microsoft.com/azureossds/2015/06/12/verify-peer-certificate-from-php-curl-for-azure-apps/ for more.

Related

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

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();
}

Send cURL requests through tor?

I have some code that sends curl requests to a website but it only has the one website in it at the moment and I don't want them wrongly banning my server IP. Is there anyway I can send those cURL requests through the tor network?
What software would I need to do it?
Running CentOS 6.5
public function checkLogin2($email, $password, $cookiefile){
$cookiefile = 'cookies/'.$cookiefile;
$handle = fopen($cookiefile, 'w+');
#$proxy = 'proxy-nl.privateinternetaccess.com:1080';
#$us = 'x9597458:Th3hXjVyuD';
$this->_curl->setCookieFile($cookiefile);
#$this->_curl->addOption(CURLOPT_PROXY, $proxy);
#$this->_curl->addOption(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
#$this->_curl->addOption(CURLOPT_PROXYUSERPWD, $us);
$this->_curl->setUserAgent('FreshAndroidApp-1.3.1');
$this->_curl->addHeader('Content-Type', 'application/x-www-form-urlencoded');
$this->_curl->addHeader('Cookie', 'JSESSIONID=' . strtoupper(md5(time())));
$this->_curl->addHeader('Cookie2', '$Version=1');
try {
$HTML = $this->_curl->post("URL HERE",
array('password' => $password,
'emailAddress' => $email
));
if(!self::isJson($HTML)){
return '{"status":"uncheck", "msg":"<font color="red"><b>Uncheck</b></font> => ' .$email.'|'.$password.'"}';
}
$resp = json_decode($HTML);
if($resp->{'status'} == "success"){
$details = $this->_curl->get('URL HERE');
return $details;
} else if ($resp->{'status'} == "failure"){
return '{"status":"failure"}';
}
fclose($handle);
} catch (CurlWrapperException $e){
return '{"status":"socksfailure", "msg":"'.$proxy. ' => Die or timeout"}';
}
fclose($handle);
}
You would need to install and run TOR, as explained in this link: https://www.torproject.org/docs/rpms.html.en
Then, if your code is right (I don't know much of PHP), just do:
$this->_curl->addOption(CURLOPT_PROXY, 127.0.0.1:9050);
$this->_curl->addOption(CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
Because TOR proxy runs by default on port 9050.
You can also put another IP instead of 127.0.0.1, if you are running TOR in another machine.
I think this should work

Curl Replacement on GAE for BaseFacebook class

I am wanting to implement federated logins to my GAE app in PHP.
I have looked at a couple of third parties like janrain or the OAuth plugin, but I just can't integrate them very easily and I don't want to pay or have limits. I just want something simple that will hook into the GAE authentication model.
At the moment I have google and yahoo as they are the only 2 that use an endpoint that doesn't require a username, and I can use the UserService::createLoginUrl()
I want to add Facebook, Twitter and Microsoft, plus others I guess, but these are my aim for now.
I started with facebook I am trying to use the facebook connector. Initially I started with the Javascript API and it worked well until you sit behind a firewall and facebook is blocked (then $.getScript() fails unmanageably), so I then started looking at the PHP library (at least then the blocking is a) visible to the user, b) not my responsibility for trapping and handling and c) fits nicely into the URL endpoint model I have)
The problem is that the BaseFacebook class uses cURL. GAE does not.
Does anyone know of a way to build the authentication into GAE so I can use login: required or if not, can anyone with better streams/curl knowlege than me replace the cURL stuff in the BaseFacebook class. Here is the function that's causing my grief:
/**
* Makes an HTTP request. This method can be overridden by subclasses if
* developers want to do fancier things or use something other than curl to
* make the request.
*
* #param string $url The URL to make the request to
* #param array $params The parameters to use for the POST body
* #param CurlHandler $ch Initialized curl handle
*
* #return string The response text
*/
protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->getFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
$errno = curl_errno($ch);
// CURLE_SSL_CACERT || CURLE_SSL_CACERT_BADFILE
if ($errno == 60 || $errno == 77) {
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . DIRECTORY_SEPARATOR . 'fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
// With dual stacked DNS responses, it's possible for a server to
// have IPv6 enabled but not have IPv6 connectivity. If this is
// the case, curl will try IPv4 first and if that fails, then it will
// fall back to IPv6 and the error EHOSTUNREACH is returned by the
// operating system.
if ($result === false && empty($opts[CURLOPT_IPRESOLVE])) {
$matches = array();
$regex = '/Failed to connect to ([^:].*): Network is unreachable/';
if (preg_match($regex, curl_error($ch), $matches)) {
if (strlen(#inet_pton($matches[1])) === 16) {
self::errorLog('Invalid IPv6 configuration on server, '.
'Please disable or get native IPv6 on your server.');
self::$CURL_OPTS[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$result = curl_exec($ch);
}
}
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
login: required in Google App Engine is not extensible by your application. If you wish to offer login from multiple providers you will need to turn that off in your app.yaml and instead handle the authentication within your application - which it sounds like you're working on.
You might want to look at using the Google Identity Toolkit - it offers login for some of the providers you list (more than just Google) and has PHP examples:
https://developers.google.com/identity-toolkit/

How to use REST services hosted on Apache 2.2 via cURL to send SSL requests?

What is the procedure for sending secure data (login id, password) over https to an Apache 2.2 server with self-signed certificates?
<?php
$uid=$_POST['user'];
$password=$_POST['pass'];
$url = "https://example.com/login";
$cert_file = './certificate.com.pem';
$cert_password = 'xxxxxx';
$ch = curl_init();
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POSTFIELDS => 'uid:'.$uid.'&password:'.$password,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true,
CURLOPT_URL => $url ,
CURLOPT_SSLCERT => $cert_file ,
CURLOPT_SSLCERTPASSWD => $cert_password ,
CURLOPT_POST => true
);
curl_setopt_array($ch , $options);
$output = curl_exec($ch);
if(!$output)
{
echo "Curl Error : " . curl_error($ch);
}
else
{
echo htmlentities($output);
}
?>
the ERROR we are getting is :
curl error:unable to use client certificate (no key found or wrong passphrase ?)
You'd need to think about it this way:
Your local server asks the remote server to validate the login info. — You would need to make an exception for the self-signed certificate and remember it. (It would be a really a bad habit to simply ignore certificate errors.)
Your local server then checks if the data the remote one sent back isn't an error message and is indeed valid JSON data.
Here's some info on how to make curl remember the self-signed certificate and trust it permanently: http://turboflash.wordpress.com/2009/06/23/curl-adding-installing-trusting-new-self-signed-certificate/ — It should work for the command-line utility just as well as the PHP module.
So, let's make a little function for it. — I'm not going to test its functionality, so I can't promise to have it perfectly error free. I'm also using some practices I wouldn't use in production code, don't account for an API key, use GET parameters and I also make the remote server responsible for any serious sort of error checking and sanitation.
<?php
function remote_login($username, $password) {
/*
Initialize the curl object
*/
$login = curl_init();
/*
Some sanitation. This is probably not enough though.
*/
$username = urlencode($username);
$password = urlencode($password);
/*
Set the url we're going to use.
REST services use clean urls, but here we simply use GET parapeters.
*/
$login_url = 'https://example.com/?username='+$username+'&password='+$password;
curl_setopt($login, CURLOPT_URL, $login_url);
/*
Tell curl we would like to use the data returned from the remote server
*/
curl_setopt($login, CURLOPT_RETURNTRANSFER, true);
/*
Set the returned data as a variable
*/
$login_data = curl_exec($login);
$login_json = json_decode($login_data);
/*
We're not going to do anything else if we encounter any sort of error.
*/
if (($login_data == false) || ($login_json == false)) {
return false;
}
/*
Return the login result as a JSON object
*/
return json_decode($login_data);
}
?>
Hope this helps.

enabling curl extension in php for 000webhost.com

So I'm trying to integrate my app with facebook and I'm using the default example.php's code as my index.php. I've changed the appID and appSecret to match my app's id and secret, whenever I test the code on facebook, it will throw an exception namely UnhandledCurlException. Wraping the code with try and catch will only return 0 whenever I call the getUser() method.
I'm aware that I could enable the curl extension on php.ini, but I can only find that on my localhost but not on the server(000webhost.com) which I used to deploy my app.
I've also heard that it's possible to use .htaccess file to explicitly modify the php configurations and hence enable the curl extension, anyone knows how to do that? or are there any other alternatives which I missed?
This is the function that throws error:
protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->getFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
$errno = curl_errno($ch);
// CURLE_SSL_CACERT || CURLE_SSL_CACERT_BADFILE
if ($errno == 60 || $errno == 77) {
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . DIRECTORY_SEPARATOR . 'fb_ca_chain_bundle.crt');
$result = curl_exec($ch); //the line 1003
}
// With dual stacked DNS responses, it's possible for a server to
// have IPv6 enabled but not have IPv6 connectivity. If this is
// the case, curl will try IPv4 first and if that fails, then it will
// fall back to IPv6 and the error EHOSTUNREACH is returned by the
// operating system.
if ($result === false && empty($opts[CURLOPT_IPRESOLVE])) {
$matches = array();
$regex = '/Failed to connect to ([^:].*): Network is unreachable/';
if (preg_match($regex, curl_error($ch), $matches)) {
if (strlen(#inet_pton($matches[1])) === 16) {
self::errorLog('Invalid IPv6 configuration on server, '.
'Please disable or get native IPv6 on your server.');
self::$CURL_OPTS[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$result = curl_exec($ch);
}
}
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
First of all make sure if cURL extension is really configured or not by using this code.
<?php
echo function_exists('curl_version') ? 1:0; // 1 = enabled , 0 = disabled.
If it is disabled, Kindly ask your webhosting provider to enable the extension. [I don't think that's a hard thing to do , instead of playing around .htaccess and other means to enable cURL without their knowledge. ]

Categories