★ wanayoo — archive 1999 http://fr.php.net/manual/fi/function.fopen.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links 
search for in the  
previousflockfpassthrunext
Last updated: Tue, 28 May 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Slovak | Spanish | Swedish | Turkish

fopen

(PHP 3, PHP 4 >= 4.0.0)

fopen -- Opens file or URL

Description

int fopen ( string filename, string mode [, int use_include_path])

If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server, the page is requested using the HTTP GET method, and a file pointer is returned to the beginning of the body of the response. A 'Host:' header is sent with the request in order to handle name-based virtual hosts.

As of PHP 4.3.0 (not yet released), if you have compiled in support for OpenSSL, you may use "https://" to open an HTTP connection over SSL.

Note that the file pointer allows you to retrieve only the body of the response; to retrieve the HTTP response header you need to be using PHP 4.0.5 or later; The headers will be stored in the $http_response_header variable. As of PHP 4.3.0 (not yet released), the header information can be retrieved using the file_get_wrapper_data().

HTTP connections are read-only; you cannot write data or copy files to an HTTP resource.

Versions prior to PHP 4.0.5 do not handle HTTP redirects. Because of this, directories must include trailing slashes.

If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and a pointer to the requested file is returned. If the server does not support passive mode ftp, this will fail. You can open files for either reading or writing via ftp (but not both simultaneously). If the remote file already exists on the ftp server and you attempt to open it for writing, this will fail. If you need to update existing files over ftp, use ftp_connect().

If filename is one of "php://stdin", "php://stdout", or "php://stderr", the corresponding stdio stream will be opened. (This was introduced in PHP 3.0.13; in earlier versions, a filename such as "/dev/stdin" or "/dev/fd/0" must be used to access the stdio streams.)

If filename begins with anything else, the file will be opened from the filesystem, and a file pointer to the file opened is returned.

If the open fails, the function returns FALSE.

