View Full Version : Questions on using PHP to connect to an external source
I have a couple of questions on using PHP to connect to an external page, using for example:
$externalsource=fopen("http://site.com/page.htm","r');
1) Is there a way to halt attempt at retriving the above page and move on to the rest of the script after x seconds? If the external page is down, I don't want the entire script to hung.
2) Also, what's the elegant method for retriving such a page? Based on a book I've read, it simply says to specify a large byte number, ie:
$contents=fread($externalsource, 1000000);
Somehow if feels like this is an unelegant solution...
Thanks,
Spookster
11-04-2002, 04:49 AM
As for your first question you could use the fsockopen function to attempt to open a connection with the remote server and if the connection fails will return a value indicating a connection cannot be made which you could use in a conditional statement.
http://www.php.net/manual/en/function.fsockopen.php
Or do you want to keep trying if it fails the first time?
As for your second question. Are you wanting to modify the contents of the external page or are you just wanting to display the contents of it as is somewhere?
Thanks Spooks. I did stumble across the fsockopen function shortly after posting, which seems to be what I need.
For 2), lets say I wish to simply copy the data from the external source into a local file, and manipulate it from there...
Thanks,
Spookster
11-04-2002, 08:56 AM
Well with fread or fgets you need to specify a length that will be greater than the file which obviously is not good if you don't know how big the file is.
You could always use the file function:
http://www.php.net/manual/en/function.file.php
This will read the contents of the file into an array, no need to know the filesize and from there you can manipulate it however you wish or just save it as a local file.
firepages
11-04-2002, 10:22 AM
if fopen wrappers are turned on in the php.ini (and they probably are) , then as spooks said you can fgets the contents, I dont know what the internal timeout for fgets is but if you try this with a non-existant file it dies pretty quickly.
this also gets around knowing the filesize which we cant.
<?
$fp=@fopen('local_copy.txt','w');
$fd = @fopen ("http://www.domain.org/no_existy.html", "r");
if($yaks=@fgets($fd,4096)){ /*does the file exist ?*/
fputs($fs,$yaks);
while (!feof ($fd)) { /*yes so get the rest*/
$yaks= fgets($fd, 4096);
fputs($fs,$yaks);
}
}else{
echo 'does not exist'; /*error log or something ?*/
}
@fclose ($fd);
@fclose($fp);
?>
then you have a local copy to work with...
another alternative is the snoopy class which soes a lot of work for you and can return just headers & even submit POST requests for you
http://snoopy.sourceforge.net
Spookster
11-04-2002, 03:36 PM
Oh yes I forgot about using the yaks. That is the key to it. lol :D
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.