curl_init intermittently returns NULL - php

I have recently moved servers and a PHP script that has worked for a long time no longer works. I've tracked it down to a wrapper class I have for easily doing multi-curl operations. The whole script works start to finish occasionally but fails most of the time.
However, during my testing I found that when the script failed it failed here:
$ch = curl_init();
When the script failed $ch was NULL. The documentation (php.net) says that it should return a resource on success and FALSE on failure not NULL.
I'm using Ubuntu 12.04 server. As I've said this script ran for a long time. So I'm thinknig one of a few things has happened. First, the image from my hosting company is supposed to be the latest with the latest security patches, etc. Could there have been a PHP patch that messed something up? Second, there's a resource issue I didn't experience on the previous machine (or any other machine I've used for that matter). Finally, there's something wrong with the image my hosting company installed.
If anyone has any experience with this type of error I'd love to hear it.
Update:
$ch = curl_init();
echo '<br>Res: ' . var_dump($ch);
Returns:
Res: NULL

I have come across a similar problem, and my guess is that curl_init() is disabled in your php server, for some reason that i do not know .
Please check if curl_init() is enabled in your system, and please set error-reporting(E_ALL); at the top of your script to see what might be wrong.
In my case, i am receiving a warning saying that curl_init() is disabled for security reasons.

Related

file_get_contents() security issue on local domain only with CentOS security settings

I know there are a hundred posts about file_get_contents() on SO but nothing seems to solve my problem:
Everything was working fine fifteen minutes ago, until I ran some security stuff via SSH. I added some iptables rules and I file_get_contents and I ran service proftpd restart and a few installs/uninstalls which seems to have disabled PHP's fopen() functions somehow.
In php.ini, I have: allow_url_fopen = on & extension=php_openssl.dll on
I'm trying a simple test: (this file loads fine via the browser)
echo file_get_contents("https://www.this-domain.com/logo.gif");
//...failed to open stream:HTTP request failed! HTTP/1.1 404 Not Found...
//However both of the following work absolutely fine:
echo file_get_contents("https://www.google.com/");
echo file_get_contents("/home/user/domains/this-domain.com/private_html/media/logospin.gif");
I cannot change the file_get_contents() code (to cURL or otherwise) - this is a server settings issue. Possibly something to do with the firewall. Can someone please suggest a fix?
The problem was in fact a DNS issue. file_get_contents() was bizarrely routing through our backup nameservers (ns3 & ns4) for some reason, while browsers were routing through the primary nameservers (ns1 & ns2). Unlike the primaries, the backups point to a different server, which does not yet have identical files - hence the unusual 404.
I had set up these backup nameservers only a few hours before tinkering with the firewall etc and by the time they propagated, it looked very much like the ssh commands had taken file_get_contents() offline.
Thanks for all the comments guys - very much appreciated.

Unable to use PHP curl on amazon ec2 free tier

I am currently moving my web app to amazon ec2. Since it's only for testing, I use the free version called ec2 free tier with windows server 2008 instance. However, Although I have done all I know and read this thread ( How to enable cURL in PHP / XAMPP ). I just couldn't use curl on my php script. it always creates the error
Call to undefined function curl_init() in C:\xampp\htdocs\index.php on line 2
Here are all thing I have tried
Install Wamp ( I tried it on XAMPP to)
Uncomment out php_curl in php.ini file ( and restart apache)
Copy two dll files to both system32 and syswow64
Could it have to do with the fact that I am using free vps?
Update:
Also, when I started the apache server in XAMPP , this error appeared
'PHP Startup: unable to load dynamic library curl.dll'
However, I have double checked the ext directory and the php_curl.dll was in there.
i think curl need to access remote sever from our web server. so i opened all traffic in my server outbound rule and it works. i think this is not good solution. still look for better way.
nope.
be sure, that you have the files in the right place, usually its in the plugins folder for php! maybe you cann add a absolute path to your php.ini!
be sure, you edit the correct ini file!
php completly independent to your operatingsystem!
just be sure to doublecheck everything. because its not saying, it has trouble loading your extention, its just saying, the function your trying to call, is not there. so i assume your extention ist not loading at all! :)
One reason I did notice for this cURL plugin to malfunction was the availability of copies of libeay32.dll and ssleay32.dll files. Please check whether your system32 folder has such copies and if so, please rename them to some other names and copy the ones found with the php installation. Sometimes you may need to restart your machine. This was documented here some time ago.
I had a similar problem, but it occours just with requests under https. I tried to create a curl request directly from the ec2 machine and got a error: "curl: (77) error setting certificate verify locations".
It looks like some kind of ssl validation fail because of a certificate not found. So I used a parameter -k (or --insicure) in my curl command, to ignore this validation and after that my curls request did directly from ec2 machine worked.
So I tried to apply a similar ideia in my curl command in php, (I suppoused that the curl php extension forward this requests to the operation system) and I found this curl opt:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
After that it works to me.
Probably this isn't the best way to solve the problem, but solved my problem temporarelly.