mode may be any of the following:

  • 'r' - Open for reading only; place the file pointer at the beginning of the file.

  • 'r+' - Open for reading and writing; place the file pointer at the beginning of the file.

  • 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

  • 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

  • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

  • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Huomaa: The mode may contain the letter 'b'. This is useful only on systems which differentiate between binary and text files (i.e. Windows. It's useless on Unix). If not needed, this will be ignored.

You can use the optional third parameter and set it to "1", if you want to search for the file in the include_path, too.

Esimerkki 1. fopen() example

$fp = fopen ("/home/rasmus/file.txt", "r");
$fp = fopen ("/home/rasmus/file.gif", "wb");
$fp = fopen ("http://www.example.com/", "r");
$fp = fopen ("ftp://user:password@example.com/", "w");

If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

$fp = fopen ("c:\\data\\info.txt", "r");

See also fclose(), fsockopen(), socket_set_timeout(), and popen().

User Contributed Notes
fopen
add a note about notes
icon at mricon dot com
09-Nov-1999 09:44

If you're running PHP as apache module, it will always write files as "nobody", "www", "httpd", (or whatever user your webserver runs as) unless you specify a different user/group in httpd.conf, or compile apache with suexec support.
However, if you run PHP as a CGI wrapper, you may setuid the PHP executable to whatever user you wish (*severe* security issues apply). If you really want to be able to su to other user, I recommend compiling with suexec support.
AFAIK, PHP can't NOT use SuEXEC if apache does. If PHP is configured as an apache module it will act as whatever user the apache is. If apache SuEXEC's to otheruser:othergroup (e.g. root:root), that's what PHP will write files as, because it acts as a part of apache code. I suggest you double-check your SuEXEC configuration and settings. Note: you can't su to another user within the PHP code -- it has to be an apache directive, either through <VirtualHost>, or through .htaccess. Also note: I'm not sure how it all works (if it works at all) on Win32 platforms.
Check www.apache.org to see how it's done.

peksalli at iki dot fi
08-Dec-1999 10:34

About writing to file with a specific user id:
You can usually change file permissions with FTP. Just open a FTP connection and say "chmod o+w filename". It is also possible to use FTP connection to write the file, for example, "fopen(ftp://user:password@ftpserver.address/file,w)". That way the file is created and used with your username and password, which (IMHO) is more secure than having files with write permission for all.

jamie dot watt at murchison dot com dot au
03-Feb-2000 02:39

To check if a file exists using http or ftp use the following:

$fp = @fopen("http://www.someurl.com/testfile.php3","r");
if ($fp)
{ print"The file exists!"; }
else
{ print"The file does not exist"; }

Note: The "@" in front of fopen suppresses the error output of the function.

I hope this clears up some confusion.

malhavoc at stomped dot com
08-Jul-2000 12:48

Just a note to individuals who use the fopen() function to reference an external url. fopen() makes no attempt to url encode the url before opening it, so be sure to do that first.

It would be a nice touch to make this function change spaces to + signs and remove illegal url characters, but you can easily get around this by making use of the urlencode() function first.

Enjoy.

WE at MYOIL dot DE
11-Jul-2000 02:54

PHP3 and fopen via proxy-
here is the solution:
....
$myfiles = "http://www.xyz.com/cgi-bin/plz_suche/search_or.cgi?or_plz=$PLZ&or_ort=".rawurlencode($stadt);

$datei = fsockopen("proxy.wdf.sap-ag.de", 8080, &$errno, &$errstr);
if( !$datei )
{
echo "proxy not available !";
fclose($resultfile);
exit();
} else {
fputs($datei,"GET $myfiles/ HTTP/1.0\n\n");
while (!feof($datei))
{
$zeile = fgets($datei,1000);
}
}

Best regards,

Wilfried Ehrensperger

kstone at trivergent dot net
19-Aug-2000 10:44

If you want to run php with suexec, make a interpreter out of it, and then put a cgi=0 in the source (cgi_main.c) or something like that. Grep for SERVER_NAME and you'll see it. Running php w/ binfmt_misc on linux is the way to go, and hopefully the php Gods will bless us with a version I won't have to patch!
paul_tanner at alum dot mit dot edu
08-Dec-2000 10:25

Be careful how you test for errors from fopen(). The familiar construction:

$out=fopen("file","w") || die ("file won't open");

is a great way NOT to create a working filehandle. Test instead with an if as in the note above. The || has the effect of overwriting the filehandle and rendering it useless.

--
editors note: use 'or' instead of '||'

sprite_jd at hotmail dot com
12-Jan-2001 05:15

Beginners (like me): Perheaps a kinda stupid thing, but it is a good idea to ALWAYS fclose a file after you've opened it.
defdac at hotmail dot com
22-Jan-2001 08:41

Newbie advice: The little "b" for binary operations is very essential when working with PHP4 and Apache on the win32 platform. fread() only reads a couple of hundred bytes when reading for example an image without "b".
// Read tempfile data into $thumb_img.
$thumb_file_size = filesize('C:\\Temp\\temp.jpg');
$fp = fopen('C:\\Temp\\temp.jpg', "rb");
$thumb_data = addslashes (fread ($fp, $thumb_file_size));
fclose ($fp);
unlink('C:\\Temp\\temp.jpg');

mnirwan at microshell dot com
21-Feb-2001 11:31

For those people who use fopen to fetch a webpage or to submit a form via get method, there's a workaround to fetch a webpage/submit form via post method. (i.e. when you want to submit data to credit card processing -- most providers only take post method to pass data)

See http://px.sklar.com/code-pretty.html?code_id=313 or http://www.holotech.net/scripts.html

badams at ingenico dot com dot au
29-Mar-2001 04:06

When going to thru proxy server a previous email gave an excellent example but the http request was missing somethings

This worked for me.

fputs($fp, "GET ".$url." HTTP/1.0 r\n\r\n");

Note the \r\n\r\n on the end of the request.

Hope this helps someone else.

thiemonagel at gmx dot de
12-Jul-2001 04:45

Due to request: Description of a workaround for the ftp overwrite anomaly that I have described above:
I use a shell script to delete the file first, then I can use fopen to create it again and write to it. This is the script:
##############################################
# Script deletes file on remote ftp server
# Usage:
# dele <server> <user> <password> <remotefile>
ftp -n -v << EOF
open $1
user $2 $3
dele $4
bye
EOF

ibetyouare at home dot com
26-Jul-2001 08:26

Ok guys just to make a note here. If you are attempting to create a file in a directory, first makes sure you have read/write permissions on that directory.
If you do, check your apache config to make sure you are allowing directory write permissions.
It can be a silly mistake that can cost you a lot of headaches.

keithm at aoeex dot NOSPAM dot com
31-Jul-2001 12:19

I was working on a consol script for win32 and noticed a few things about it. On win32 it appears that you can't re-open the input stream for reading, but rather you have to open it once, and read from there on. Also, i don't know if this is a bug or what but it appears that fgets() reads until the new line anyway. The number of characters returned is ok, but it will not halt reading and return to the script. I don't know of a work around for this right now, but i'll keep working on it.

This is some code to work around the close and re-open of stdin.

<?php
function read($length='255'){
if (!isset($GLOBALS['StdinPointer'])){
$GLOBALS['StdinPointer']=fopen("php://stdin","r");
}
$line=fgets($GLOBALS['StdinPointer'],$length);
return trim($line);
}
echo "Enter your name: ";
$name=read();
echo "Enter your age: ";
$age=read();
echo "Hi $name, Isn't it Great to be $age years old?";
@fclose($StdinPointer);
?>

marcel_levy at onebox dot com
01-Aug-2001 03:34

It appears that fopen() always opens a connection to port 80 when the location string starts with "http://", so these lines are functionally identical:

$fd = fopen('http://www.foo.com:8080/');
$fd = fopen('http://www.foo.com:80/');
$fd = fopen('http://www.foo.com/');

sui at haus-a dot de
10-Aug-2001 06:08

you don't need to use a shell script to delete a file on ftp. just open a socket...

$ftp=fsockopen("ftp.your.host",21);
echo fgets($ftp,255);
fputs($ftp,"USER your_username\r\n");
echo fgets($ftp,255);
fputs($ftp,"PASS your_password\r\n");
echo fgets($ftp,255);
fputs($ftp,"DELE file_to_delete.txt\r\n");
echo fgets($ftp,255);
fputs($ftp,"QUIT\r\n");
echo fgets($ftp,255);
fclose($ftp);

mcrosland at chello dot nl
20-Aug-2001 03:56

If you need to replace the contents of a file, but are getting problems with ownership/permissions, ftruncate can be used to effectively delete the contents by truncating the size of the file to 0 thus;

ftruncate($file,0);
fwrite($file,$my_stuff);


Using this method will allow you to replace the file contents without changing ownership.
The alternative method of using unlink() to delete the file then replacing it with a new file is unsatisfactory because the file created will be owned by 'nobody'.

php at themastermind1 dot com
24-Oct-2001 05:37

I have found that I can do fopen("COM1:", "r+"); to open the comport in windows. You have to make sure the comport isn't already open or you will get a permission denied.

I am still playing around with this but you have to somehow flush what you send to the comport if you are trying to communicate realtime with a device.

slevy1 at pipeline.com
30-Dec-2001 01:54

Attn Perl Programmers:

If you are used to writing script like

do something || die("no can do");

note that in php || has a higher precedence than =

So, don't write:

$h = fopen("$filename", "r") || die("cannot open $filename");

b/c this will overwrite the file ptr!

Now, or has a lower precedence than || and is also lower than =

So, you may write:

$h = fopen("$filename","r") or die("cannot open $filename");

However, you may avoid the entire issue with code like this:


$h = fopen("$filename","r");
if (!$h) {
die("unable to open $filename");
}

mp3godNOSPAM at mail dot ru
30-Jan-2002 10:12

previous notes about using fopen via proxy didn't work for me. so i've written some code, i hope it'll be useful for someone

function fget_proxy($url)
{

$PROXY_URL="proxy.yourisp.org";
$PROXY_PORT=8080;

putenv("http_proxy=$PROXY_URL:$PROXY_PORT");
$result = shell_exec("wget -q -O - $url");

return $result;
}

landrews at email dot com
21-Feb-2002 05:31

To the people haveing problems with opening "ftp:" url opens and files not being written. It seems that PHP wants the complete path. Make sure your not referencing through a soft link or alias. Use the full path from /
ie
/usr/www/htdocs/data/blah.php

16-Mar-2002 01:18
Also if you're server is useing htaccess to authticate users make sure to add the username and password to the http link you're trying to open. I forgot about this and took a while to find.
ie:

fopen("http://user:pass@www.mysite.com/mypage.php");

ellis at geeklab dot net
21-Apr-2002 05:42

The example of appending to a file that is listed above states that you can append to a top of a file using $fp=fopen("file.txt", "aw"); is completely wrong! It will just append to the file. Here's a working method of how to add information to the top of your file:
$a="content";
$file=join(" ",file("file.txt"));
$fp=fopen("file.txt","w");
fputs($fp,$a);
fputs($fp, $file);
fclose($fp);

Now if we could just get a "p" mode in fopen(), that would rock. *hint hint*

jared at dctkc dot com
22-Apr-2002 08:33

<?php
// HOW TO USE PHP TO WRITE TO YOUR SERIAL PORT: TWO METHODS
$serproxy=true;
if ($serproxy) {
// Use this code in conjunction with SERPROXY.EXE
// (http://www.lspace.nildram.co.uk/freeware.html)
// which converts a Serial stream to a TCP/IP stream
$fp = fsockopen ("localhost", 5331, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)";
} else {
$e = chr(27);
$string = $e . "A" . $e . "H300";
$string .= $e . "V100" . $e . "XL1SATO";
$string .= $e . "Q1" . $e . "Z";
echo $string;
fputs ($fp, $string );
fclose ($fp);
}
} elseif ($com1) {
// Use this code to write directly to the COM1 serial port
// First, you want to set the mode of the port. You need to set
// it only once; it will remain the same until you reboot.
// Note: the backticks on the following line will execute the
// DOS 'mode' command from within PHP
`mode com1: BAUD=9600 PARITY=N data=8 stop=1 xon=off`;
$fp = fopen ("COM1:", "w+");
if (!$fp) {
echo "Uh-oh. Port not opened.";
} else {
$e = chr(27);
$string = $e . "A" . $e . "H300";
$string .= $e . "V100" . $e . "XL1SATO";
$string .= $e . "Q1" . $e . "Z";
echo $string;
fputs ($fp, $string );
fclose ($fp);
}
}
?>

