English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Основной курс

PHP Уровеньный курс

PHP & MySQL

PHP Референс Мануал

Примеры использования и применения функции fsockopen() в PHP

PHP HTTP  reference manual

Функция fsockopen() открывает сетевое подключение или подключение к Unix-сокету.

Синтаксис

resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]])

Определение и использование

Используется для открытия подключения к сокету в Интернете или Unix-домену.

Инициализация подключения сокета к указанному хосту (hostname).
PHP поддерживает следующий список типов транспортов сокетов: список поддерживаемых транспортов сокетов (Socket Transports). Также можно получить支持的 типы транспортов сокетов с помощью функции stream_get_transports().
By default, the socket connection will be opened in blocking mode. Of course, you can change it to non-blocking mode by using stream_set_blocking().
stream_socket_client() is very similar and provides more comprehensive parameter settings, including non-blocking mode and context-based settings.

Return value

 fsockopen() will return a file handle, which can then be called by other file class functions (for example: fgets(), fgetss(), fwrite(), fclose(), and feof()). If the call fails, FALSE will be returned.

Note: If the hostname is inaccessible, a warning level (E_WARNING) error message will be thrown.

Parameter

Serial numberParameters and descriptions
1

hostname

If OpenSSL is installed, you may need to add the access protocol ssl:// or tls:// before your hostname address, so that you can connect to the remote host using SSL or TLS clients based on the TCP/IP protocol.

2

port

Port number. If a -1 is passed as a parameter, it means that the port is not used, for example, unix://.

3

errno

Save the system-level error number that occurred during the system-level connect() call.

4

errstr

Error messages will be returned as a string.

5

timeout

 Set the timeout for the connection, in seconds. 

Online example

Try the following example

<?php
   $connection = fsockopen("ru.oldtoolbag.com", 80, $errno, $errstr, 30);
   
   if (!$connection) {
      echo "$errstr ($errno)
      \n";
   }else {
      $out = "GET / HTTP/1.1\r\n";
      $out .= "Host: ru.oldtoolbag.com\r\n";
      $out .= "Connection: Close\r\n\r\n";
      
      fwrite($connection, $out);
      
      while (!feof($connection)) {
         echo fgets($connection, 128);
      }
      fclose($connection);
   }
?>

Open the connection in the example above

PHP HTTP  reference manual