cURL issues with Google Voice "APIs" running on XAMPP/Windows 7

I'm using aaronpk's Google Voice APIs to send and receive SMS messages in Google Voice. I've uncommented the "extension=php_curl.dll" line in the php.ini and have confirmed that cURL is working. I'm now stuck at this point and I keep receiving this error:
Uncaught exception 'Exception' with
message 'Could not parse for GALX
token'
I've checked all the basic things. The username and password on the account are correct. The only thing that I can see is that cURL is not writing cookie files.
I know the script has a Linux path for the cookiejar / cookiefile by default. I've tried changing this to a Windows directory, as well as including the full path. The code snippet I'm currently using is:
$this->_cookieFile = dirname(__FILE__) . "\cookies.txt";
Even with this code modification, the script is not writing to the cookies.txt file.
I've uploaded these scripts to a Linux host and they work just fine, proving to me that this is a Windows issue. Sadly, we don't have a Linux server for the production environment.
I'm looking for any guidance to get this working within Windows. Right now I'm developing on a Windows 7 machine running XAMPP. The production environment will likely be Windows 2008 Server.
Any assistance would be greatly appreciated!
I know this one is rather old...but it's still nice to share an answer, yeah?
Changing the path of the cookie file is good, but the problem here is with cURL trying (and failing) to verify google's SSL certificate. Two solutions can be found here (I found that link in the accepted answer for this other SO question)
For testing purposes I'd think it would be ok to use the quick and dirty solution (blindly accepting all SSL certificates without verifying).
You'd insert the following line into the GoogleVoice class constructor along with the other curl_setopt lines
curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
For production code, I'd verify the certificate. Finding and saving the certificate is covered in the first link I provided. Assuming the certificate is in the same directory as GoogleVoice.php, you'd insert the following lines
curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($this->_ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($this->_ch, CURLOPT_CAINFO, getcwd().'\BuiltinObjectToken-VerisignClass3PublicPrimaryCertificationAuthority.crt');
I'm no cURL expert, so I can't say if there's another way to verify the SSL certificate (or why it isn't needed on a Linux host.) This should be all that needs to be changed to get aaronpk's Google Voice API working on XAMPP
It seems that Google has just changed the output HTML for https://accounts.google.com/ServiceLogin in a way that breaks aaronpk's API. I observed the change sometime after December 8th, 2015.
The old HTML: <input name="GALX" type="hidden" value="SecureTokenHere">
The new HTML: <input type="hidden" name="GALX" value="SecureTokenHere">
So if you have the Could not parse for GALX token error, simply update your RegEx from:/name="GALX"\s*type="hidden"\s*value="([^"]+)"/ to /type="hidden"\s*name="GALX"\s*value="([^"]+)"/, or for compatibility, check for the new way if the old way doesn't find a match.

PHP5 giving failed to open stream: HTTP request failed error when using fopen

This problem seems to have been discussed in the past everywhere on google and here, but I have yet to find a solution.
A very simple fopen gives me a
PHP Warning: fopen(http://www.google.ca): failed to open stream: HTTP request failed!".
The URL I am fetching have no importance because even when I fetch http://www.google.com it doesnt work. The exact same script works on different server. The one failing is Ubuntu 10.04 and PHP 5.3.2. This is not a problem in my script, it's something different in my server or it might be a bug in PHP.
I have tried using a user_agent in php.ini but no success. My allow_url_fopen is set to On.
If you have any ideas, feel free!
It sounds like your configuration isn't allowed to use file functions, which is common these days because of security concerns. If you have the cURL libraries available to you, I would recommend trying those out.
PHP: cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.ca/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$file = curl_exec($ch);
curl_close($ch);
echo $file;
Check that your php.ini config is set to allow fopen to open external URL's:
allow_url_fopen "1"
http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
I'm not at all sure about whether this is the problem or not, but I know in the past I've had problems with opening URLs with fopen, often due to php.ini's allow_url_fopen or other unknown security settings
You may want to try cURL in PHP, which often works for me, you'll find an example really easily by googling that.
Check your phpinfo output - is http present under Registered PHP Streams?
Are you getting "HTTP request failed" without further details? The socket timeout could be expired. This default to 60 seconds. See: http://php.net/manual/en/function.socket-set-timeout.php

Janrain's PHP-OpenID and Google/Yahoo

I'm using Janrain's PHP-OpenID 2.1.3, and I've managed to get it working with all the providers I have tried except for Google and Yahoo. The major difference here seems to be that Google and Yahoo, unlike most other providers, don't use a user-specific URL, but rather have the user discovery framework all on their end - which throws the default Janrain framework for a loop then it tries to begin the auth request.
From what I've seen it looks like it's probably the YADIS discovery that is throwing the error, which should be able to be bypassed since the discovery is on Google or Yahoo's end, but I'm not sure. This is all a big informal learning experience for me, and I haven't had any luck finding documentation that can help me on this one. Any tips would be greatly appreciated.
Edit: the specific problem I am having is that when the begin() function is called for the Google or Yahoo URL, I get a null return. This function is found in Auth/OpenID/Consumer.php for reference.
Ok, I finally got to fix the library... I explained everything here (you can also download the php-openid library after my changes).
I needed to do what Paul Tarjan suggested but, also, I needed to modify the Auth_OpenID_detectMathLibrary and add the static keyword to a lot of functions. After that It seems to work perfectly although it is not an ideal solution... I think that someone should rewrite the whole library in PHP 5...
I had the same problem on Windows XP. Fixed by activating curl extension. To do this uncomment in php.ini the line
extension=php_curl.dll
by removing the ; in front of it if any. Restart apache.
Also on windows to work properly you need to define Auth_OpenID_RAND_SOURCE as null since in windows you don't have a random source. You can do this by adding the line
define('Auth_OpenID_RAND_SOURCE', null);
in CryptUtil.php before the first code line
if(!defined('Auth_OpenID_RAND_SOURCE')){
Even if the curl is not enabled the API should work by using instead the Auth_Yadis_PlainHTTPFetcher to communicat via HTTP. In the case of Google and Yahoo you need https, so it only works if open_ssl is enabled (Auth_Yadis_PlainHTTPFetcher::supportsSSL must return true).
I had exactly the same problem and it took me nearly 2 hours to track the problem. Jan Rain's OpenId lib requires 'DOM or domxml PHP XML' (https://github.com/openid/php-openid) but it will fail silently when neither is available!
On my CentOS installation simple:
yum install php-xml
fixed the problem (I'm using this repo: http://blog.famillecollet.com/pages/Config-en).
Are you using the example RP? Can I suggest you submit a detailed bug at http://trac.openidenabled.com/trac/newticket?project=php-openid or a detailed enquiry via the mailing list.
The immediate_mode support indeed does work the libraries if implemented correctly. I (and others) would also be happy to help you on the OpenID IRC channel irc.reenode.net in #openid. My nickname is flaccid.
It's because you don't have curl support enabled enabled in php. Without this, it can't get https content. At least, that's what I discovered. When I tried to get yahoo or google, it failed with an error message "Authentication error; not a valid OpenID," but when I enable php_curl, it works properly.
Make sure your server has curl with https protocol enabled. This solved it for me.
see this thread.
Here is a quick script to test it out. Upload on your server then acccess it via your browser.
<?php
error_reporting(E_ALL);
// create curl resource
$myurl = 'https://<YOURACCOUNT>.myopenid.com';
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL, $myurl);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
if (empty($buffer))
{
print "Sorry, cannot access $myurl .<p>". curl_error($curl_handle);
}
else
{
print $buffer;
}
curl_close($curl_handle);
?>
If it returns " Protocol https not supported or disabled in libcurl" then you know what to do.
I tried it using my gmail account and it works but it leads to a 301 permanent rediret, which makes sense.
Another potential difference is that Google and Yahoo use HTTPS and if your PHP or SSL installation is misconfigured (perhaps missing CA certs) then your OpenID code will fail to establish an association or complete the check_authentication call.
But without error messages or logs, I can't really tell what type of failure you're looking at.
A couple of years too late, but this might be relevant for users using Janrains PHP OpenID 2.2.2 library on a Windows platform. I'm still on PHP 5.2.17.
My simple test, just to make sure the library was contacting Google was to use the examples/discover.php program, and pass Googles OpenID URL (https://www.google.com/accounts/o8/id).
As per the instructions, the standard steps are to enable GMP (uncomment extension=php_gmp.dll) and CURL (uncomment extension=php_curl.dll). XML should already be enabled.
You may also need to extract the package in contrib/google and make sure google_discovery.php and ca-bundle.crt are in Auth/OpenID.
The extra paranoid could start with examples/detect.php, to make sure they have things set up correctly. It is expected you'd pass all the tests except the Cryptographic Randomness test. For this, you'll need to add
define('Auth_OpenID_RAND_SOURCE', null);
to the top of examples/detect.php. And while you're there, add that to examples/consumer/common.php (since examples/discover.php uses it).
Now, even after all this, discovery for the Google OpenID URL was failing. I was getting CURL error (60): SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in the php error log.
In the Windows environment, you need a definition for the CURLOPT_CAINFO. For my quick test, I added curl_setopt($c, CURLOPT_CAINFO, dirname(__FILE__)."/../OpenID/ca-bundle.crt"); before the curl_exec() statements in Auth/Yadis/ParanoidHTTPFetcher.php.
This allowed the examples/discover.php to discover the services offered by the Google URL.
As a longer term solution for setting CURLOPT_CAINFO in Windows, you might like to refer to this StackOverflow answer so you can add a setting to your php.ini.

Categories