me at pagongski dot com
25-Apr-2002 06:57

been having a problem since yesterday while trying to code a shoutbox. It was that i didnt know how to open a .txt, where all the entries would be stored, from different locations on the server (i.e. from root or from archive dir, etc).
well, tried referring to the file to open on fopen using a http url, obviously doesnt work for a or w modes.
So i, desperatley, tried referring to it using something like /usr/name/www/shout.txt, and to my surprise it worked, so i can call the .txt from anywhere on the site.
heres part of the code:

(note the {$HTTP_HOST}{$REQUEST_URI} on the form action so the post gets sent to the right place)

<?
$aqui = "http://{$HTTP_HOST}{$REQUEST_URI}";

?>

<form action=/old?u=http%3A%2F%2Ffr.php.net%2Fmanual%2Ffi%2F%26quot%3B%26lt%3B%3Fprint%28%26quot%3B%24aqui%26quot%3B%29%3B%3F%26gt%3B%26quot%3B&y=1999 method="post">

<input class="inputbox2" type="text" name="sh" value="valor" size="20" maxlength="40">
<input style="color: black; width: 10px; height: 17px;background-color: #aaaaaa; font-family: verdana, arial, helvetica, sans-serif;font-size: 10px;margin-top: 2px;width: 120px" type="submit" name="btrb" value="Adicionar">
</form>

