You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.
If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.
If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:
$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1n");
fputs($fp, "Host: www.mydomain.netn");
fputs($fp, "Connection: closenn");
That leaves any error handling up to you of course, but it would mean that you wouldn’t waste time reading the response.
You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.
If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.
If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:
$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1n");
fputs($fp, "Host: www.mydomain.netn");
fputs($fp, "Connection: closenn");
That leaves any error handling up to you of course, but it would mean that you wouldn’t waste time reading the response.
You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.
If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.
If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:
$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1n");
fputs($fp, "Host: www.mydomain.netn");
fputs($fp, "Connection: closenn");
That leaves any error handling up to you of course, but it would mean that you wouldn’t waste time reading the response.
|
Пользователь 32599 Эксперт Сообщений: 1135 |
#1 0 15.10.2012 19:58:04 При попытке перейти на страницу обновлений вот такое сообщение: Ошибка Внутри локальной сети портал доступен по адресу 192.168.0.10 Техподдержка ответила
Портал висит на BitrixVM 3.1, все работает из под администратора на Windows Server 2008, интернет есть на машине. Куда копать? Профессиональная и дорогая вёрстка. |
||
|
Пользователь 57829 Гуру Сообщений: 3754 |
Андрей Погорелый, думаю проблема с настройками DNS на виртуальной машине, посмотрите что написано в файле /etc/resolv.conf |
|
Пользователь 36078 Эксперт Сообщений: 602 |
Если обновлять по частям, то всё ок |
|
Пользователь 125789 Заглянувший Сообщений: 4 |
vi /etc/sysconfig/network добавить: |
|
Пользователь 57829 Гуру Сообщений: 3754 |
#5 0 07.05.2014 13:32:20
т.е. вас не смущает что у кого то может быть и другой шлюз? Карточка партнера Наш сайт |
||
|
Пользователь 277908 Заглянувший Сообщений: 45 |
Аналогчно. Интегрирую свой интернет-магазин с CRM (демо на вирт. машине). Обновление прошло в штатном режиме, но дальше, после введения адреса своего аккаунта на Битрикс-24, логина и пароля, появляется сообщение: [0] php_network_getaddresses: getaddrinfo failed: Name or service not known Кто виноват и что делать? |
|
Пользователь 57829 Гуру Сообщений: 3754 |
настраивать DNS, php не может получить информацию по доменному имени. |
|
Пользователь 277908 Заглянувший Сообщений: 45 |
Не может ли это быть ограничением демо-версии? |
|
Пользователь 57829 Гуру Сообщений: 3754 |
#9 0 02.09.2014 10:20:17
нет. Карточка партнера Наш сайт |
||
|
Пользователь 132775 Постоянный посетитель Сообщений: 180 |
#10 0 23.09.2014 08:24:14 Такая же проблема. Случается в неопределенном порядке, через раз, будто выставлено какое-то ограничение, иногда отрабатывает, иногда нет.
Блог о веб-разработке | Каталог сайтов |
||
|
Пользователь 53386 Постоянный посетитель Сообщений: 269 |
#11 0 23.09.2014 10:17:23
Рустам, это сообщения указывают на то, что запрашиваемое у DNS сервера доменное имя — не найдено, т.е. либо действительно имени не существует, либо у вашего сервера/виртуальной машины в данный момент нет доступа к DNS серверу. |
||
|
Пользователь 132775 Постоянный посетитель Сообщений: 180 |
#12 1 23.09.2014 17:30:51
Самое стремное в этой ситуаци то, что доменное имя есть, и DNS сервер работает. С локалки (под виндой) скрипт отрабатывает на ура, стабильно коннектится к тому же серверу, на боевом сервере (vmbitrix — centos) через раз возникают глюки с такими ошибками. Где-то на форумах встретил предположение что возможно, но не сто пудово может быть недостаточно ресурсов для выполнения команды. Блог о веб-разработке | Каталог сайтов |
||||
|
Пользователь 365352 Заглянувший Сообщений: 5 |
#13 0 30.07.2015 16:46:44 [img]c:UsersO’tkirbekDesktop1111111[/img] |
|
Пользователь 365352 Заглянувший Сообщений: 5 |
#14 0 30.07.2015 16:47:09 Ошибка [0] php_network_getaddresses: getaddrinfo failed: Name or service not known |
|
Пользователь 262639 Заглянувший Сообщений: 26 |
#15 0 06.09.2015 10:24:43 Столкнулся с данной проблемой и не могу понять из-за чего не может получить IP-адрес, на этой же виртуальной машине выполняет:
Также работает вот такая команда:
И вот даже это из командной строки выполняется:
Но при выполнении подобного скрипта уже через веб-сервер, ничего не возвращает, вернее согласно спецификации самой команды, возвращается имя хоста в случае неудачи : Вот собственно и вопрос, почему веб-окружение работает не правильно и как это оно отделилось от настроек самой виртуальной машины? UPD: Подумал о каких-нибудь ограничениях для пользователя bitrix, выполнил в командной строке все тоже что и для root, все выполнилось правильно, везде все работает, но через веб-сервер не работает? Почему? |
||||||
|
Пользователь 262639 Заглянувший Сообщений: 26 |
#16 8 06.09.2015 11:02:37 Разобрался! Оказалось все очень просто, необходимо после настройки сети остановить Apache и через несколько секунд запустить снова. Простой перезапуск не помогает. Проблема связана с какой-то хренью в mod_php. Поэтому если запустили виртуальную машину, настроили сеть — обязательно остановите Apache и запустите его спустя какое-то время. |
|
Пользователь 101762 Заглянувший Сообщений: 3 |
#17 0 30.01.2016 17:29:40
спасибо, помогло…долго пришлось повозиться с этой проблемой |
||
|
Пользователь 187465 Заглянувший Сообщений: 4 |
#18 0 26.07.2016 14:28:03
Спасибо! Мне тоже помогла эта магия. |
||
|
Пользователь 269339 Постоянный посетитель Сообщений: 161 |
#19 0 12.08.2016 13:43:12 Обновился, сайт упал и вылезла ошибка: Ошибка Пожалуйста, техническая поддержка, ответьте на обращение: 1101899 |
|
Пользователь 209695 Эксперт Сообщений: 787 |
#20 1 12.08.2016 15:15:56 Вероятно это связано с последним обновлением ядра. Откатите изменения, выключите мемкеш, обновитесь и включите мемкеш При этом (если только одно обновление для ядра требуется) н сколько я понял база не трогается. Я откатывал только файлы. |
|
Пользователь 406092 Заглянувший Сообщений: 14 |
#21 0 17.08.2016 09:38:14
Александр, мне откатывать не понадобилось. После обращения в поддержку мне было посоветовано отключить memcashe в файле .settings.php и потом обновиться. После этого — все сразу обновилось. |
||
|
Пользователь 73356 Посетитель Сообщений: 68 |
#22 0 21.08.2016 16:28:56 А после обновления ни у кого при проверке не выдает ошибку структуры базы данных? Как ее исправить? |
|
Пользователь 508285 Заглянувший Сообщений: 1 |
#23 0 06.09.2016 11:55:39
помогло просто остановка memcached, при этом было выключено все кеширование через админку. непонятно почему он кеширует если везде указано не кешировать. |
||||
|
Пользователь 631057 Посетитель Сообщений: 21 |
#24 1 29.06.2017 07:46:26 Такая же ошибка возникла в журнале проверки системы, при полном тестировании системы в Docker’е:
Решилось добавлением имени сайта в файле /etc/hosts к 127.0.0.1:
Не ты выбираешь Linux, а Linux выбирает тебя |
||||
|
Пользователь 247426 Заглянувший Сообщений: 6 |
#25 1 02.11.2017 20:51:49 со слов тех поддержки хостера: systemctl restart httpd /etc/resolv.conf Generated by NetworkManager nameserver 8.8.8.8 и все — php_network_getaddresses: getaddrinfo failed: Name or service not known исправилась |
Comments
Description:
mysql, redis This problem occurs under the debug of phpstorm. This problem does not occur directly in the browser or postman. I want to know what causes it.
error
redis
php_network_getaddresses: getaddrinfo failed: Name or service not known [tcp://reids:6379]
mysql
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
Project configuration file .env
redis
REDIS_HOST=reids REDIS_PASSWORD=null REDIS_PORT=6379
mysql
DB_HOST=mysql DB_PORT=3306 DB_DATABASE=campaign DB_USERNAME=root DB_PASSWORD=root
docker fo mac
dcoker:19.03
docker-compsoe:1.25.2
check container working first.
docker-compse ps
docker-compse logs mysql
docker-compse logs redis
Ref #2507
Probably typo:
REDIS_HOST=reids
@metalcamp Not the problem, the configuration is wrong
@pizsd: Is your redis service (in docker-compose.yml) also named reids?
I’m getting this error too.
IlluminateDatabaseQueryException : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
when i run tests from phpstorm I’m getting this. But i didn’t get this when i run from terminal like phpunit TestsExampleTest
My project .env
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=default
DB_USERNAME=default
DB_PASSWORD=secret
laradock .env
MYSQL_VERSION=5.7
MYSQL_DATABASE=default
MYSQL_USER=default
MYSQL_PASSWORD=secret
MYSQL_PORT=3306
docker-compose.yml
mysql:
build:
context: ./mysql
args:
- MYSQL_VERSION=${MYSQL_VERSION}
environment:
- MYSQL_DATABASE=${MYSQL_DATABASE}
- MYSQL_USER=${MYSQL_USER}
- MYSQL_PASSWORD=${MYSQL_PASSWORD}
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
- TZ=${WORKSPACE_TIMEZONE}
volumes:
- ${DATA_PATH_HOST}/mysql:/var/lib/mysql
- ${MYSQL_ENTRYPOINT_INITDB}:/docker-entrypoint-initdb.d
ports:
- "${MYSQL_PORT}:3306"
networks:
- backend
My Solution:
PhpStorm->Preferences->Languages & Frameworks->PHP->Test Frameworks
Add PHPUnit by Remote Interpreter
Select Docker interpreter
After created you should add link ( Links section ) which one do u want to use ( mysql, redis) to docker container (click Browse in docker container section)
And if you know which network is using in docker container you should write name of network ( docker network ls ) into Network Mode section then click OK . That’s it.
But if you don’t know which network is using . First you should remove all unused networks ( docker network prune ) then run ( docker network ls )
Hi 👋 this issue has been automatically marked as stale 📌 because it has not had recent activity 😴. It will be closed if no further activity occurs. Thank you for your contributions ❤️.
Hi again 👋 we would like to inform you that this issue has been automatically closed 🔒 because it had not recent activity during the stale period. We really really appreciate your contributions, and looking forward for more in the future 🎈.
My Solution:
PhpStorm->Preferences->Languages & Frameworks->PHP->Test Frameworks
Add PHPUnit by Remote Interpreter
Select Docker interpreter
After created you should add link ( Links section ) which one do u want to use ( mysql, redis) to docker container (click Browse in docker container section)
And if you know which network is using in docker container you should write name of network (
docker network ls) into Network Mode section then click OK . That’s it.But if you don’t know which network is using . First you should remove all unused networks (
docker network prune) then run (docker network ls)
changing Network mode from bridge to docker internal network fixed my problem
In my case error was misleading. You have to run commands from docker container eg docker-compose exec containerName (app) php (serviceName) bin/console doctrine:migrations:migrate (service command).
I was trying to run it from outside of the container. Dunno how not connected redis to doctrine is related during doctrine command, but that was the case. Lost 2-3 hours on that and asked for help other dev.
hi @ugurdnlr,
Regarding this section «After created you should add link ( Links section ) which one do u want to use ( mysql, redis) to docker container (click Browse in docker container section)», could you explain in more detail with screenshot?
I try to config but an error occurs
This is screenshots of my config



Thanks in advance
“SMTP ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed”. Well, this is how my week started. One of my client’s website running WordPress and Easy WP SMTP plugin failed to send mails. Though I rechecked all the mail configurations, test mails via Easy WP SMTP failed with the above error followed by “Name or service not known (0)SMTP connect() failed”. I could solve the issue after an hour of debugging.
Error : Failed to connect to server: php_network_getaddresses: getaddrinfo failed
This error can occur due to two reasons. One, there might me an issue with your DNS settings and second, PHP may not be able to get the network addresses for a given host/domain name.
To start with, I checked the mail settings in Easy WP SMTP plugin and everything was fine. Next, I contacted my DNS provider and confirmed that the issue is not with DNS. So it means, the issue boils down to PHP and as I rightly guessed, PHP was not able to resolve domain names. For example, while debugging, I thought the issue might be due to an outdated Easy WP SMTP plugin, so I decided to update the plugin to only see the error “wordpress.org : Name or service not known”.
It means, for some reason PHP was not able to get the network addresses of the given domain name. To confirm that the issue is with PHP, I wrote a small script as shown below:
<?php
$ip = gethostbyname('www.google.com');
echo $ip;
?>
The function gethostbyname will get the IPv4 address corresponding to the given host name or prints back the host name on failure. In my case, the output was an unmodified host name. It means, gethostbyname has failed to get the IP address of the given host name and that was the culprit.
All I did to fix the issue was to restart the php-fpm daemon and everything worked fine. Unfortunately, I couldn’t find what caused php-fpm to fail, but more often restarting the daemon fixes many issue. Hope it helps someone in need.
You might have encountered the following warning while working with databases, servers, or web services in PHP.
Warning : php_network_getaddresses: getaddrinfo failed: No such host is known
The warning is caused when your system cannot find a valid DNS server. This article will introduce a method to get rid of such warnings.
Ensure the Host Exists Using the dns_get_record() PHP Function
We can interact and read contents from a website using the file functions like fopen(), fgets() and fclose() in PHP. While opening a URL, you might encounter a warning message that says No such host is known.
The complete warning is shown at the beginning of the article. One probable reason for the warning is that the host may not exist.
Therefore, it is a good approach to check the host’s status.
We can use the dns_get_record() PHP function to see the DNS Resources Records of a particular host. We can set the hostname in the function and obtain its DNS information.
For example, create a variable $result and assign the function dns_get_record() to it. Write the hostname stackoverflow.com as the parameter to the function.
Next, use print_r() to display the information of the $result variable.
Example Code:
$result = dns_get_record("stackoverflow.com");
echo '<pre>', print_r($result), '</pre>';
Output:
Array
(
[0] => Array
(
[host] => stackoverflow.com
[class] => IN
[ttl] => 186
[type] => A
[ip] => 151.101.129.69
)
[1] => Array
(
[host] => stackoverflow.com
[class] => IN
[ttl] => 186
[type] => A
[ip] => 151.101.65.69
)
[2] => Array
(
[host] => stackoverflow.com
[class] => IN
[ttl] => 186
[type] => A
[ip] => 151.101.1.69
)
[3] => Array
(
[host] => stackoverflow.com
[class] => IN
[ttl] => 186
[type] => A
[ip] => 151.101.193.69
)
)
1
The output displays the DNS Resource Records of stackoverflow.com. It ensures the hostname exists.
If the hostname does not exist, the output will be something like this.
Output:
You can also check the name resolution with the ping command. Type the following in the terminal.
ping stackoverflow.com
Output:

If the host does not exist, the output is something like this.
ping: pokharasahar.com: Name or service not known
Here, we have used the hostname pokharasahar.com, which does not exist.
Thus, we can perform name resolution using the dns_get_record() function to ensure the domain exists. This way, we can get rid of PHP’s php_network_getaddresses: getaddrinfo failed warning.