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. ]
Related
I made function to read GeoPlugin data for my websites and on one server I find wierd issue. All cURL request are refused. Here is part of my code:
protected $url='http://www.geoplugin.net/json.gp?ip={IP}&base_currency={CURRENCY}';
protected function __get_data($ip=false, $currency='')
{
// Current or custom IP
$ip = ((is_bool($ip) && $ip==false) ? $this->__ip() : $ip);
if($ip!='127.0.0.1' || $ip!='0.0.0.0')
{
// Configure GET function
$url = str_replace('{IP}', $ip, $this->url );
if(empty($currency))
$url = str_replace( '&base_currency={CURRENCY}', '', $url);
else
$url = str_replace( '{CURRENCY}', $currency, $url);
// Get content from URL
if(function_exists("curl_init"))
{
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_CONNECTTIMEOUT ,5);
curl_setopt($cURL, CURLOPT_TIMEOUT , 2);
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($cURL);
curl_close($cURL);
}
else
{
$result = file_get_contents($url);
}
// Return objects from JSON data
if($result!=false)
{
return json_decode($result);
}
else return false;
}
else return false;
}
## find real IP adress of visitor ##
protected function __ip()
{
$findIP=array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR'
);
$ip = '';
foreach($findIP as $http)
{
if(function_exists("getenv"))
{
$ip = getenv($http);
}
else
{
if (array_key_exists($http, $_SERVER) !== false){
foreach (explode(',', $_SERVER[$http]) as $findIP){
$ip = trim($findIP);
}
}
}
if(function_exists("filter_var") && !empty($ip))
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) return $ip;
}
else if(preg_match('/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/', $ip) && !empty($ip))
{
return $ip;
}
}
return '0.0.0.0';
}
On arround90 websites everithing work perfectly, on one website with var_dump() I find that connection are refused. I try also with file_get_contents and the same results. I try also just cURL call in some test PHP file separated from website and the same results. What can be a problem?
It's may be DNS problem;
It's may be poor connection (more time needed for loading);
Your query may be banned from target server, because from your IP (source's server IP) too much queries for a time, more than limits.
What you can do:
Make sure that you can open target url from source server without using cURL (if you use simple hosting, I mean not VPS, you'll can't check it);
Increase values for CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT;
If problem will not solved, you should use proxy with cURL (look for official documentation about CURLOPT_PROXY and other proxy options for curl_setopt function).
cURL might be disabled in your server.
Please run the phpinfo() to check the status of cURL.
If it is disabled, please install cURL and enable it in PHP.
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
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/
I have a PHP page that needs to send data to another PHP page during the page execution and receive data back.
Can this be done? If so, how?
Update:
Sorry - meant to say that the second script is on a completely different server and domain.
Like how is Stripe doing it with their PHP option: https://stripe.com/docs/api?lang=php
EDIT
Looking at the Stripe source code, you will see they do use cURL (ApiRequestor.php):
private function _curlRequest($meth, $absUrl, $headers, $params, $myApiKey)
{
$curl = curl_init();
$meth = strtolower($meth);
$opts = array();
if ($meth == 'get') {
$opts[CURLOPT_HTTPGET] = 1;
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else if ($meth == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = self::encode($params);
} else if ($meth == 'delete') {
$opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else {
throw new Stripe_ApiError("Unrecognized method $meth");
}
$absUrl = self::utf8($absUrl);
$opts[CURLOPT_URL] = $absUrl;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_CONNECTTIMEOUT] = 30;
$opts[CURLOPT_TIMEOUT] = 80;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_HTTPHEADER] = $headers;
$opts[CURLOPT_USERPWD] = $myApiKey . ':';
$opts[CURLOPT_CAINFO] = dirname(__FILE__) . '/../data/ca-certificates.crt';
if (!Stripe::$verifySslCerts)
$opts[CURLOPT_SSL_VERIFYPEER] = false;
curl_setopt_array($curl, $opts);
$rbody = curl_exec($curl);
if ($rbody === false) {
$errno = curl_errno($curl);
$message = curl_error($curl);
curl_close($curl);
$this->handleCurlError($errno, $message);
}
$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array($rbody, $rcode);
}
cURL - from the PHP manual:
PHP supports libcurl, a library created by Daniel Stenberg, that
allows you to connect and communicate to many different types of
servers with many different types of protocols. libcurl currently
supports the http, https, ftp, gopher, telnet, dict, file, and ldap
protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP
PUT, FTP uploading (this can also be done with PHP's ftp extension),
HTTP form based upload, proxies, cookies, and user+password
authentication.
<?php
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
Use include('script2.php') from script1.php
Then you can call the functions within script2.php (assuming they have global scope) from script1.php.
The other possibility if you want to call a PHP script like the end user via URL's, cURL is a good tool to know about.
http://php.net/manual/en/book.curl.php
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