<?

$d = date("H:i-j/m/y");
$fp = fopen ("/usr/home/pagon/www/shout.txt", "a");
if (!($fp))
{
print ("ERROR file not open!");
exit;
}

fputs($fp,"\n");
fputs ($fp,"$d|$sh");
fclose ($fp);

}
?>

just a bit of the code of my shoutbox, but you get the idea, it saved me quite a lot of work and i didnt find this documented anywhere, i thought i only had two choices: referer the file while on the same dir or use http, glad this works. :-)

jos at mindcoders dot com
17-Jun-2002 01:29

If you want to log errors, just use or exit

$fp=fopen($filename,'r') or exit (LogError($filename));

--
editors note: make sure you use 'or', not '||'

01-Jul-2002 04:57
Note that if specifying the optional 'b' (binary) mode, it appears that it cannot be the first letter for some unaccountable reason. In other words, "br" doesn't work, while "rb" is ok!
suraj at _nospam_nospam_symonds dot net
17-Jul-2002 01:41

This note is relevant to the first few notes that talk about writing to files as user 'foobar'.

if one wanted to write to files as user 'foobar' when apache runs as 'root' the new POSIX fucntions. Here's a code snippet explaining how this can be done

<?

$x = posix_getuid ();

if (0 == $x) {
echo "I'm root\n";

$pw_info = posix_getpwnam ("foobar");
$uid = $pw_info["uid"];
posix_setuid ($uid);

$fp = fopen ("/tmp/test.file", "w");
fclose ($fp);
} else {
echo "I'm not root! I'm not worthy... I'm not worthy....\n";
}

