<?php
$a = file_get_contents('http://www.google.com');
echo $
Why is the browser returning this error?
Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: Connection timed out in /home/test.php on line 2
Mostly probably your server cannot connect to an external resource, for example, because of firewall restrictions.
file_get_contents does not work well at all with getting remote files and should not be used. It does not deal with slow network connections or redirects, and does not return error codes. You should use curl instead to fetch remote files.
There is an example in the manual for curl_exec: http://us3.php.net/manual/en/function.curl-exec.php
I had the same problem, couldn't download using file_get_contents(), but using curl on the command line for the same URL worked fine. Turned out it tried to connect over IPv6 which failed.
I solved it by disabling IPv6 in my kernel parameters.
It might be server side issue, might be your server cannot communicate with other server remotely. You have to communicate with server administrator.
For some reason file_get_contents() fails intermittently on some websites that support IPv6 (maybe 20% of the time, the command times-out). Although disabling IPv6 resolves the issue, that is not the best solution as more sites move to IPv6.
I wrote a simple PHP gethtml() function that works around the issue using wget. This will automatically use IPv6 when IPv4 is not available. A minor drawback is that it uses an external command, but I think it is preferable to disabling IPv6.
If wget is not already installed on your distribution, you can install it as follows:
sudo apt install wget
PHP Function Example:
$myhtml = gethtml("http://example.com");
//use instead of file_get_contents() due to inconsistent IPv6 performance
function gethtml($url){return shell_exec("wget --prefer-family=IPv4 -qO- ".$url);}
Related
I am trying to implement the following chat-html5 from git hub:
https://github.com/ivanph/Chat-HTML5
I have uploaded everything to my ISP but I have found that the ISP blocks exec for security reasons.
The file I am calling is :
<?php
/**
* Main Script of phpWebSockets
*
* Run this file in a shell or windows cmd to start the socket server.
* Sorry for calling this daemon but the goal is that this server run
* as daemon in near future.
*
* #author Moritz Wutz <moritzwutz#gmail.com>
* #version 0.1
* #package phpWebSockets
*/
ob_implicit_flush(true);
require 'socket.class.php';
require 'socketWebSocket.class.php';
require 'socketWebSocketTrigger.class.php';
$ip = exec ("ifconfig|grep 'inet:'|grep -v '127.0.0.1' |cut -d: -f2 |awk '{ print $1}'");
$WebSocket = new socketWebSocket($ip,8000);
?>
Is there an alternative way to do this ? Do all Isp's block this ?
What can I do?
Hi Guys
thanks for the responses.
I got a response from the script developer.
I have changed the $ip to the ip address of our web site. I now get the following error:
--2013-08-13 12:07:01-- http://www.wilsea.com/websockets2/startDaemon.php
Resolving www.wilsea.com... 188.64.188.21
Connecting to www.wilsea.com|188.64.188.21|:80... connected.
HTTP request sent, awaiting response... 500 Internal Server Error
2013-08-13 12:07:12 ERROR 500: Internal Server Error.
The developer says this means that the port (8000) is in use so I tried 80 - 443 - 8080 but got the same error.
I have emailed the ISP and asked if websockets are blocked or if I need a port opening.
Anyone else had this issue or any insights into this problem?
Is there an alternative way to do this ?
There also are system and shell_exec, but I'd assume this to be disabled for the same reasons.
Like pointed out in the comments, you could also just provide your server's static IP instead of having the script determine it. However, chances are sockets are disabled as well, so don't put your hopes too high.
Do all Isp's block this ?
Most Hosting Providers do. Obviously a hosting service doesn't want you to run arbitrary commands on the shell that could potentially reconfigure the machine.
What can I do?
Get paid hosting that allows you to exec. A VPS or a dedicated server comes to mind.
I could try to find a way to detect a good listening address in PHP to avoid this monstrosity. (The workaround would probably be $ip = '0';) Your next question would be: Fatal error: Call to undefined function socket_create() why is my ISP so mean?. exec() is blocked for good reasons on a shared hosting and you won't be allowed to create a socket with create_socket().
No hoster will want something like this on their shared server. You'll have to get your own system but then you wouldn't want this code to run on it. This is because you don't want to run this code anywhere unless you were trying to improve on it. But then you'd be improving on a solution which builds on the sand that is PHP. And that would be sad.
Get a cheap virtual server if you really want to use this. I don't recommend it. Looks like somebody is trying to use PHP for a task it's not designed to do. If you've gotten this far without understanding the issues involved I recommend you to stay far away from it. Try it on localhost if you must, so you're not harming other people.
The issue was the ISP blocks all port. They have now opened the port for me.
Cheers
SteveW
$output = file_get_contents("http://www.canadapost.ca/cpc2/addrm/hh/current/indexa/caONu-e.asp");
var_dump($output);
HTTP 505 Status means the webserver does not support the HTTP version used by the client (in this case, your PHP program).
What version of PHP are you running, and what HTTP/Web package(s) are you using in your PHP program?
[edit...]
Some servers deliberately block some browsers -- your code may "look like" a browser that the server is configured to ignore. I would particularly check the user agent string that your code is passing along to the server.
Check in your PHP installation (php.ini file) if the allow_url_fopen is enabled.
If not, any calls to file_get_contents will fail.
It works fine for me.
That site could be blocking the server that you're using to access it.
When you run the URL from your browser, your own ISP is used to get the information and display in your browser. But when you run from PHP, the ISP of your web host is used to get the information, then it passes it back to you.
Maybe you can do this to check and see what kind of headers its returning for you?
$headers=get_headers("http://www.canadapost.ca/cpc2/addrm/hh/current/indexa/caONu-e.asp");
print_r($headers);
Here is a snippet of my code
$fp = fsockopen($s['url'], 80, $errno, $errstr, 5);
if($fp){
fwrite($fp, $out);
fclose($fp);
When I run it, it outputs:
unable to connect to www.mydomain.net/1/file.php:80 (php_network_getaddresses: getaddrinfo failed: Name or service not known
I'm using this to submit GET data to the $s['url']
I can't figure out why. Any help would be greatly appreciated.
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.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n");
That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.
I had a similar problem on my local testserver and local testdomains e.g.: www.testdomain.loc with the function GetImageSize();
Solved it by adding the hostname in the hosts file on the local server:
In the file /etc/hosts I added:
192.168.1.1 www.testdomain.loc
If you only want to submit GET data to the URL, you should use something straightforward like file_get_contents();
$myGetData = "?var1=val1&var2=val2";
file_get_contents($url.$myGetData);
Had such a problem (with https://github.com/PHPMailer/PHPMailer), just reload PHP and everything start worked
for Centos 6 and 7:
service php-fpm restart
$url = "http://user:pass#www.example.com/abc.php?var1=def";
$contents = file_get_contents($url);
echo $contents;
you are trying to open a socket to a file on the remote host which is not correct. you could make a socket connection (TCP/UDP) to a port number on a remote host. so your code should be like this:
fsockopen('www.mysite.com', 80);
if you are trying to create a file pointer resource to a remote file, you may use the fopen() function. but to do this, you need to specify the application protocol as well.
PHP provides default stream wrappers for URL file opens. based on the schema of the URL the appropriate stream wrapper will be called internally. the URL you are trying to open does not have a valid schema for this solution. make sure there is a schema like "http://" or "ftp://" in it.
so the code would be like this:
$fp = fopen('http://www.mysite.com/path/file.txt');
Besides I don't think the HTTP stream wrapper (that handles actions on file resources on URLs with http schema) supports writing of data. you can use fread() to read contents of a the URL through HTTP, but I'm not sure about writing.
EDIT:
from comments and other answers I figured out you would want to send a HTTP request to the specified URL.
the methods described in this answer are for when you want to receive data from the remote URL. if you want to send data, you can use http_request() to do this.
I was getting the same error of fsocket() and I just updated my hosts files
I logged via SSH in CentOS server. USERNAME and PASSWORD
type
cd /etc/
ls //"just to watch list"
vi hosts //"edit the host file"
i //" to put the file into insert mode"
95.183.24.10 [mail_server_name] in my case ("mail.kingologic.com")
Press ESC Key
press ZZ
hope it will solve your problem
for any further query please ping me at http://kingologic.com
In my case this error caused by wrong /etc/nsswitch.conf configuration on debian.
I've been replaced string
hosts: files myhostname mdns4_minimal [NOTFOUND=return] dns
with
hosts: files dns
and everything works right now.
Try to set ENV PATH. Add PHP path in to ENV PATH.
In order for this extension to work, there are DLL files that must be available to the Windows system PATH. For information on how to do this, see the FAQ entitled "How do I add my PHP directory to the PATH on Windows". Although copying DLL files from the PHP folder into the Windows system directory also works (because the system directory is by default in the system's PATH), this is not recommended. This extension requires the following files to be in the PATH: libeay32.dll
http://php.net/manual/en/openssl.installation.php
in simple word your site has been blocked to access network. may be you have automated some script and it caused your whole website to be blocked. the better way to resolve this is contact that site and tell your issue. if issue is genuine they may consider unblocking
I had a similar problem when connecting to a local MySQL database, only changed the url for the ip address 127.0.0.1 and it worked. You could change the url for the ip address of the server.
any idea why fopen would timeout for a file if it is on my server and I know the url is correct?
update: sorry, i should have mentioned this is in php.
the code is:
fopen($url, 'r');
It works if i put in a relative path for the file, but not if $url is a url in my server (but it works for google.com). Thanks for the help.
Alaitnik's answer was right. The problem only appears when i access my own server files through the ethernet interface. How can I fix this? I need to be able to access the file from the ethernet interface because the url loads dynamically (it's generated from a wordpress cms, so the url doesn't technically exist as a file on my server)
you can use
ini_set('default_socket_timeout',2);
before opening the fopen $url . This actually set the default socket connection timout without responding.
Stream_set_timeout sets time out on the stream that is established via fopn or socket opening functions.
Try this may be helpful for you.
It appears that you're trying to download a file from your own server using the HTTP protocol from a program running on that same server?
If so, the timeout problem is likely to be web server or network configuration related. Timeouts normally only happen because either:
the server really is taking a long time to send back the answer, or
the TCP connection is being blocked
For example, it may be that your local firewall rules only permit access to www.example.com if those queries come from the ethernet interface, but a locally made connection would try to go via the loopback interface.
maybe your "allow_url_fopen" is set to "Off"
check your php.ini file or phpinfo()
If you are trying to get the HTML of a URL, I suggest using curl instead of fopen.
fopen is best used with local files, coz it does not "know" how to deal with the idiosyncrasies of a network resource.
Check the comments on the documentation of fopen. There's a whole lot of gold in there.
Took me ages to solve this, but here I found it, thanks to Alnitak. Opening the file with localhost in the URL instead of the hostname was what did the trick for me.
I'm on a Linux system where I am not allowed to use the 'ping' application (ping: icmp open socket: Operation not permitted). However, the script that I am writing (PHP, but I can use an exec() call to any script/program if needed) needs to determine if a host is 'alive'. How can I go about this without using 'ping'?
If ping can't do it, you can't do it in a different language. Here is an analogy that may help you understand why. Let's say there is a file on the file system and you want to its contents. You run cat filename and it says cat: filename: Permission denied. Do you think Perl (or any other language) will fair better than C did here? Let's try:
#!/usr/bin/perl
use strict;
use warnings;
die "usage: $0 filename" unless #ARGV == 1;
my $filename = shift;
open my $fh, "<", $filename
or die "could not open $filename: $!\n";
print while <$fh>;
When run against the file it says could not open filename: Permission denied. No matter what language you try to use, you are going to get Operation not permitted.
That said, there are other methods of determining if a machine is alive. If there is a server that is known to always be running on the machine, you could try to connect to it. Note that you don't need to finish the connection (e.g. log in), just the fact that you can successfully initiate the connection is enough to know that box is up.
To do a ping (ICMP) you need root access.
The only way you have is to do a TCP or UDP ping.
If you want an example check the code of Cacti or you can use hping to do it for you
Or you can set SUID bit on "ping" program on unix ;)
http://us2.php.net/manual-lookup.php?pattern=socket
But if you can't open a socket with ping, it's unlikely that you can use any of these. Talk to your hosting provider.
The PHP Manual gives user supplied code for an implementation of a ping in PHP. Unfortunately, it requires root access so it's not likely you'll be able to use that either. One alternative is to use curl and look at the values returned by curl_getinfo():
c = curl_init('http://www.site.com/');
curl_exec($c);
$info = curl_getinfo($ch);
It is nowhere near being equivalent to ping, but still maybe suitable for your needs.