- How to Use SSL Sockets with PHP
- Generating an OpenSSL PEM
- SSL Client Socket
- SSL Server Socket
- HTTPS Client
- HTTPS Server
- Как настроить HTTPS-соединение?
- Комментарии ( 11 ):
- PHP CURL Requests With HTTPS (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- HTTPS CURL
- WHAT & WHY HTTPS
- EXAMPLE 1) CURL REQUEST TO HTTPS
- EXAMPLE 2) CURL IGNORE SSL
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
How to Use SSL Sockets with PHP
SSL sockets are perfect for sending secure data. With certificates, you can verify the identify of the host, the client, or both. Signed certificates cost money but you can create and self-sign a certificate. Check out the code samples below to see how to generate SSL certificates and create SSL clients and servers. Examples include raw socket communication as well as the common HTTPS protocol.
Generating an OpenSSL PEM
$certificateData = array(
"countryName" => "US",
"stateOrProvinceName" => "Texas",
"localityName" => "Houston",
"organizationName" => "DevDungeon.com",
"organizationalUnitName" => "Development",
"commonName" => "DevDungeon",
"emailAddress" => "nanodano@devdungeon.com"
);
// Generate certificate
$privateKey = openssl_pkey_new();
$certificate = openssl_csr_new($certificateData, $privateKey);
$certificate = openssl_csr_sign($certificate, null, $privateKey, 365);
// Generate PEM file
$pem_passphrase = 'abracadabra'; // empty for no passphrase
$pem = array();
openssl_x509_export($certificate, $pem[0]);
openssl_pkey_export($privateKey, $pem[1], $pem_passphrase);
$pem = implode($pem);
// Save PEM file
$pemfile = './server.pem';
file_put_contents($pemfile, $pem);
SSL Client Socket
$socket = stream_socket_client("ssl://192.168.1.2:5522", $errno, $errstr);
if ($socket) echo fread($socket, 2000);
>
$host = '192.168.1.2';
$port = 5522;
$timeout = 30;
$cert = 'e:\www\workspace\php\sockets\server.pem'; // Path to certificate
$context = stream_context_create(
array('ssl'=>array('local_cert'=> $cert))
);
if ($socket = stream_socket_client(
'ssl://'.$host.':'.$port,
$errno,
$errstr,
30,
STREAM_CLIENT_CONNECT,
$context)
) fwrite($socket, "\n");
echo fread($socket,8192);
fclose($socket);
> else echo "ERROR: $errno - $errstr\n";
>
SSL Server Socket
$context = stream_context_create();
// local_cert must be in PEM format
stream_context_set_option($context, 'ssl', 'local_cert', $pemfile);
// Pass Phrase (password) of private key
stream_context_set_option($context, 'ssl', 'passphrase', $pem_passphrase);
stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer', false);
// Create the server socket
$socket = stream_socket_server(
'ssl://0.0.0.0:9001',
$errno,
$errstr,
STREAM_SERVER_BIND|STREAM_SERVER_LISTEN,
$context
);
// fwrite/fread to $socket
HTTPS Client
// Get port and IP address
$service_port = getservbyname('www', 'tcp');
$address = gethostbyname('www.google.com');
// Bind socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
>
// Connect
$result = socket_connect($socket, $address, $service_port);
if ($result === false) echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
>
// Create HTTP request
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.google.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
// Send HTTP request
socket_write($socket, $in, strlen($in));
// Read and output response
while ($out = socket_read($socket, 2048)) echo $out;
>
// Close socket
socket_close($socket);
HTTPS Server
This is just a slight extension of the SSL Server code above to accept and respond as an HTTP server
$context = stream_context_create();
// local_cert must be in PEM format
stream_context_set_option($context, 'ssl', 'local_cert', '/path/to/pem/file');
stream_context_set_option($context, 'ssl', 'passphrase', $pem_passphrase);
stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer', false);
// Create the server socket
$server = stream_socket_server('ssl://192.168.1.96:9001', $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context);
while(true)
$buffer = '';
$client = stream_socket_accept($server);
if($client) // Read until double CRLF
while( !preg_match('/\r?\n\r?\n/', $buffer) )
$buffer .= fread($client, 2046);
// Respond to client
fwrite($client, "200 OK HTTP/1.1\r\n"
. "Connection: close\r\n"
. "Content-Type: text/html\r\n"
. "\r\n"
. "Hello World! " . microtime(true)
. "\n ");
fclose($client);
>
>
Как настроить HTTPS-соединение?
Меня уже давно просили немного осветить тему настройки HTTPS-соединения на сайте. Для тех, кто не знает, зачем нужен HTTPS, объясняю: когда Вы передаёте свои данные (например, логин и пароль) серверу, то они идут в открытом виде. Если их злоумышленник перехватит, то, соответственно, он их узнает. На обычных сайтах это не так страшно, но вот если это будет какая-нибудь платёжная система, тогда, получив доступ к данным, злоумышленник просто опустошит Ваши кошельки. А с использованием HTTPS данные отправляются в зашифрованном виде, и только лишь у сервера-приёмника есть ключ, позволяющий их расшифровать. То есть злоумышленник, перехватив данные, не получит ровным счётом ничего.
Сразу говорю, что сам сайт никак не меняется. По сути для создания HTTPS-соединения надо лишь настроить сервер.
- Настроить SSL. Сам процесс зависит от сервера, но, как правило, по умолчанию он уже настроен. В пакете Denwer он уже также подготовлен для работы.
- Купить и установить сертификат на сервер. Цены начинаются примерно от 2500 рублей в год. Можно, конечно, и не покупать, но тогда пользователей будут постоянно предупреждать, что используется недоверенный сертификат. Сам сертификат состоит из двух частей: открытый и закрытый ключ (public и private). Первый используется для шифрования данных от клиента к серверу, а второй для расшифровки этих данных уже на сервере. Установка сертификата также зависит от сервера, плюс от операционной системы.
- Настроить виртуальный хост. Примерный код я покажу ниже, но опять же это всё зависит от сервера и от операционной системы.
Ниже привожу код, который необходимо прописать в файле httpd.conf (файл настройки сервера Apache):
#Включить SSL
SSLEngine on
# Путь к сертификату
SSLCertificateFile /usr/local/etc/apache/ssl.crt/certificate.crt
# Путь к закрытому ключу
SSLCertificateKeyFile /usr/local/etc/apache/ssl.key/privatekey.key
# Убираем ошибку у Internet Explorer "Bad data from the server"
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
# Путь к log-файлу
ErrorLog /usr/local/apache/logs/ssl_engine_log
# Формат содержимого log-файла
CustomLog /usr/local/apache/var/log/ssl_request_log \ "%t %h %x %x \"%r\" %b"
После этого можно будет обращаться к https://mysite.ru, тем самым, делая безопасное соединение с сайтом.
В данной статье я показал ход действий для настройки HTTPS-соединения на сайте. Ещё раз повторяю, каждый из этапов зависит от сервера и от операционной системы, поэтому всё-таки придётся воспользоваться поиском для одного из частных случаев, который возник конкретно у Вас.
Создано 10.12.2012 06:20:44
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 11 ):
А все браузеры поддерживаю 256 битное шифрование?
Не все, а поддержка 256 битного шифрования зависит ещё и от сервера, а также от ОС.
Если сервер apache. OC - Windows 7? А браузер MSIE7?
IE7 не поддерживает, только с IE8 появилась такая поддержка.
у вас такой вопрос!! от php nado otpravit sms na tel a kak eto budet kogda nebud vi rabotali ob etom-smpp. spasibo
SMS надо отправлять через сторонние сервисы, причём каждое сообщение будет стоить Вам денег. Как настроить это на сайте, Вам объяснят в самом сервисе, дав инструкцию и код.
nam est elektroniy dnevnik v tadjikistan i nado sms dnevnik no tam nado vash savet kak im eto realizovaat
Здравствуйте Михаил! Поздравляю Вас с Новым Годом (дважды,так как в прошлом письме не поздравила)! В статье "Как настроить HTTPS-соединение?" Вы рассказываете про настройку применительно к серверу Apache. А не могли бы Вы рассказать о настройках в случае применения сервера IIS 7.5? С уважением, Маша.
Таке саме питання, але для Nginx.
PHP CURL Requests With HTTPS (Simple Examples)
Welcome to a tutorial on how to make CURL requests to HTTPS in PHP. Need to access a secure URL with PHP CURL? Well, we need to specify a couple of extra settings in CURL to do that.
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, "https://site.com");
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- $result = curl_exec($ch);
- curl_close($ch);
That covers the quick basics, but read on for more examples and details!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
HTTPS CURL
All right, let us now get into the examples and more details on doing a CURL call to an HTTPS URL.
WHAT & WHY HTTPS
- HTTPS stands for “HTTP Secure”.
- When we access a website via http:// , the data exchange is in cleartext. This is vulnerable to “man in the middle” (MITM) attacks, anyone can hijack and read the data.
- With https:// , the data exchange is encrypted. People can still hijack the data, but cannot read the data easily.
That covers the basics, but things are not that simple. Any website can use HTTPS technology, but that does not mean they are safe. For example, a fake phishing website can also use HTTPS, but that does not mean it is a legit and safe website.
So apart from encryption, the other part of HTTPS is verification. Not going into the confusing mechanics, but there are third parties known as “certificate authority” (CA). They do the verifications and issue digital certificates; In a single HTTPS session, we are actually encrypting data and checking with various CA for authentication.
EXAMPLE 1) CURL REQUEST TO HTTPS
// (A) CURL INIT $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://code-boxx.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // RETURN SERVER RESPONSE curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // VERIFY SSL CERTIFICATE curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // VERIFY HOST NAME // (B) CURL FETCH $result = curl_exec($ch); if (curl_errno($ch)) < echo curl_error($ch); >else < echo $result; >curl_close($ch);
All right, this is pretty much the same as the introduction snippet. But as you already know, HTTPS does 2 things – Encryption and verification. Thus, the 2 CURL settings CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST .
P.S. Ever since PHP 7.1 (if I remember correctly), these verification settings are set to “true” by default. Yes, even if you omit these 2 settings, CURL will still automatically do the SSL verification.
EXAMPLE 2) CURL IGNORE SSL
Simply disable the verification if you have to work with an unverified host (or expired certificate) for some reason… But don’t do this unless it is for the sole purpose of testing. The verification is there to prevent MITM attacks.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a "paid scripts and courses" business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript - Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.