?>

[Note:
1. This would only set the uid... not the gid. If you wanted to write to files as 'foobar:foobar' then you also have to do a posix_setgid ($gid);
2. If you are using the CGI version of php4, you should setuid your php4 interpreter: chmod 4755 /path/to/cgi-bin/php4 (generally, /usr/lib/cgi-bin/php4)]

web at affenkrieger.de
23-Jul-2002 02:11

an enhanced version of WebGet (see above):

$file = new GetWebObject("de.php.net", 80, "/");
$data = $file->get_header();

echo $data["status"];
echo $data["Content-Type"];

echo $file->get_content();

class GetWebObject
{
var $host = "";
var $port = "";
var $path = "";
var $header = array();
var $content = "";

function GetWebObject($host, $port, $path)
{
$this->host = $host;
$this->port = $port;
$this->path = $path;
$this->fetch();
}

function fetch()
{
$fp = fsockopen ($this->host, $this->port);

if(!$fp)
{ die("Could not connect to host.");}

$header_done=false;

$request = "GET ".$this->path." HTTP/1.0\r\n";
$request .= "User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)\r\n";
$request .= "Host: ".$this->host."\r\n";
$request .= "Connection: Close\r\n\r\n";
$return = '';

fputs ($fp, $request);

$line = fgets ($fp, 128);
$this->header["status"] = $line;

while (!feof($fp))
{
$line = fgets ( $fp, 128 );
if($header_done)
{ $this->content .= $line;}
else
{
if($line == "\r\n")
{ $header_done=true;}
else
{
$data = explode(": ",$line);
$this->header[$data[0]] = $data[1];
}
}
}

fclose ($fp);
}

function get_header()
{ return($this->header);}

function get_content()
{ return($this->content);}
}

web at affenkrieger.de
26-Jul-2002 03:23

+------------------------------------+
| addition to the GetWebObject class |
+------------------------------------+
the version above doesn't work with binary data, e.g. pictures

replace the fetch method with this one and all should work:

~~8<~~

function fetch()
{
$fp = fsockopen ($this->host, $this->port);

if(!$fp)
{ die("Could not connect to host.");}

$header_done=false;

$request = "GET ".$this->path." HTTP/1.0\r\n";
$request .= "User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)\r\n";
$request .= "Host: ".$this->host."\r\n";
$request .= "Connection: Close\r\n\r\n";
$return = '';

fputs ($fp, $request);

$line = fgets ($fp, 128);
$this->header["status"] = $line;

while (!feof($fp))
{
if($header_done)
{
$line = fread ( $fp, 1024 );
$this->content .= $line;
}
else
{
$line = fgets ($fp, 128);
if($line == "\r\n")
{ $header_done=true;}
else
{
$data = explode(": ",$line);
$this->header[$data[0]] = $data[1];
}
}
}

fclose ($fp);
}

