php warning fsockopen unable to connect to
fsockopen
(PHP 4, PHP 5, PHP 7, PHP 8)
fsockopen — Открывает соединение с интернет-сокетом или доменным сокетом Unix
Описание
stream_socket_client() выполняет аналогичную функцию, но предоставляет более широкий выбор настроек соединения, включающий установку неблокирующего режима и возможность предоставления потокового контекста.
Список параметров
Если этот параметр предоставить, то в случае возникновения ошибки системного вызова функции connect() он будет принимать номер этой ошибки.
Сообщение об ошибке в виде строки.
Тайм-аут соединения в секундах.
Возвращаемые значения
Ошибки
Список изменений
Примеры
Пример #1 Пример использования fsockopen()
Пример #2 Использование UDP-соединения
Пример ниже демонстрирует, как получить день и время от UDP-службы «daytime» (порт 13) на вашей машине.
Примечания
В зависимости от окружения, Unix-домен или тайм-аут установки подключения могут оказаться недоступными.
Иногда UDP-сокеты получают статус открытых, даже если удалённый хост недоступен. Ошибка проявит себя только во время чтения или записи данных в/из этого сокета. Причина этого заключается в том, что протокол UDP передаёт данные без установки соединения, а это означает, что операционная система не устанавливает и не держит соединение с сокетом, пока не начнётся передача данных.
Смотрите также
User Contributed Notes 41 notes
// This script is an example of posting multiple files using
// fsockopen.
// The tricky part is making sure the HTTP headers and file boundaries are acceptable to the target webserver.
// This script is for example purposes only and could/should be improved upon.
$host = ‘targethost’ ;
$port = 80 ;
$path = ‘/test/socket/file_upload/receive_files.php’ ;
// the file you want to upload
$file_array [ 0 ] = «dingoboy.gif» ; // the file
$file_array [ 1 ] = «dingoboy2.gif» ; // the file
$file_array [ 2 ] = «dingoboy3.gif» ; // the file
$content_type = «image/gif» ; // the file mime type
//$content_type = «text/plain»;
//echo «file_array[0]:$file_array[0]
/************************************************************
* Author: Richard Lajaunie
* Mail : richard.lajaunie@cote-azur.cci.fr
*
* subject : this script retreive all mac-addresses on all ports
* of a Cisco 3548 Switch by a telnet connection
*
* base on the script by: xbensemhoun at t-systems dot fr
**************************************************************/
$cfgPort = 23 ; //port, 22 if SSH
$cfgTimeOut = 10 ;
This script checks specific ports so you need to have the correct port open on the server for this to work.
I have found, when using fsockopen() and the POST method, that using HTTP/1.1 is VERY significantly slower than HTTP/1.0 (at least for the server I’m querying, an Orion-based server). Also, using cURL tended to be faster than fsockopen(), though only slightly. For example, here was a recent set of data (for the same exact request in each case):
cURL: 4.2sec
fsockopen() HTTP/1.0: 4.9sec
fsockopen() HTTP/1.1: 19.9sec (!)
I’m not sure why this was occurring. Perhaps it has something to do with the Orion server, which I have little experience with. However, it was not a fluke, and I double-checked the code to make sure there were no errors.
EDITORS NOTE: HTTP/1.1 uses persistent connection causing this delay. Use «Connection: close» header to disable it.
Here’s a function to just fetch the contents behind an URL.
The following snippet allows you to retrieve the title of a page.
Great for rewriting auto-url detectors to display the actual title rather then http://.
I was tearing my hair out for a week trying to figure out how to do this.
If you use fsockopen with a service that doesn’t have an EOF, or you try to read beyond EOF or line break, PHP can hang completely.
In my case, I was trying to write a class that talks to Kali servers (www.kali.net) to get a list of people on the chat server. To keep PHP from hanging due to the above, I discovered this:
I’ve only used this on PHP 4.2.1 so far.
To check if a Url is Online (with http and https)
Using @fgets to hide Warning when using SSL
(Bug: «Warning: function.fgets SSL: fatal protocol error», http://bugs.php.net/bug.php?id=23220)
[EDIT BY danbrown AT php DOT net: Based on code provided in a note by (rafaelbc AT matrix DOT com DOT br) on 23-MAY-09, which has since been removed.]
My recursive unchunk function:
The following function performs pop3 authentication. Returns NULL on error, or true/false to indicate username/password matching:
Lots of tries and lots of reading http-headers.
A simple proxy list checker. You can check a list ip:port if that port is opened on that IP.
Here’s a quick function to establish a connection to a web server that will time out if the connection is lost after a user definable amount of time or if the server can’t be reached.
Also supports Basic authentication if a username/password is specified. Any improvements or criticisms, please email me! 🙂
This is a very fast program for test a form or link (many times).
= 100 ; // How many times repeat the test
$timeout = 100 ; // Max time for stablish the conection
$size = 16 ; // Bytes will be read (and display). 0 for read all
$server = ‘127.0.0.1’ ; // IP address
$host = ‘www.example.net’ ; // Domain name
$target = ‘/poll/answer.asp’ ; // Specific program
$referer = ‘http://www.example.com/’ ; // Referer
$port = 80 ;
thought you guys may appreciate this function, allows you to pass an array of urls to download and does so simultaneously using non-blocking sockets, then returns the data in an array.
// function connects to an array of URLS at the same time
// and returns an array of results.
If you are using fsockopen to access webpage, but come across a redirect (Location: ) in the header and want to find and follow the redirect as in this snippet:
The documentation example is of a GET request. I have found POST documentation to be lacking, and here’s a function to easily simulate submitting form data:
Here is my fsockopen-based HTTP request fonction (GET and POST) :
Improved HTTP/1.1 chunked transfer-encoding example.
The sample code given below by Jack does not function correctly when run against a recent version of Apache (I’m assuming that this did once work, but from the HTTP/1.1 spec I can only assume if it did work it was based mostly on luck).
It appears that in PHP 5.6.0 (at least the version in Debian jessie, with openssl 1.0.1h-3), this function *is* now validating SSL certificates (in a variety of ways). First, it appears to fail for untrusted certificates (i.e. no matching CA trusted locally), and secondly, it appears to fail for mismatched hostnames in the request and certificate.
Here’s how to send an email using SMTP. This includes rudimentary checking on server responses during the process of sending an email. Could be improved by more comprehensive processing of the result codes. or going on to the next mail exchanger when you fail after connecting to the first.
Trying to fsockopen an ssl:// connection, but it was hanging for a long time, ignoring timeout parameter, and eventually returning false, without an error message.
Turns out (at least) on Windows it validates certificates and doesn’t have a valid certificate store.
This worked for me:
— download Mozilla’s certificate store from https://curl.haxx.se/ca/cacert.pem
— copy it inside php installation (for example: c:\php)
— and set it up in php.ini
My system: Apache/2.4.29 (Win64) OpenSSL/1.0.2n PHP/5.6.38
on my FreeBSD vm, with Joomla, I was getting the error
fsockopen(): unable to connect to ssl://localhost:443 (Unknown error)
when using a contact form and also the module updating process.
After reading other notes on here, regarding certificate validation, I installed the port ca_root_nss
(Root certificates from certificate authorities included in the Mozilla
NSS library and thus in Firefox and Thunderbird.)
/*
this script i used for remote my PvPGN Server, to check email user.
not good, but it work.
*/
When downloading large files, it is not really efficient to put the whole server answer in memory before parsing the data to remove the header parts. Here is a simple way to do it while writing the data as it arrive:
This was a great help to me, given Twitter’s recent API changes to require TLS 1.2+.
//
// Example usage.
//
$server = ‘127.0.0.1’ ;
$port = ’80’ ;
$uri = ‘/cgi-bin/random-cgi’ ;
$content = ‘Your post content. ‘ ;
If you have to use a proxy to make requests outside of your local network, you may use this class:
/*
*
* No Proxy Authentification Implemented; PHP 5
*
*/
private function get_url_via_proxy () <
public function request_via_proxy () <
public function request_without_proxy () <
I was having trouble doing an https in fopen and with fsockopen where the address had ssl://. I was getting error code 114 in the log. After much research i found that there was some ssl conflict trouble with MySQL 5.0.20-5.0.33. It had some functions that were interfering with openssl that showed up in the php install.
Here is a function for testing a website/URI for availability:
Try this.
Use AUTH when necessary.
Read RFC 821 when having problems.
To make a telnet connection with a Cisco router:
= «nnn.nnn.nnn.nnn» ; //IP of your router
$cfgPort = 23 ; //port, 22 if SSH
$cfgTimeOut = 10 ;
Here is how to connect to the web from behind a proxy server:
Here is some code to help out abit more with the EOF problem.
I had a problem where I needed to strip out so many lines of server input to get back right data i wanted.
#takes in account servers that do not return EOF character
#send data to server and get back input
#function globals
$linenumber = «2» ; #amount of lines to get rid of before we give input
$lineamount = «1» ; #amount of lines to read after we give input
Did you know that fsockopen() DOES NOT validate SSL certificates whatsoever? For the sake of World’s overall security level, I guess it would be a very positive idea to add a BIG WARNING notice on the manual page!
Citing the extensive study titled «The Most Dangerous Code in the World: Validating SSL Certificates in Non-Browser Software» published in 2012 (google it if they removed the link) on page 5:
«PHP provides several methods for establishing SSL connections. For example, fsockopen, which opens a raw socket to the remote server, can be used to connect to SSL servers by putting “ssl://” in the URL. Even though fsockopen does not perform any certificate checks whatsoever, PHP application developers routinely use it for SSL connection establishment (see Section 9).»
For proper certificate validation with some level of ease, you can always move to cURL, but be careful:
«PHP also provides a cURL binding, which uses cURL’s default settings to establish SSL connections with proper certificate validation. As we show in Sections 7.1, 7.2, and 7.3, application developers often set cURL options incorrectly, overriding the defaults and breaking certificate validation.»
fsockopen() [function.fsockopen]: unable to connect to
I have problem with fsockopen. My site works normal, but when I log in into admin panel (wordpress), I got this error message all over my screen: Warning: fsockopen() [function.fsockopen]: unable to connect to udp://:0 (Failed to parse address «») in /home/visit014/public_html/wp-admin/function.php on line 32
Code of wp-admin/function.php is here:
anyone can help me? I see that it has been similar problems, but not one with functions.php so the code is different. Please help me. Thanks!
1 Answer 1
Your functions.php have been compromised and altered. And someone is using your website to attack other people. It should not contain any such code, reupload a clean version of the script and you should be good.
A very similar script can be found here, and it is used to issue flood attacks to an victim. https://code.google.com/p/php-dos-attacker/downloads/detail?name=php-dos-attacker-1.2b.zip
Not the answer you’re looking for? Browse other questions tagged wordpress fsockopen or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
fsockopen — Открывает соединение с интернет сокетом или доменным сокетом Unix
Описание
stream_socket_client() выполняет аналогичную функцию, но предоставляет более широкий выбор настроек соединения, включающий установку неблокирующего режима и возможность предоставления потокового контекста.
Список параметров
Если установлена поддержка OpenSSL, можно использовать SSL или TLS протоколы соединений поверх TCP/IP при подключении к удаленному хосту. Для этого перед hostname нужно добавить префикс ssl:// или tls://.
Номер порта. Его можно не указывать, передав -1 для тех протоколов, которые не используют порты, например unix://.
Если этот параметр предоставить, то в случае ошибки системного вызова функции connect() он будет принимать номер этой ошибки.
Сообщение об ошибке в виде строки.
Таймаут соединения в секундах.
Возвращаемые значения
Ошибки
Примеры
Пример #1 Пример использования fsockopen()
Пример #2 Использование UDP соединения
Пример ниже демонстрирует, как получить день и время от UDP службы «daytime» (порт 13) на вашей машине.
Примечания
В зависимости от окружения, Unix домен или таймаут установки подключения могут оказаться недоступными.
Иногда UDP сокеты получают статус открытых, даже если удаленный хост недоступен. Ошибка проявит себя только во время чтения или записи данных в/из этого сокета. Причиной этому служит тот факт, что протокол UDP передает данные без установки соединения. То есть операционная система не устанавливает и не держит соединение с сокетом, пока не начнется передача данных.
Замечание: При указании числового адреса IPv6 (например, fe80::1) вы должны заключать его в квадратные скобки. Например, tcp://[fe80::1]:80.
Смотрите также
Warning: fsockopen(): unable to connect to
itrends
Well-Known Member
None of my users (including a few of my own sites) have the right to open a connection (fsockopen) to another server.
«Warning: fsockopen(): unable to connect to *** «
brainx
Member
This probably is caused by your firewall configuration.You may need to allow both incoming and outgoing access for the ip and/or the port number you wish to connect to.
We had similar issues before and have solved them this way.Hope it helps.
Thanks
itrends
Well-Known Member
This probably is caused by your firewall configuration.You may need to allow both incoming and outgoing access for the ip and/or the port number you wish to connect to.
We had similar issues before and have solved them this way.Hope it helps.
Thanks
no, our firewall does not have any rules against this. It allows all outbound traffic, inbound is filtered.
It has to do something with PHP, just can’t figure it out?
richy
Well-Known Member
itrends
Well-Known Member
With SSH it all goes well.. telnet returns valid information.
It’s only when i want to fsockopen() with a script.
jamesbond
Well-Known Member
itrends
Well-Known Member
allow_url_fopen On On
itrends
Well-Known Member
webignition
Well-Known Member
Try specifying the optional paramaters errno and errstr and then print them afterwards. This should give you more specific errors which should aid the troubleshooting process.
itrends
Well-Known Member
Try specifying the optional paramaters errno and errstr and then print them afterwards. This should give you more specific errors which should aid the troubleshooting process.
itrends
Well-Known Member
webignition
Well-Known Member
I suppose if you’ve exhausted all of the options presented here and you’re still unable to resolve the problem, all I could suggest would be:
1. Thoroughly search the forums in case there is a thread on this that you missed
2. Use Google or some other search engine to hunt for solutions
3. Contact your data center for support
4. Hire someone if you’re unable to resolve the issue yourself