|
|
 |
fopen (PHP 3, PHP 4 ) fopen -- Otwiera plik lub URL Opisint fopen ( string nazwa_pliku, string tryb [, int użyj_include_path])
Jeśli nazwa_pliku zaczyna się od "http://" (nie
jest rozróżniana wielkość liter), jest otwierane połączenie HTTP 1.0
do wybranego serwera, strona jest żądana używając metody HTTP GET
i wskaźnik pliku jest ustawiany na początku ciała odpowiedzi.
Nagłówek 'Host:' jest wysyłany z żądaniem pozwalającym
uchwycić oparte o nazwę wirtualne hosty.
W PHP 4.3.0 (jeszcze nie udostępnionym), jeśli masz wkompilowane wsparcie dla
OpenSSL, możesz użyć "https://" aby otworzyć połączenie HTTP po SSL.
Zauważ, że wskaźnik pliku pozwala tobie odczytać tylko
ciało odpowiedzi; aby uzyskać nagłówek HTTP
musisz użyć wersji PHP 4.0.5 lub nowszej.
Nagłówki są przechowywane w zmiennej $http_response_header.
W PHP 4.3.0 (jeszcze nie udostępnionym), informacja z nagłowka może
być pobrana używając funkcji file_get_wrapper_data().
Połączenia HTTP są tylko do odczytu, nie możesz zapisać danych lub
kopiować plików do zasobu HTTP.
Wersje przed PHP 4.0.5 nie obsługują przekierowań HTTP. Z tego powodu
katalogi muszą zawierać kończące slashe.
Jeśli nazwa_pliku zaczyna się od "ftp://"
(nie jest rozróżniana wielkość znaków), jest otwierane połączenie
ftp do podanego serwera i zwracany jest wskaźnik do żądanego pliku.
jeśli serwer nie obsługuje trybu pasywnego ftp, ta funkcja zawiedzie.
Możesz otwierać pliki albo do odczytu lub zapisu przez ftp (ale nie
oba tryby równocześnie). Jeśli zdalny plik już istnieje na serwerze FTP
i spróbujesz otworzyć go do zapisu, ta funkcja zawiedzie.
jeśli potrzebujesz zmodyfikować istniejące pliki przez FTP, użyj
ftp_connect().
Jeśli nazwa_pliku jest jedną z możliwości
"php://stdin", "php://stdout" lub "php://stderr" zostanie otworzony
odpowiedni strumień stdio. (To zostało wprowadzone w PHP 3.0.13;
we wcześniejszych wersjach, aby dostać się do strumienia stdio
nazwa_pliku musi mieć postać "/dev/stdin" lub "/dev/fd/0".)
Jeśli nazwa_pliku zaczyna się czymkolwiek innym
zostanie otworzony plik z systemu plików i zostanie zwrócony wskaźnik
pliku.
Jeśli otwieranie się nie powiedzie, funkcja zwróci FALSE.
tryb może być dowolny z poniższych:
'r' - Otwórz tylko do odczytu; ustawia wskaźnik pliku na początku
pliku.
'r+' - Otwórz do odczytu i zapisu; ustawia wskaźnik pliku na początku
pliku.
'w' - Otwórz tylko do zapisu; ustawia wskaźnik pliku na początku
pliku i obcina plik (zeruje) do 0 długości.
Jeśli plik nie istnieje to próbuje go utworzyć.
'w+' - Otwórz do odczytu i zapisu; ustawia wskaźnik pliku na początku
pliku i obcina plik (zeruje) do 0 długości.
Jeśli plik nie istnieje to próbuje go utworzyć.
'a' - Otwórz tylko do zapisu; ustawia wskaźnik pliku na końcu
pliku. Jeśli plik nie istnieje to próbuje go utworzyć.
'a+' - Otwórz do odczytu i zapisu; ustawia wskaźnik pliku na końcu
pliku. Jeśli plik nie istnieje to próbuje go utworzyć.
Notatka:
Parametr tryb może zawierać literę
'b'. To jest użyteczne tylko na systemach, które rozróżniają
pliki pomiędzy binarne i tekstowe (np. Windows. To jest
bezużyteczne na Unixach)
Jeśli nie potrzebne zostanie zignorowane.
Możesz użyć opcjonalnego 3 parametru i ustawić go na "1", jeśli
chcesz szukać pliku także w
include_path.
Przykład 1. fopen() przykład $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"); |
|
Jeśli doświadczasz problemów z czytaniem i zapisywaniem do plików
i używasz PHP jako moduł serwera, pamiętaj, że pliki i katalogi
które używasz muszą być osiągalne dla procesu serwera.
Na platformach Windows, uważaj na zastosowanie znaków ucieczki
dla wszystkich użytych w ścieżce do pliku backslashy, lub
użyj slash'y.
Patrz także: fclose(),
fsockopen(),
socket_set_timeout() i
popen().
sergiopaternoster at tiscali dot it
27-Nov-2003 10:11
If you want to open large files (more than 2GB) that's what I did and it works: you should recompile your php with the CFLAGS="-D_FILE_OFFSET_BITS=64" ./configure etc... This tells to your compiler (I tested only gcc on PHP-4.3.4 binary on Linux and Solaris) to make the PHP parser binary large file aware. This way fopen() will not give you the "Value too large for defined data type" error message.
God bless PHP
ciao
Sergio Paternoster
ken dot gregg at rwre dot com
25-Nov-2003 08:03
PHP will open a directory if a path with no file name is supplied. This just bit me. I was not checking the filename part of a concatenated string.
For example:
$fd = fopen('/home/mydir/' . $somefile, 'r');
Will open the directory if $somefile = ''
If you attempt to read using the file handle you will get the binary directory contents. I tried append mode and it errors out so does not seem to be dangerous.
This is with FreeBSD 4.5 and PHP 4.3.1. Behaves the same on 4.1.1 and PHP 4.1.2. I have not tested other version/os combinations.
dan at cleandns dot com
19-Nov-2003 04:15
<?php
$counter_file = '/tmp/counter.txt';
clearstatcache();
ignore_user_abort(true); if (file_exists($counter_file)) {
$fh = fopen($counter_file, 'r+');
while(1) {
if (flock($fh, LOCK_EX)) {
$buffer = chop(fread($fh, filesize($counter_file)));
$buffer++;
rewind($fh);
fwrite($fh, $buffer);
fflush($fh);
ftruncate($fh, ftell($fh));
flock($fh, LOCK_UN);
break;
}
}
}
else {
$fh = fopen($counter_file, 'w+');
fwrite($fh, "1");
$buffer="1";
}
fclose($fh);
print "Count is $buffer";
?>
Bill Fletcher
18-Nov-2003 03:33
I had the same problem mentioned by Tim Fountain below: trying to open a file larger than 2 GB to read it throws the error "Value too large for defined data type" . (This error is explain in the online manual under filesize(), but no workaround for OPENING files is given.)
After lots of Googling (mainly to unanswered forum questions) I found a workaround on a Perl forum:
open a pipe to "cat filename":
$fh = popen("cat $filename", "r");
Hope this saves someone some of the grief I've just gone through!
Bill
fade at punkass dot com
06-Oct-2003 05:44
a fast way of retrieving a single random line from a large file:
<?php
$fp = fopen("/path/to/file", "r");
$seek = rand(0, filesize("/path/to/file"));
fseek($fp, $seek);
fgets($fp); print fgets($fp); fclose ($fp);
?>
ofcourse this can be easily used to retrieve more than one line quite easily. I've tried this on a 17mb irc log file on a p2 mmx 233 with 32MB ram and an old 1.2gb HD in a for-loop, running this section of code 100 times (including the fclose), an it finishes in an average of 0.5 seconds. The 800kb log file I tried did it in about 0.1 seconds.
(note that there's a small chance, depending on your filesize, that the rand() will return the last byte and that the fgets will return EOF and nothing else, so you might want to use $seek = rand(1024, (filesize("path/to/file")) - 1024; instead so you should always get a valid line.)
phpNO at SPAMperfectweb dot com
31-Jul-2003 06:39
I offer the following script for updating a counter, using methods gleaned from various posts on file operations...
<?
$counter_file = 'somefile.txt';
clearstatcache();
ignore_user_abort(true); $fh = fopen($counter_file, 'r+b'); if ($fh)
{
if (flock($fh, LOCK_EX)) {
$count = fread($fh, filesize($counter_file));
rewind($fh);
$count++;
fwrite($fh, $count);
fflush($fh);
ftruncate($fh, ftell($fh)); flock($fh, LOCK_UN);
} else echo "Could not lock counter file '$counter_file'";
fclose($fh);
} else echo "Could not open counter file '$counter_file'";
ignore_user_abort(false); echo "counter is at $count";
?>
unshift at yahoo dot com
01-Jul-2003 09:58
It seems that fopen() errors when you attempt opening a url starting with HTTP:// as opposed to http:// - it is case sensitive. In 4.3.1 anyway..."HTTP://", by not matching "http://" will tell the wrapper to look locally. From the looks of the source, the same goes for HTTPS vs https, etc.
simon at gornall dot net
19-Jun-2003 05:24
If you're having problems with fopen("url...") but you can run 'host url' in a shell window and get the correct lookup, here's why...
This has had me banging my head against it all day - finally I found the answer buried in the bug reports, but figured it should really be more prominent!
The problem happens when you're on an ADSL line with DHCP (like our office)... When the ADSL modem renews the DHCP lease, you can also switch DNS servers, which confuses apache (and hence PHP) - meaning that you can't look up hosts from within PHP, even though you *can* from the commandline.... The short-term solution is to restart apache.
You'll get "php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution in ..." messages as symptoms. Restart apache, and they're gone :-)
Simon
RobNar
17-Jun-2003 01:15
This is an addendum to ibetyouare at home dot com's note about Apache directory permissions. If you are on a shared host and cannot tweak Apache's permissions directives then you might try setting the same thing in a .htaccess file. Failing that, if you are having trouble just creating files then set the directory permissions to allow writing (for whatever directory the file is supposed to be in) and include the following before fopen():
`touch /path/to/myfile/myfile.txt`;
That will usually create a new empty file that you can write to even when fopen fails. - PHP 4.3.0
09-Jun-2003 08:50
If you have problems with safe mode creating errors
"Warning: SAFE MODE Restriction in effect. The script whose uid is.."
because one of your PHP scripts created the PHP file you are now trying to run, then you can use fopen() to create these files which will then be owned by you (not the server admin).
It must be done using the ftp method...
>> fopen('ftp://user:pass@domain.com', 'w+b');
But please remember that this only creates files, I havent found a way around setting the correct UID on folders (yet)
Krang
- http://www.krang.org.uk
Jhilton a at t nurv dot us
05-Jun-2003 05:54
Quick tip. If using fopen to make http requests that contain a querystring, it is advised that you urlencode() your values, else characters like @ can make fopen (or whatever wrapper it is using) throw an error.
Tim Fountain
30-Apr-2003 09:43
There seems to be an upper limit on the size of file that can be opened - when trying to open a ridiculously large file (~2.5gig) I got a 'file to large' error, and fopen returned false. This doesn't seem to be documented anywhere and there's no obvious way to change the limit. Obviously opening very large files isn't something you want to do very often but it's worth keeping in mind.
04-Mar-2003 01:49
To overwrite a file with a new content without deleting it, and without changing the owner or access rights, it's best to not use:
$file = fopen($filename, 'r+b); // binary update mode
...
ftruncate($file, 0);
fwrite($file, $my_stuff);
...
fclose($file);
but instead the faster one:
$file = fopen($filename, 'r+b); // binary update mode
...
rewind($file);
fwrite($file, $my_stuff);
fflush($file);
ftruncate($file, ftell($file));
...
fclose($file);
The reason is that truncating a file at size 0 forces the OS to deallocate all storage clusters used by the file, before you write your content which will be reallocated on disk.
The second code simply overwrites the existing content where it is already located on disk, and truncates any remaining bytes that may exist (if the new content is shorter than the old content). The "r+b" mode allows access for both read and write: the file can be kept opened after reading it and before rewriting the modified content.
It's particularly useful for files that are accessed often or have a size larger than a few kilobytes, as it saves lots of system I/O, and also limits the filesystem fragmentation if the updated file is quite large.
And this method also works if the file is locked exclusively once opened (but I would rather recommend using another empty file for locking purpose, opened with "a+" access mode, in "/var/lock/yourapp/*" or other fast filesystems where filelocks are easily monitored and where the webserver running PHP is allowed to create and update lock files, and not forgetting to close the lock file after closing the content file).
draconumpb at hotmail dot com
06-Dec-2002 08:37
I just used explode() as an alternative to fscanf, since my only delimiter was | (pipe). I was having problems with it, since I use it in my news-management script. I found that it cut the last variable I was using, $body, a bit short when I posted a long news post. This would've been a real problem for anybody trying to make news posts longer than a paragraph or so.
However, I found that when I used:
list($variable1, $variable2, etc) = explode("|",$data);
it didn't cut any variables short, so.. what I'm really trying to say here is that for people who are experiencing problems with parsing simple files (i.e with only a single, simple delimiter such as : or |) using the unecessarily complex fscanf() and sscanf() functions, explode() is definately the way to go.
function get_news($filepath, $newsid)
{
$datafile = fopen("$filepath/news/$newsid.txt","r");
$data = fread($datafile, 1000000);
list($author, $email, $date, $subject, $body) = explode("|",$data);
$body = stripslashes("$body");
$subject = stripslashes("$subject");
echo "<a href=/old?u=http%3A%2F%2Fuk.php.net%2Fmanual%2Fpl%2F%5C&y=1999"mailto:$email\">$author</a> -- $date -- $subject<hr>$body<p>";
}
sample file:
AdministratorMax|admin@somesite.com|Tuesday, March 5th @ 5:45 PM EST|Site Going Down Tomarrow|Well, folks, I\'m sorry to say that the site will indeed be down tomarrow for most of the day. Hang in there.
Output:
<a href="mailto:admin@somesite.com">AdministratorMax</a> -- Tuesday, March 5th -- Site Going Down Tomarrow<hr>Well, folks, I'm sorry to say that the site will indeed be down tomarrow for most of the day. Hang in there.
Thought that might be useful for anybody making a simple news-management script, ;)
By the way, feel free to correct me if I made any mistakes - I'm at my dad's work where I don't really have a way to check to see if it works or not. However, I use a more complex version of this on my portal project, and it works beautifully.
Jester at free2code dot net
28-Nov-2002 02:13
joe at joestump dot net
11-Nov-2002 08:36
fopen() reads headers. This means that 404's do not end up as valid fp's - instead it fails gracefully.
chirchik at r66 dot ru
16-Oct-2002 06: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<br>\n";
}else{
echo "Error opening $newurl for writing<br>\n";
}
}else{
echo "Error opening $url<br>\n";
// print_r($img);
}
}
zman at inbox dot ru
02-Oct-2002 05: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);
?>
philihp at philihp dot com
26-Sep-2002 03: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."
ben at gelbnet dot com
25-Sep-2002 08: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
<?
$RETURN_CHAR = "\n";
$TIMEOUT = 5; $PID = getmypid();
$CHILD_PID = 0;
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);
}
function read_data() {
$in = fopen("php://stdin", "r");
set_timeout();
$in_string = fgets($in, 255);
clear_timeout();
fclose($in);
return $in_string;
}
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);
}
?>
andyNO at SPAMuchicago dot edu
30-Aug-2002 07: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.
suraj at _nospam_nospam_symonds dot net
17-Jul-2002 11: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)]
01-Jul-2002 02: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!
jared at dctkc dot com
22-Apr-2002 06:33
<?php
$serproxy=true;
if ($serproxy) {
$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) {
`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);
}
}
?>
15-Mar-2002 11: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");
landrews at email dot com
21-Feb-2002 03: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
mp3godNOSPAM at mail dot ru
30-Jan-2002 08: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;
}
slevy1 at pipeline.com
29-Dec-2001 11: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");
}
php at themastermind1 dot com
24-Oct-2001 03: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.
keithm at aoeex dot NOSPAM dot com
31-Jul-2001 10: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);
?>
ibetyouare at home dot com
26-Jul-2001 06: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.
mnirwan at microshell dot com
21-Feb-2001 09:31
defdac at hotmail dot com
22-Jan-2001 06: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');
paul_tanner at alum dot mit dot edu
08-Dec-2000 08: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 '||'
icon at mricon dot com
09-Nov-1999 07: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.
| |