~~>8~~

26-Aug-2002 02:14
Note that the WebGetObject class above does not parse HTTP headers correctly:
- it should detect headers split in multiple lines (they are continued by starting the next line by an additional space or tab),
- it does not handle correctly the slitting between the header name and its value (it requires no space before the colon, and requires one space after it, where HTTP allows no space or additional whitespace): it should split in two parts only lines that contain a ":" character and trim both splitted parts.
- it does not parse header values according to the HTTP format regarding blanks, comma and (comments)
- it does not support headers that may be repeated (and that should be returned either as an array value for the header name stored in the returned key, or by merging headers with a separating comma), so it looses some headers.

Regarding the problem with the "proxying" script, it simply does not work because the HTTP transaction is not complete: it should emit the "Host:" header that most proxies require to specify the proxy host name, even when performing an HTTP/1.0 GET request. This is because most proxies are configured to allow virtual hosts including themselves.

andyNO at SPAMuchicago dot edu
30-Aug-2002 09:42

Playing with fopen("https://xxx", "r") it seems that HTTPS is only supported with OpenSSL AND PHP 4.3 . Older versions of PHP don't seem to be able to do this.
ben at gelbnet dot com
25-Sep-2002 10:53

I was writing a shell script to get input from a user, however, I needed my script to time out after a certain number of seconds if the user didn't enter enough data. The code below descibes the method I used. It's a little hairy but it does work.

-Ben

#!/home/ben/php/bin/php -q
<?
//GLOBALS
$RETURN_CHAR = "\n";
$TIMEOUT = 5; //number of seconds to timeout on input
$PID = getmypid();
$CHILD_PID = 0;

//Make sure program execution doesn't time out
set_time_limit(0);

function set_timeout() {
global $PID;
global $CHILD_PID;
global $TIMEOUT;

$CHILD_PID = pcntl_fork();
if($CHILD_PID == 0) {
sleep($TIMEOUT);
posix_kill($PID, SIGTERM);
exit;
}
}

function clear_timeout() {
global $CHILD_PID;
posix_kill($CHILD_PID, SIGTERM);
}

// read_data()
// gets a line of data from STDIN and returns it
function read_data() {

$in = fopen("php://stdin", "r");
set_timeout();
$in_string = fgets($in, 255);
clear_timeout();
fclose($in);
return $in_string;
}

// write_data($outstring)
// writes data to STDOUT
function write_data($outstring) {
$out = fopen("php://stdout", "w");
fwrite($out, $outstring);
fclose($out);
}

while(1) {
write_data("say something->");
$input = read_data();
write_data($RETURN_CHAR.$input);
}

?>

philihp at philihp dot com
26-Sep-2002 05:15

