Call to undefined function cur_init() - php

I've seen plenty of these both here on stackoverflow and in other places - by try as I might i am still getting this error.
Any way - useful information
The Code I am trying to execute is as follows
<?php
function getOAuthToken ( $grantCode, $grant_type ) {
global $client_id;
global $client_secret;
global $refresh_token;
try {
ini_set('display_errors', '1');
error_reporting(E_ALL);
$oauth2token_uri = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
"client_id" => $client_id,
"client_secret" => $client_secret
);
if ($grant_type === "online") {
$clienttoken_post["code"] = $grantCode;
$clienttoken_post["redirect_uri"] = $refresh_token;
$clienttoken_post["grant_type"] = "authorization_code";
}
if ($grant_type == "offline") {
$clienttoken_post["refresh_token"] = $grantCode;
$clienttoken_post["grant_type"] = "refresh_token";
}
$curl = cur_init($oauth2token_uri);
}
catch ( Exception $e )
{
echo 'Message: ' .$e->getMessage();
}
};
session_start();
if (isset($_GET['code'])) {
try
{
$accessToken = getOAuthToken($_GET['code'],'online');
}
catch (Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
}
?>
Windows 7 (64bit) IIS Express
PHP.INI
executing phpInfo() gives the following information.
Php Version 5.3.24
Loaded Configuration File C:\Program Files (x86)\php\php.ini
cURL support enabled
cURL Information 7.29.0
Age 3
Features
AsynchDNS Yes
Debug No
GSS-Negotiate Yes
IDN No
IPv6 Yes
Largefile Yes
NTLM Yes
SPNEGO Yes
SSL Yes
SSPI Yes
krb4 No
libz Yes
CharConv No
Protocols dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, pop3, pop3s, rtsp, scp, sftp, smtp, smtps, telnet, tftp
Host i386-pc-win32
SSL Version OpenSSL/0.9.8y
ZLib Version 1.2.7
libSSH Version libssh2/1.4.2
Executing the following code;
<?php
$ci=#curl_version(); $cv=$ci["version_number"]; if($cv) echo "curl
installed"; else echo "curl is not installed";
?>
Shows curl installed
Libcurl.dll (v7.13) installed in Windows\System32 C:\Windows\SysWOW64
Extensions directory is given as C:\Program Files (x86)\php\v5.3\ext
this contains php_curl.dll (ver 5.3.24)
in the php.ini file the line
extension=php_curl.dll
has no semi-colon in front of it
The DLL ssleay32.dll (ver 0.9.8y) has been copied into c:\windows\System32 and C:\Windows\SysWOW64
the DLL libeay32.dll (ver 1.0.1e) has been copied into c:\windows\System32 and c:\windows\sysWOW64
Which I think covers all the answers I have been able to find but still have the ' Call to undefined function cur_init() ' error and have no idea what to try next.

should be
$curl = curl_init($oauth2token_uri);
and not
$curl = cur_init($oauth2token_uri);

Related

Unable to complete SSL/TLS handshake and set local cert chain file

I can create a ssl key and certificate with the following script:
<?php
$name='example_ss'; //Will add _key.pem, _crt.pem, _csr.pem
$data = [
"countryName" => "US",
"stateOrProvinceName" => "CA",
"localityName" => "San Francisco",
"organizationName" => "example.net",
"organizationalUnitName" => "example.net",
"commonName" => "example.net",
"emailAddress" => "exampleATgmailDOTcom"
];
$pem_passphrase = 'secret';
// Generate certificate
$key = openssl_pkey_new();
$csr = openssl_csr_new($data, $key);
$csr = openssl_csr_sign($csr, null, $key, 365);
// Generate PEM file
$pem = [];
openssl_x509_export($csr, $pem[0]);
file_put_contents($name.'_crt.pem', $pem[0]);
//openssl_pkey_export($key, $pem[1], $pem_passphrase); //Remove $pem_passphrase for none
openssl_pkey_export($key, $pem[1]); //Remove $pem_passphrase for none
$pem = implode($pem);
file_put_contents($name.'_key.pem', $pem);
Move them as required:
sudo mv example_ss_crt.pem /etc/pki/tls/certs/example_ss_crt.pem
sudo mv example_ss_key.pem /etc/pki/tls/private/example_ss_key.pem
And everything works find.
But when I create them manually: (w/ and w/o using -sha256)
openssl req -x509 -newkey rsa:4096 -keyout example_ss_key.pem -out example_ss_crt.pem -days 365 -nodes
And move them as I did for the previous, I get the following error:
Unable to complete SSL/TLS handshake: stream_socket_enable_crypto():
Unable to set local cert chain file `/etc/pki/tls/private/example_ss_key.pem';
Check that your cafile/capath settings include details of your certificate and its issuer
What is the difference between these two sets of keys and how do I create them manually? I don't think it is relevant, but they are being used for a tcp sockets connection between Centos7 and a Raspberry Pi.
EDIT. The server is created with the following script. I am not using a passphrase.
$loop = \React\EventLoop\Factory::create();
$server = new \React\Socket\TcpServer($this->host['url'].':'.$this->host['port'], $loop);
if($this->host['tls']) {
$server = $this->host['privateKey']
?new \React\Socket\SecureServer($server, $loop, ['local_cert' => $this->host['privateKey'],'passphrase' => $this->host['passphrase'] ])
:new \React\Socket\SecureServer($server, $loop, ['local_cert' => $this->host['privateKey'] ]);
}
Dummy mistake. http://php.net/manual/en/context.ssl.php
local_cert string Path to local certificate file on filesystem. It
must be a PEM encoded file which contains your certificate and private
key. It can optionally contain the certificate chain of issuers. The
private key also may be contained in a separate file specified by
local_pk
.

encrypt file in php with Mcrypt

I use this code for encrypt file in php:
<?php
// The password
$passphrase = 'My secret';
// Turn a human readable passphrase
// into a reproducible iv/key pair
$iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
$key = substr(md5("\x2D\xFC\xD8".$passphrase, true) .
md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
$opts = array('iv' => $iv, 'key' => $key, 'mode' => 'stream');
// Open the file
$fp = fopen('panel.css', 'wb');
// Add the Mcrypt stream filter
// We use Triple DES here, but you
// can use other encryption algorithm here
stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
// Wrote some contents to the file
fwrite($fp, 'Secret secret secret data');
// Close the file
fclose($fp);
but when run above code this error happen:
stream_filter_append(): Could not open encryption module
I check for mcrypt extension with this code:
if (extension_loaded('mcrypt') === true)
{
echo "Mcrypt exist !";
}
and Mcrypt exist ! displayed.also I check php.ini for Mcrypt and this line is about Mcrypt:
[mcrypt]
; For more information about mcrypt settings see http://php.net/mcrypt-module-open
; Directory where to load mcrypt algorithms
; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt)
;mcrypt.algorithms_dir=
; Directory where to load mcrypt modes
; Default: Compiled in into libmcrypt (usually /usr/local/lib/libmcrypt)
;mcrypt.modes_dir=
any one can help me ?

APNS certificate .pem

I am trying to create the server side connection for apple push notifications.
First, I ask from the user (who probably will be an ios dev) to give the .cer and .p12 files that Apple provides in order to make it a .pem file.
Below is the .pem certificate creation.
$dir = $this->directory.'/certificates';
$password = 'a_user_password';
$certificate = $dir.'/certificate.cer';
$key_password = $dir.'/key.p12';
exec('openssl x509 -inform der -in '.$certificate.' -out '.$dir.'/certificate.pem');
exec('openssl pkcs12 -nocerts -out '.$dir.'/key.pem -in '.$key_password.' -passout pass:'.$password.' -passin pass:'.$password);
$filename = $key_password;
$results = array();
$worked = openssl_pkcs12_read(file_get_contents($filename), $results, $obj->password);
if($worked) {
$current = file_get_contents($dir.'/key.pem');
$current .= $results['pkey'];
file_put_contents($dir.'/key.pem', $current);
} else {
echo openssl_error_string();
}
exec('cat '.$dir.'/certificate.pem '.$dir.'/key.pem > '.$dir.'/apns_certificate.pem');
So far, so good. I have tested that the above generated apns_certificate.pem is successful with apple through command line via:
s_client -connect gateway.sandbox.push.apple.com:2195 -cert certificate.pem -key key.pem
However,
When I try to connect with apns through PHP I cannot. Follows the last php code that I have tried and I have seen that for others has worked:
$this->certificate = ROOT.'/certificates/apns_certificate.pem';
$this->socket = 'ssl://gateway.push.apple.com:2195';
if (!file_exists($this->certificate)) {
$this->error = 'Certificate file not found';
return false;
}
$this->stream_context = stream_context_create();
$this->stream_options = array(
'ssl' => array(
'local_cert' => $this->certificate,
'passphrase' => 'a_user_password', //same with the one used in my previous code
)
);
$success = stream_context_set_option($this->stream_context, $this->stream_options);
if ($success == false) {
$this->error = 'Secure connection failed';
return false;
}
$this->socket_client = stream_socket_client($this->socket, $con_error, $con_error_string, $this->timeout, STREAM_CLIENT_CONNECT, $this->stream_context);
if ($this->socket_client === false) {
$this->error = $con_error_string;
return false;
} else {
return true;
}
The above code returns me an error:
Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown
Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195
Thank you in advance for your help!
The above code is correct. There was an error with the certification .p12 . Also I changed the exec for .p12 convertion file to:
exec('openssl pkcs12 -out '.$dir.'/key.pem -in '.$key_password.' -passout pass:'.$password.' -passin pass:'.$password.' -nodes');

push notification in ios

I am new in a php and write a code for push notification in codeigniter but I got these erros.
Here is my model..
function sendmessage($appid, $deviceid, $status, $message)
{
$deviceToken = '0f744707bebcf74f9b7c25d48e3358945f6aa01da5ddb387462c7eaf61bbad78';
$message = 'My first push notification!';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
//stream_context_set_option($ctx, 'ssl', 'passphrase', 'essar#123');
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp){
exit("Failed to connect: $err $errstr" . PHP_EOL);
}
else {
print "Connection OK/n";
}
echo 'Connected to APNS' . PHP_EOL;
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
fclose($fp);
$data = array(
'message' => $this->message . 'add',
'appid' => $this->appid,
'deviceid' => $this->deviceid,
'status' => $status
);
$this->sendmessage($data);
Error message:
Message: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure Message: stream_socket_client(): Failed to enable crypto Message: stream_socket_client(): unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error)
Once you created the provisional certificates and push notification for both development and distribution. Follow the steps for Generate Push Notification
In order to use the certificates you generated, you need to create a PEM file that stores both, your Apple Push Notification Service SSL Certificate and your Private Key. You can create the PEM file from a terminal.
Navigate to the directory that contains the certificates and key you generated earlier and execute the following steps. The file names here reflect the names of the certificates that were generated as part of this lesson. You have to update the syntax according the names you gave your certificates.
First create the application certificate PEM file. You can do this by double clicking on the aps_developer_identity.cer certificate file, then opening the Keychain Assistant and exporting the certificate as ap12 file and then converting it to a PEM file, in the same fashion as the PushNotificationApp.p12 is converted to a PEM file. Alternatively you can use a single command line that converts the aps_developer_identity.cer certificate file directly to a PEM file. Here we are opting for the single command line option, as follows:
openssl x509 -inform der -outform pem -in aps_developer_identity.cer -out PushNotificationAppCertificate.pem
Now create the application key PEM file as follows. You need to enter the import password and PEM pass phrase:
openssl pkcs12 -in PushNotificationApp.p12 -out PushNotificationAppKey.pem -nocerts
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
Now concatenate the two files:
cat PushNotificationAppCertificate.pem PushNotificationAppKey.pem > PushNotificationAppCertificateKey.pem
Open a Mac terminal and execute the following line from the directory that contains the certificates you generated:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushNotificationAppCertificate.pem -key PushNotificationAppKey.pem
You are then asked to enter the pass phrase for the key you submitted:
Enter pass phrase for PushNotificationAppKey.pem:
If everything worked, then the server should send you a lot of information that may look something like the following:
CONNECTED(00000003)
depth=1 /C=US/O=Entrust, Inc./OU=www.entrust.net/rpa is incorporated by reference/OU=(c) 2009 Entrust, Inc./CN=Entrust Certification Authority - L1C
verify error:num=20:unable to get local issuer certificate verify return:0
...
Key-Arg : None
Start Time: 1326899631 Timeout : 300 (sec) Verify return code: 0 (ok)
At the end of this, you can enter some text and then select the return key. We entered the text "**Hello World**".
**Hello World
closed**
This completes the communication with the server and verifies that our certificates work.
I have been having the same issue as you mentioned here. This took some time and head scratching to find...
The solution that I found that corrected the handshake error was to download the entrust certificate, and include this in the stream context using the code below:
$entrustCert = '<full path to cert>/entrust_2048_ca.cer';
stream_context_set_option($ctx, 'ssl', 'cafile', entrustCert);
There does seem to intermittent connection issues with the sandbox APN service. I occasionally get errors returned like:
Warning: stream_socket_client(): SSL: Connection reset by peer
Warning: stream_socket_client(): Failed to enable crypto
I hope this is a time saver for someone!
function send_iOS_notifications($device_tokens, $notification_content)
{
$this->load->library('apn');
$this->apn->payloadMethod = 'enhance'; // you can turn on this method for debuggin purpose
$this->apn->connectToPush();
//$badge_count = $this->set_and_get_ios_active_notifications('',$device_token);
// adding custom variables to the notification
$this->apn->setData($notification_content);
$message = $notification_content['message'];
if ((strpos($message, 'http://') !== false) || (strpos($message, 'https://') !== false)) {
$message = "Image";
}
//$send_result = $this->apn->sendMessage($device_token, 'Test notif #1 (TIME:'.date('H:i:s').')', /*badge*/ 2, /*sound*/ 'default' );
$send_result = $this->apn->sendMessage($device_tokens, $message, /*badge*/ '', /*sound*/ 'default' );
if($send_result){
log_message('debug','Sending successful');
$result['status'] = true;
$result['message'] = 'Sending successful';
}
else{
log_message('error',$this->apn->error);
$result['status'] = true;
$result['message'] = $this->apn->error;
}
$this->apn->disconnectPush();
}

PHP SOAP SSL problems

I'm trying to connect to a secure SOAP server using NuSOAP. (I gave the built-in SOAP library a chance, but that was behaving strangely, so I switched to NuSOAP.)
Here's my code:
require('application/libraries/nusoap/nusoap.php');
$soap = new nusoap_client('https://ws.firstdataglobalgateway.com/fdggwsapi/services/order.wsdl', 'wsdl');
$soap->setCredentials('WS'.STORE_NUMBER.'._.1',
PASSWORD,
'certificate',
array(
'sslcertfile' => 'first_data/cert.pem',
'sslkeyfile' => 'first_data/key.pem',
'passphrase' => KEY_PASSPHRASE
)
);
if($err = $soap->getError()) {
die('Error: '.$err);
}
$result = $soap->call('fdggwsapi:FDGGWSApiOrderRequest', array('v1:Transaction' => '1'));
if($soap->fault) {
echo 'Fault! <pre>';
var_dump($result);
echo '</pre>';
} else {
if($err = $soap->getError()) {
die('Error: '.$err);
} else {
echo '<pre>';
var_dump($result);
die('</pre>');
}
}
I get the following error:
Error: wsdl error: Getting https://ws.firstdataglobalgateway.com/fdggwsapi/services/order.wsdl - HTTP ERROR: cURL ERROR: 56: SSL read: error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert decrypt error, errno 0
url: https://ws.firstdataglobalgateway.com:443/fdggwsapi/services/order.wsdl
content_type:
http_code: 0
header_size: 0
request_size: 163
filetime: -1
ssl_verify_result: 0
redirect_count: 0
total_time: 0.531131
namelookup_time: 0.00121
connect_time: 0.070608
pretransfer_time: 0.305044
size_upload: 0
size_download: 0
speed_download: 0
speed_upload: 0
download_content_length: -1
upload_content_length: 0
starttransfer_time: 0
redirect_time: 0
What could be the possible problems? How could I debug this? I'm rather out of my league here.
Based on the error:
SSL read: error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert
decrypt error, errno 0
It looks to me like the PHP library is having trouble reading your cert.pem and key.pem files. These files can come in different formats. Apache requires that these be in PKCS12 format and I would guess PHP is the same. You can use a tool called "Keystore Explorer 4.0.1" to verify and convert if necessary.
You can verify the validity of the format of the keys also, using openssl and this command:
C:\Temp> openssl pkcs12 -info -in ksb_cert.p12
With this settings my client working finally
$client = new nusoap_client($wsdlurl,'wdsl');
$client->setUseCURL(true);
$client->useHTTPPersistentConnection();
$client->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);
$client->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
$client->setCurlOption(CURLOPT_RETURNTRANSFER, 1);
$client->setCurlOption(CURLOPT_SSLVERSION,3);

Categories