- Saved searches
- Use saved searches to filter your results more quickly
- License
- InitPHP/Socket
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- SSL из PHP: socket и cURL
- How to Use SSL Sockets with PHP
- Generating an OpenSSL PEM
- SSL Client Socket
- SSL Server Socket
- HTTPS Client
- HTTPS Server
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
PHP Socket (TCP, TLS, UDP, SSL) Server/Client Library
License
InitPHP/Socket
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP Socket (TCP, TLS, UDP, SSL) Server/Client Library
composer require initphp/socket
Supported Types :
\InitPHP\Socket\Socket::class It allows you to easily create socket server or client.
public static function server(int $handler = Socket::TCP, string $host = '', int $port = 0, null|string|float $argument = null): \InitPHP\Socket\Interfaces\SocketServerInterface
- $handler : Socket::SSL , Socket::TCP , Socket::TLS or Socket::UDP
- $host : Identifies the socket host. If not defined or left blank, it will throw an error.
- $port : Identifies the socket port. If not defined or left blank, it will throw an error.
- $argument : This value is the value that will be sent as 3 parameters to the constructor method of the handler.
- SSL or TLS = (float) Defines the timeout period.
- UDP or TCP = (string) Defines the protocol family to be used by the socket. «v4», «v6» or «unix»
public static function client(int $handler = self::TCP, string $host = '', int $port = 0, null|string|float $argument = null): \InitPHP\Socket\Interfaces\SocketClientInterface
- $handler : Socket::SSL , Socket::TCP , Socket::TLS or Socket::UDP
- $host : Identifies the socket host. If not defined or left blank, it will throw an error.
- $port : Identifies the socket port. If not defined or left blank, it will throw an error.
- $argument : This value is the value that will be sent as 3 parameters to the constructor method of the handler.
- SSL or TLS = (float) Defines the timeout period.
- UDP or TCP = (string) Defines the protocol family to be used by the socket. «v4», «v6» or «unix»
connection() : Initiates the socket connection.
public function connection(): self;
disconnect() : Terminates the connection.
public function disconnect(): bool;
read() : Reads data from socket.
public function read(int $length = 1024): ?string;
write() : Writes data to the socket
public function write(string $string): ?int;
public function live(callable $callback): void;
public function wait(int $second): void;
Special methods for TLS and SSL.
TLS and SSL work similarly.
There are some additional methods you can use from TLS and SSL sockets.
timeout() : Defines the timeout period of the current.
public function timeout(int $second): self;
blocking() : Sets the blocking mode of the current.
public function blocking(bool $mode = true): self;
crypto() : Turns encryption on or off on a connected socket.
public function crypto(?string $method = null): self;
Possible values for $method are;
- «sslv2»
- «sslv3»
- «sslv23»
- «any»
- «tls»
- «tlsv1.0»
- «tlsv1.1»
- «tlsv1.2»
- NULL
option() : Defines connection options for SSL and TLS. see; https://www.php.net/manual/en/context.ssl.php
public function option(string $key, mixed $value): self;
require_once "../vendor/autoload.php"; use \InitPHP\Socket\Socket; use \InitPHP\Socket\Interfaces\SocketServerInterface; $server = Socket::server(Socket::TLS, '127.0.0.1', 8080); $server->connection(); $server->live(function (SocketServerInterface $socket) < switch ($socket->read()) < case 'exit' : $socket->write('Goodbye!'); return; case 'write' : $socket->write('Run write command.'); break; case 'read' : $socket->write('Run read command.'); break; default: return; > >);
require_once "../vendor/autoload.php"; use \InitPHP\Socket\Socket; $client = Socket::client(Socket::SSL, 'smtp.gmail.com', 465); $client->option('verify_peer', false) ->option('verify_peer_name', false); $client->connection(); $client->write('EHLO [127.0.0.1]'); echo $client->read();
In the above example, a simple smtp connection to gmail is made.
SSL из PHP: socket и cURL
Сегодня, этим сонным летним утром, я расскажу вам про SSL соединение из PHP скрипта. Расскажу исходя не только лишь из теории, а ещё и решая вполне себе практическую задачу — логин на гугловский блогосервис blogger.com.
Начнём с сокетов. В хелпе заявлена возможность использования HTTPS протокола, поэтому пробуем. Набор POST переменных взят из developer’s guide. Хабрапарсер обрамляет мыло ссылкой, поэтому «@» заменена на (at).
$postvars = array(
"Email" => "mail(at)gmail.com",
"Passwd" => "pass",
"service" => "blogger"
);
$postdata = "";
foreach ( $postvars as $key => $value )
$postdata .= "&".rawurlencode($key)." ssl://google.com", 443);
$send = "";
$send .= "POST /accounts/ClientLogin HTTP/1.1\r\n";
$send .= "Host: google.com\r\n";
$send .= "Content-length: ".strlen($postdata)."\r\n";
$send .= "Content-type: text/plain\r\n";
$send .= "Connection: close\r\n";
$send .= "\r\n";
$send .= $postdata."\r\n\r\n";
fputs($fp, $send);
$html = fread($fp, 1000000);
fclose($fp);
echo "".$html."В функции fsockopen в качестве префикса перед именем сервера используем не https, а ssl. Так прямым текстом написано в хелпе. Дальше всё просто. Формируем HTTP-header, и пихаем его в открытый сокет. Читаем ответ, и получаем
Короче, если опустить часовые мытарства и пляски вокруг функций сокета, у меня ничего не вышло. Ну то есть не вышло передать POST данные, хотя GET запросы возвращаются нормально. Может это связано только с гугловским сервером, а где-то в другом месте получится.
UPD. Огромное спасибо хабраюзеру anabolik, который подсказал что если изменить одну строку заголовка и сделать
$send .= «Content-type: application/x-www-form-urlencoded\r\n»;
то всё сразу заработает. Ещё раз спасибо. Отблагодарил всякими способами =).Переходим ко второму способу.
Открываем страницу мана про cURL и радуемся. Столько возможностей для запросов, для всякого конфигурирования. Должно получиться. Итак, лезем в curl_setopt. Нам понадобятся
CURLOPT_URL — это URL запроса.
CURLOPT_POST — говорим, что будем посылать POST запрос.
CURLOPT_POSTFIELDS — собственно POST переменыые.
CURLOPT_RETURNTRANSFER — вернуть результат запроса, а не выводить в браузер.Теперь собственно о SSL параметрах:
CURLOPT_SSL_VERIFYPEER — если поставить его в 0, то удалённый сервер не будет проверять наш сертификат. В противном случае необходимо этот самый сертификат послать.
CURLOPT_CAINFO — указывать файл сертификата, если CURLOPT_SSL_VERIFYPEER установлен в 1.
CURLOPT_SSLVERSION — целое число, указывает версию SSL (2 или 3), обычно определяется автоматически.
CURLOPT_SSL_VERIFYHOST — будет ли производиться проверка имени удалённого сервера, указанного в сертификате. Если установить значение «2», то будет произведена ещё и проверка соответствия имени хоста. (если честно, я так и не понял что делает этот флаг)Вот и всё. Нам для гугла понадобится только указать, что мы с собой никаких сертификатов не принесли, пустите нас так пожалуйста. Пишем код.
$postvars = array(
«Email» => «mail(at)gmail.com»,
«Passwd» => «pass»,
«service» => «blogger»
);$postdata = «»;
foreach ( $postvars as $key => $value )
$postdata .= «&».rawurlencode($key).» https://www.google.com/accounts/ClientLogin»);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close($ch);В переменной $result у нас теперь находятся три строки, из которых нужна только одна — последняя, которая начинается с «Auth=». Но про это, наверное, в следующий раз.
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 $socketHTTPS 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);
>
>