fopen may not be used on a shoutcast server to connect to web XML stats (http://localhost/admin.cgi?pass=password&mode=viewxml&page=0). In order to connect, you must use fsockopen, and include "User-Agent: Mozilla" as part of your http query.

This is not on the online documentation for shoutcast (as of right now), and can only be found in the README file in the shoutcast directory.

"Your XML parser MUST send a User-Agent: HTTP header containing the word "Mozilla" in order for the DNAS to recognize it as something other than a listener."

zman at inbox dot ru
02-Oct-2002 07:37

feof does NOT work together with
fopen of an URL,
it is only functional together with files on host.

This work:

<?PHP
$fd=fopen("http://www.server.com/index.html","r");
while ($line=fgets($fd,1000))
{
$alltext.=$line;
}
fclose ($fd);
?>

chirchik at r66 dot ru
16-Oct-2002 08:06

If you're experiencing troubles with downloading files using the PROXY example posted here, here's a workaround.

I've been trying to make the proxy example work for two hours when found out that it uses fgets. That's why you can't get pictures properly downloaded.

I've made several changes, so here's a function to use.

function getthroughproxy
($myfiles,
$proxyhost="0.0.0.0",
$proxyport=0){
$errno="";
$errstr="";
$datei = fsockopen($proxyhost, $proxyport, &$errno, &$errstr,30);
if( !$datei )
{
fclose($resultfile);
return array('headers'=>false,
'content'=>false,
'errno'=>$errno,
'errstr'=>$errstr);
// ^^^ proxy not available
// You'll probably want to change this with return false;
// to use in an
// if($file=getthroughproxy){} manner.
// Well, it's up to You
} else {
fputs($datei,"GET $myfiles HTTP/1.0\n\n");
while (!feof($datei))
{
$zeile =$zeile.fread($datei,4096);
}
}
fclose($datei);
return array('headers'=>substr($zeile,0,strpos($zeile,"\r\n\r\n")),
'content'=>substr($zeile,strpos($zeile,"\r\n\r\n")+4),
'errno'=>$errno,
'errstr'=>$errstr);
}

Put Your proxy settings in the header of the function.

According to a comment in PHP web manual, you'll probably need to replace \n\n with \r\n\r\n or vice versa for some proxies.

Usage:

foreach($imgurls as $num=>$url){
$img=getthroughproxy($url);
if($img['content']!==false){
if($new=fopen(
$newurl="/web/news/imageheap".strrchr($url,"/"),"w")){
fputs($new,$img['content']);
fclose($new);
// print_r($img);
foreach($img as $ki=>$vi) unset($img[$ki]);
unset($img);
echo "$url written as $newurl
\n";
}else{
echo "Error opening $newurl for writing
\n";
}
}else{
echo "Error opening $url
\n";
// print_r($img);
}
}

dir at badblue dot com
17-Oct-2002 10:24

Note that some versions of PHP (4.0.3?) appear to have some fopen(URL...) bugs. The fopen will fail occasionally even though the URL is valid and there are sufficient resources on the box to open the URL.

This can likely be fixed by either an upgrade to a newer version or an automatic retry loop in your code.

thecompholio at msn dot com
26-Oct-2002 11:41

I've found that some servers don't support HTTP/1.0 and will actually return a 403 error (forbidden). This is especially true with Google (my favorite search engine). So, in order to get around this limitation of the fopen command I wrote a routine to use HTTP/1.1 instead (i wrote a simple check for a 403 from fopen first, but this is the important piece)...
<START CODE>
$GrabURL = "/search";
$sockhandle = fsockopen("www.google.com", 80, &$errno, &$errstr);
if(!$sockhandle) {
print "server not available!";
} else {
$request = "GET $GrabURL HTTP/1.1\r\n";
$request .= "User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)\r\n";
$request .= "Host: www.google.com\r\n";
$request .= "Connection: Close\r\n\r\n";
fputs($sockhandle, $request);
$line = fgets($sockhandle, 1024); //Request Method
$line = fgets($sockhandle, 1024); //Close Method
$line = fgets($sockhandle, 1024); //Server Type
$line = fgets($sockhandle, 1024); //Date
$line = fgets($sockhandle, 1024); //Transfer-Encoding
$line = fgets($sockhandle, 1024); //Content-Type
$line = fgets($sockhandle, 1024); //Cache-control
$line = fgets($sockhandle, 1024); //Set-Cookie
$line = fgets($sockhandle, 1024); //End Header "space"
$content = "";
while (!feof($sockhandle)) {
$line = fgets($sockhandle, 1024); //Packet length
$length = hexdec($line);
$content .= fread($sockhandle, $length); //Packet data
}
print $content;
}
fclose($sockhandle);
<END CODE>
If you have any questions feel free to email me, to see this code working in action visit http://google.compholio.com/. If you are curious as to why I did this it's because the custom google search doesn't show up properly if you set the links to be white, so I tacked on some HTML to turn the links the appropriate color but not screw everything else up. As of this posting my IP address was in the process of changing, so if you can't reach the site try again in a day or so.

ender at pf dot pl
27-Oct-2002 02:23

Concerning GetWebObject:
in "$line = fgets ($fp, 128);" length of 128 is in some cases too short. Use 256 or 512 if you are receiving garbage in get_content() method.

add a note about notes
previousflockfpassthrunext
Last updated: Tue, 28 May 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Sun Oct 27 04:18:06 2002 CET