|
użytkowników online: 57
|
OPINIE UŻYTKOWNIKÓW
|
W takich dniach, jak ten, nie żałuję, że wykupiłem abonament. Korzystam z porad na tych stronach nawet kilkanaście razy w tygodniu i dzięki nim prace nad stronami dla klientów idą mi o wiele szybciej, a strony wyglądają bardziej profesjonalnie. Nie wiem, jak mogłem wcześniej pracować bez dostępu do porad w tym serwisie!
Wojciech Miszkiewicz
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
fopen (PHP 3, PHP 4, PHP 5) fopen -- Otwiera plik lub URL Opisresource fopen ( string nazwa_pliku, string tryb [, bool użyj_include_path [, resource zkontekst]] )
fopen() wiąże nazwany zasób, określony przez
przez nazwa_pliku do strumienia. Jeśli
nazwa_pliku jest w formacie "schemat://...",
PHP przyjmuje, że to jest URL i rozpoczyna poszukiwanie programu
obsługi protokołu (róznież zwanego wrapperem) dla tego schematu.
Jeśli nie ma zarejestrowanego wrappera dla tego protokołu, PHP
wyświetli wiadomość aby pomóc Tobie namierzyć potencjalne
problemy w Twoim skrypcie i będzie kontynuować pracę, traktując
podany nazwa_pliku jako zwykły plik.
Jeśli PHP zdecyduje, że nazwa_pliku określa
lokalny plik, wtedy spróbuje otworzyć strumień na tym pliku.
Plik musi być dostępny dla PHP, więc musisz zapewnić prawa
dostępu do pliku pozwalające na taką operację.
Jeśli masz włączone tryb bezpieczny lub open_basedir
mogą mieć zastosowanie dodatkowe restrykcje.
Jeśli PHP zdecyduje, że nazwa_pliku określa
zarejestrowany protokół i ten protokół jest zarejestowany jako
sieciowy URL, PHP sprawdzi allow_url_fopen
czy jest włączone. Jeśli jest wyłączone (off), PHP wyświetli ostrzeżenie
i wywołanie fopen zakończy się niepowodzeniem.
Notatka:
Listę obsługiwanych protokołów możesz znaleźć w Dodatek L.
Niektóre protokoły (również określane przez wrappery obsługują
kontekst lub/i opcje php.ini.
Odwołaj się do konkretnej strony protokołu aby uzyskać listę opcji jakie
mogą zostać ustawione (np. php.ini wartość
user_agent używana przez wrapper http).
Notatka: Wsparcie dla kontekstów zostało
dodane w PHP 5.0.0.
Notatka:
Od PHP 4.3.2 domyślny tryb ustawiany jest na binarny, dla wszystkich
platform, które rozróżniają tryby binarne i tekstowe. Jeśli masz
problemy ze skryptem po aktualizacji, spróbuj użyć flagi 't'
jako obejście dopóki nie uczynisz Twojego skryptu bardziej przenośnym
jak opisano niżej.
Parametr tryb określa rodzaj dostępu jaki
wymagasz do strumienia. Może być dowolny z następujących:
Tabela 1.
Lista możliwych trybów dla fopen()
używając tryb
| tryb | Opis |
|---|
| 'r' |
Otwiera tylko do odczytu; umieszcza wskaźnik pliku na jego początku.
| | 'r+' |
Otwiera do odczytu i zapisu; umieszcza wskaźnik pliku na jego początku.
| | 'w' |
Otwiera tylko do zapisu; umieszcza wskaźnik pliku na jego początku
i obcina plik do zerowej długości. Jeśli plik nie istnieje to
próbuje go utworzyć.
| | 'w+' |
Otwiera do odczytu i zapisu; umieszcza wskaźnik pliku na jego początku
i obcina plik do zerowej długości. Jeśli plik nie istnieje to
próbuje go utworzyć.
| | 'a' |
Otwiera tylko do zapisu; umieszcza wskaźnik pliku na jego końcu.
Jeśli plik nie istnieje to próbuje go utworzyć.
| | 'a+' |
Otwiera do odczytu i zapisu; umieszcza wskaźnik pliku na jego końcu.
Jeśli plik nie istnieje to próbuje go utworzyć.
| | 'x' |
Tworzy i otwiera plik tylko do zapisu; umieszcza wskaźnik pliku na
jego początku. Jeśli plik juz istnieje, wywołanie fopen()
nie powiedzie się, zwróci FALSE i wygeneruje błąd na poziomie
E_WARNING. Jeśli plik nie istnieje, spróbuje go
utworzyć. To jest równoważne z określeniem flag O_EXCL|O_CREAT
stosowanym w wywołaniu systemowym open(2). Ta opcja
jest obsługiwana w PHP 4.3.2 i późniejszych i działa tylko na plikach
lokalnych.
| | 'x+' |
Tworzy i otwiera plik odczytu i zapisu; umieszcza wskaźnik pliku na
jego początku. Jeśli plik juz istnieje, wywołanie fopen()
nie powiedzie się, zwróci FALSE i wygeneruje błąd na poziomie
E_WARNING. Jeśli plik nie istnieje, spróbuje go
utworzyć. To jest równoważne z okresleniem flag O_EXCL|O_CREAT
stosowanym w wywołaniu systemowym open(2). Ta opcja
jest obsługiwana w PHP 4.3.2 i późniejszych i działa tylko na plikach
lokalnych.
|
Notatka:
Różne rodziny systemów operacyjnych stosuja rózne konwencje końca lini.
Kiedy zapisujesz plik tekstowy i chcesz wstawić łamanie lini, musisz
użyć poprawnych dla twojego systemu operacyjnego znak(ów) końca lini.
Systemy bazujące na Uniksie używają \n jako
znaku końca lini, systemy bazujące na Windowsie używają \r\n
jako znaków końca lini, a systemy Macintosh używają \r
jako znak końca lini.
Jeśli użyjesz nieprawidłowego końca lini do zapisu pliku, możesz
zaobserwować, w innych aplikacjach otwierając ten plik, że "wygląda on
zabawnie".
Windows oferuje flagę ('t') konwertującą tryb tekstowy,
która przezroczyście przekłada \n na
\r\n kiedy pracujesz z plikiem. Dla kontrastu, możesz
także uzyć 'b' aby wymusić tryb binarny, wtedy
nie będzie konwertować twoich danych. Aby użyć tych flag, wstaw
'b' lub 't' jako ostatni
znak w parametrze tryb.
Domyślnie tryb konwersji zależy od SAPI i wersji PHP jakiej używasz,
więc namawiamy aby zawsze podawać stosowną flage w celu przenośności.
Powinieneś użyć trybu 't' jeśli pracujesz ze
zwykłymi plikami tekstowymi (plain-text)i używasz \n
do ograniczenia konców lini w twoim skrypcie, ale wymagasz aby twój
plik był czytelny w aplikacjach takich jak notatnik. Powinieneś uzyć
'b' w każdym innym przypadku.
Jeśli nie podasz flagi 'b' kiedy pracujesz na binarnych plikach, możesz
doświadczyć dziwnych problemów z twoimi danymi, włączając uszkodzone pliki
graficzne i dziwne problemy ze znakami \r\n.
Notatka:
Dla przenośności, bardzo zalecane jest użycie zawsze flagi 'b'
kiedy otwierasz pliki za pomocą fopen().
Notatka:
Ponownie, dla przenośności, jest również bardzo zalecane abyś,
przepisał swój kod, który używa lub polega na trybie 't'
tak aby używał poprawnego końca lini oraz trybu 'b'.
Opcjonalny trzeci parametr użyj_include_path
może być ustawiony na '1' lub TRUE jeśli chcesz szukać pliku także w
include_path.
Jeśli otwieranie się nie powiedzie, funkcja zwróci FALSE i
wygenerowany zostanie błąd na poziomie E_WARNING.
Możesz użyć @ aby
zatuszować to ostrzeżenie.
Przykład 1. fopen() przykłady |
<?php
$handle = fopen("/home/rasmus/plik.txt", "r");
$handle = fopen("/home/rasmus/plik.gif", "wb");
$handle = fopen("http://www.przyklad.com/", "r");
$handle = fopen("ftp://uzytkownik:haslo@przyklad.com/jakisplik.txt", "w");
?>
|
|
Jeśli doświadczasz problemów z odczytem lub zapisywaniem do plików i
używasz PHP w postaci modułu serwera, pamiętaj, żeby się upewnić, że
pliki i katalogi, których używasz są dostępne dla procesu serwera.
Na platformie Windows, dbaj aby wstawiać znaki ucieczki (escape)
przed wszystkimi lewymi ukośnikami (backslash) użytymi w ścieżce do
pliku lub używać ukośników (slash).
| Ostrzeżenie | Łącząc się przez SSL, serwer
Microsoft IIS pogwałca reguły protokołu przez zamknięcie połączenia bez
wysłania znacznika close_notify. PHP zgłosi to jako "SSL: Fatal Protocol Error"
po przesłaniu całości danych. Aby obejść ten błąd, wystarczy obniżyć poziom
raportowania błędów (error_reporting) aby nie były
wyświetlane ostrzeżenia. PHP w wersji 4.3.7 i nowsze wykrywa obecność
zepsutego serwera IIS przy otwieraniu strumienia przez wrapper https:// i
wyłącza wyświetlanie tych ostrzeżeń. Używając funkcji
fsockopen() do otwarcia gniazda ssl:// należy samemu
zatroszczyć się o wyłączenie ostrzeżeń. |
Notatka: Kiedy włączony jest tryb bezpieczny, PHP sprawdza czy
katalog, na którym chcesz operować, ma takie same UID (owner) jak skrypt,
który jest aktualnie wykonywany.
Patrz także: Dodatek L,
fclose(),
fgets(),
fread(),
fwrite(),
fsockopen(),
file(),
file_exists(),
is_readable(),
stream_set_timeout() i
popen().
User Contributed NotesPaul Yanchenko
22-Jan-2006 02:16
I found a strange behaviour of PHP when several scripts trying to fopen a file for writing access simultaneously. I expect that this will result file sharing violation, but it's not and all scripts can open and write that file. I'd like to use sharing violation to control uniqueness of script instance, but now I even do know how to do this. The only idea is to use "x" flag in fopen(), but if that lock-file somehow will not be deleted - script will never run.
PHP 5.0.5, Windows XP Pro SP2
flobee
15-Jan-2006 04:58
download: i need a function to simulate a "wget url" and do not buffer the data in the memory to avoid thouse problems on large files:
<?php
function download($file_source, $file_target) {
$rh = fopen($file_source, 'rb');
$wh = fopen($file_target, 'wb');
if ($rh===false || $wh===false) {
return true;
}
while (!feof($rh)) {
if (fwrite($wh, fread($rh, 1024)) === FALSE) {
return true;
}
}
fclose($rh);
fclose($wh);
return false;
}
?>
anonymous at anonymous dot com
27-Dec-2005 12:11
Contrary to a note below the concept of what the preferred line ending is on mac os x is a little bit fuzzy. I'm pretty sure all the bsd utils installed by default are going to use \n but that is not necessarily the norm. Some apps will use that while others will use \r.
You should be prepared to deal with either.
Camillo
19-Dec-2005 06:58
Contrary to what this page says, the preferred line ending on Macintosh systems is \n (LF). \r was used on legacy versions of the Mac OS (pre-OS X), and I don't think PHP even runs on those.
151408626 dot unique at servux dot org
19-Dec-2005 01:05
I found a nice trick how to work around the issue (mentioned here: http://www.php.net/manual/en/function.fopen.php#41243) that the PHP process will block on opening a FIFO until data is sent to it:
Simply do send some data to the FIFO, using an echo command started in background (and ignoring that spedific data, when parsing whatever read from the FIFO).
A very simple example of that:
<?
$someFIFO = "path/to/your/fifo"
$uniqueData = "some specific data";
system("(echo -n '$uniqueData' >$someFIFO) >/dev/null &");
$handle = fopen($someFIFO, 'r');
while (TRUE) {
$data = fread($handle, 8192);
if (!(strpos($inp, $uniqueData) === FALSE)) $data = str_replace($uniqueData, '', $data);
}
?>
info at b1g dot de
24-Oct-2005 01:54
Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.
<?php
$r = new HTTPRequest('http://www.php.net');
echo $r->DownloadToString();
class HTTPRequest
{
var $_fp; var $_url; var $_host; var $_protocol; var $_uri; var $_port; function _scan_url()
{
$req = $this->_url;
$pos = strpos($req, '://');
$this->_protocol = strtolower(substr($req, 0, $pos));
$req = substr($req, $pos+3);
$pos = strpos($req, '/');
if($pos === false)
$pos = strlen($req);
$host = substr($req, 0, $pos);
if(strpos($host, ':') !== false)
{
list($this->_host, $this->_port) = explode(':', $host);
}
else
{
$this->_host = $host;
$this->_port = ($this->_protocol == 'https') ? 443 : 80;
}
$this->_uri = substr($req, $pos);
if($this->_uri == '')
$this->_uri = '/';
}
function HTTPRequest($url)
{
$this->_url = $url;
$this->_scan_url();
}
function DownloadToString()
{
$crlf = "\r\n";
$req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
. 'Host: ' . $this->_host . $crlf
. $crlf;
$this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);
fwrite($this->_fp, $req);
while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
$response .= fread($this->_fp, 1024);
fclose($this->_fp);
$pos = strpos($response, $crlf . $crlf);
if($pos === false)
return($response);
$header = substr($response, 0, $pos);
$body = substr($response, $pos + 2 * strlen($crlf));
$headers = array();
$lines = explode($crlf, $header);
foreach($lines as $line)
if(($pos = strpos($line, ':')) !== false)
$headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));
if(isset($headers['location']))
{
$http = new HTTPRequest($headers['location']);
return($http->DownloadToString($http));
}
else
{
return($body);
}
}
}
?>
admin at sellchain dot com
17-Oct-2005 04:34
TIP: If you are using fopen and fread to read HTTP or FTP or Remote Files, and experiencing some performance issues such as stalling, slowing down and otherwise, then it's time you learned a thing called cURL.
Performance Comparison:
10 per minute for fopen/fread for 100 HTTP files
2000 per minute for cURL for 2000 HTTP files
cURL should be used for opening HTTP and FTP files, it is EXTREMELY reliable, even when it comes to performance.
I noticed when using too many scripts at the same time to download the data from the site I was harvesting from, fopen and fread would go into deadlock. When using cURL i can open 50 windows, running 10 URL's from each window, and getting the best performance possible.
Just a Tip :)
nefertari at nefertari dot be
20-Sep-2005 02:47
Important note:
You have always to use the real path name for a file with the command fopen [for example: fopen($filename, 'w')], never use a symbolic link, it will not work (unable to open $filename).
francis dot fish at gmail dot com
10-Sep-2005 05:10
None of the examples on the page test to see if the file has been opened successfully. Fopen will return false if it failed. To quickly extend one of the examples in the manual:
$filename = "some.dat" ;
$dataFile = fopen( $filename, "r" ) ;
if ( $dataFile )
{
while (!feof($dataFile))
{
$buffer = fgets($dataFile, 4096);
echo $buffer;
}
fclose($dataFile);
}
else
{
die( "fopen failed for $filename" ) ;
}
Hope this is some use.
durwood at speakeasy dot NOSPAM dot net
07-Sep-2005 08:43
I couldn't for the life of me get a certain php script working when i moved my server to a new Fedora 4 installation. The problem was that fopen() was failing when trying to access a file as a URL through apache -- even though it worked fine when run from the shell and even though the file was readily readable from any browser. After trying to place blame on Apache, RedHat, and even my cat and dog, I finally ran across this bug report on Redhat's website:
https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=164700
Basically the problem was SELinux (which I knew nothing about) -- you have to run the following command in order for SELinux to allow php to open a web file:
/usr/sbin/setsebool httpd_can_network_connect=1
To make the change permanent, run it with the -P option:
/usr/sbin/setsebool -P httpd_can_network_connect=1
Hope this helps others out -- it sure took me a long time to track down the problem.
ericw at w3consultant dot net
02-Sep-2005 08:49
RE: using fopen to read an http doc
I beat my head against the wall trying to figure out why i couldn't fopen("http://www.mainserver.com/mySettings.php","r");
on just 1 webserver. It was working on all the other webservers, but on this one, it would just hang, then fail.
Finally i figured out the machine i was doing it on was unable to look up domain names!
If you are having this problem try an nslookup to the website you are having from the command line.
ie: nslookup www.yahoo.com
If that fails, the fopen will not work either.
I changed to an IP (temp solution) and it works like a charm.
-e
Luiz Miguel Axcar (lmaxcar at yahoo dot com dot br)
17-Aug-2005 10:11
If you are getting message "Warning: fopen(): URL file-access is disabled in the server configuration", you can use function below to get the content from a local or remote file.
Function uses CURL lib, follow the link to get help: http://www.php.net/curl
<?php
function get_content($url)
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
$content = get_content ("http://www.php.net");
var_dump ($content);
?>
zachajc at yahoo dot com (Zealot)
05-Aug-2005 10:35
When designing a few flatfile databases and admin panels, I stumbled upon an interesting thing. If a file has been generated into a page or variable via the readfile or include methods (did not try require), an ereg or preg replace to replace \n with <br> does not detect any \n in the file. However, when attempting the same thing with fopen, fread, it works perfectly.
ideacode
03-Aug-2005 04:28
Note that whether you may open directories is operating system dependent. The following lines:
<?php
$fh = fopen('c:\\Temp', 'r');
$fh = fopen('/tmp', 'r');
?>
demonstrate that on Windows (2000, probably XP) you may not open a directory (the error is "Permission Denied"), regardless of the security permissions on that directory.
On UNIX, you may happily read the directory format for the native filesystem.
rafaelbc at matrix dot com dot br
23-May-2005 06:23
pflaume dot NOSPAM at NOSPAM dot gmx dot de's proxy_url() was very helpful to me!
Although, I still had a problem: proxy authentication.
So I added some code to enable http get through a proxy with user authentication.
<?php
function proxy_url($proxy_url)
{
$proxy_name = '127.0.0.1';
$proxy_port = 4001;
$proxy_user = "user"; $proxy_pass = "password"; $proxy_cont = '';
$proxy_fp = fsockopen($proxy_name, $proxy_port);
if (!$proxy_fp) {return false;}
fputs($proxy_fp, "GET $proxy_url HTTP/1.0\r\nHost: $proxy_name\r\n");
fputs($proxy_fp, "Proxy-Authorization: Basic " . base64_encode ("$proxy_user:$proxy_pass") . "\r\n\r\n"); while(!feof($proxy_fp)) {$proxy_cont .= fread($proxy_fp,4096);}
fclose($proxy_fp);
$proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
return $proxy_cont;
}
?>
francois AT crevola DOT com
11-May-2005 01:54
In reply to "pflaume dot NOSPAM at NOSPAM dot gmx dot de"
about fopen() and PROXY
With PHP 5.0.0 and after, you can use a proxy by using a stream context. See the note about "Context support was added with PHP 5.0.0".
18-Apr-2005 05:41
This only relavant to those opening a remote file for writing using the PECL SSH2 for SFTP paths for the string filename. Since SFTP has variations, most of which are non-secure, using this module is the only viable solution. The optional FTP extension class that uses the function 'ftp_ssl_connect' uses openssl, which only encrypts the communication requests and not the data - or something close to that. At any rate, many systems will not allow connection to their SFTP server using this method.
I think it's worth mentioning that some of the examples provided in various areas failed consistantly using the syntax given, using both possible methods of.
ssh2.sftp://$sftp/example.com/path/to/file
ssh2.sftp://user:pass@$sftp/example.com/path/to/file
It's just a small adjustment to correct this, but as most coding goes, a long road to find a stupid little oversight. Apparently it is necessary to supply the port as well in the path. Could just be the few systems I was testing against, but that would be three separate networks using three separate platforms (Windows Server, Linux, Unix). At any rate, the following works like a charm, and was very simple to install the libssh2 library and PECL SSH2 module required to use this system. Gotta love PHP.
ssh2.sftp://$sftp/example.com:22/path/to/file
ssh2.sftp://user:pass@$sftp:22/example.com/path/to/file
Hope this saves anyone some headache and time.
abesharp at yahoo dot co dot uk
05-Apr-2005 01:12
This function has a basic implementation of HTTP Digest Authentication (as per RFC 2617) to get a file from a web server which requires digest authentication (as opposed to basic authentication - the difference being that, with basic, your password is sent to the server as plain text, whereas with digest, it is hashed with a server-supplied nonce to protect against sniffing and replay attacks).
You just supply the host (e.g www.example.com), the name of the file you want (e.g protected_page.html), and the necessary username and password, and the function returns the contents of the protected file (or the error message that the server sends, if you supplied the wrong credentials).
If the server only supports a QOP of auth-int (rather then auth) this function won't work, but can be easily modified with reference to the RFC at http://www.ietf.org/rfc/rfc2617.txt
<?php
function readHTTPDigestAuthenticatedFile($host,$file,$username,$password)
{
if (!$fp=fsockopen($host,80, $errno, $errstr, 15))
return false;
$out = "GET /$file HTTP/1.1\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp))
{
$line=fgets($fp, 512);
if (strpos($line,"WWW-Authenticate:")!==false)
$authline=trim(substr($line,18));
}
fclose($fp);
$authlinearr=explode(",",$authline);
$autharr=array();
foreach ($authlinearr as $el)
{
$elarr=explode("=",$el);
$autharr[trim($elarr[0])]=substr($elarr[1],1,strlen($elarr[1])-2);
}
foreach ($autharr as $k=>$v)
echo("$k ==> $v\r\n");
$nonce=$autharr['nonce'];
$opaque=$autharr['opaque'];
$drealm=$autharr['Digest realm'];
$cnonce="sausages";
$a1="$username:$drealm:$password";$a2="GET:/$file";
$ha1=md5($a1);$ha2=md5($a2);
$concat = $ha1.':'.$nonce.':00000001:'.$cnonce.':auth:'.$ha2;
$response=md5($concat);
$out = "GET /$file HTTP/1.1\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: cookie=MyCookie\r\n";
$out .= "Authorization: Digest username=\"$username\", realm=\"$drealm\", qop=\"auth\", algorithm=\"MD5\", uri=\"/$file\", nonce=\"$nonce\", nc=00000001, cnonce=\"$cnonce\", opaque=\"$opaque\", response=\"$response\"\r\n\r\n";
if (!$fp=fsockopen($host,80, $errno, $errstr, 15))
return false;
fwrite($fp, $out);
while (!feof($fp))
{
$str.=fgets($fp, 512);
}
fclose($fp);
return $str;
}
?>
nuno at ideianet dot pt
04-Mar-2005 02:03
In IIS you must add the group Authenticated Users
with write and modify permissions in the file where
you want to write if you are in a Protected directory
(Basic or Digest authentication) and want to write to
a file in a Unprotected directory (Anonymous Access)
in order to get permission to do that. Otherwise you
will get the message: PHP Warning: fopen(x.txt): failed
to open stream: Permission denied in c:\web\x\x.php on
line 3 PHP Warning: fwrite(): supplied argument is not
a valid stream resource in c:\web\x\x.php on line 10
nuno at ideianet dot pt
21-Feb-2005 06:37
In IIS you must add the user IUSR_yourservername
(Internet Guest Account) with write and modify
permissions in the file where you want to write
in order to get permission to do that. Otherwise
you will get the message: PHP Warning: fopen(x.txt):
failed to open stream: Permission denied in
c:\web\x\x.php on line 3 PHP Warning: fwrite():
supplied argument is not a valid stream resource
in c:\web\x\x.php on line 10
Thomas Candrian tc_ at gmx dot ch
12-Nov-2004 04:35
With this it isn't possible to get data from another port than 80 (and 443) - at least for me. Because of that I've made this function who gets data from every port you want using HTTP:
<?php;
function getcontent($server, $port, $file)
{
$cont = "";
$ip = gethostbyname($server);
$fp = fsockopen($ip, $port);
if (!$fp)
{
return "Unknown";
}
else
{
$com = "GET $file HTTP/1.1\r\nAccept: */*\r\nAccept-Language: de-ch\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\r\nHost: $server:$port\r\nConnection: Keep-Alive\r\n\r\n";
fputs($fp, $com);
while (!feof($fp))
{
$cont .= fread($fp, 500);
}
fclose($fp);
$cont = substr($cont, strpos($cont, "\r\n\r\n") + 4);
return $cont;
}
}
echo getcontent("www.myhost.com", "81", "/"));
?>
Works fine for me. Had to do this especially for a shoutcast server, which only delivered the HTML-file if the user-agent was given.
pflaume dot NOSPAM at NOSPAM dot gmx dot de
07-Nov-2004 11:31
fopen() and PROXY
I wondered why there is no possibility to use fopen() through a proxy in php. The solution posted above did not work for me.
This little function gets http through a given proxy:
<?php
function proxy_url($proxy_url)
{
$proxy_name = '127.0.0.1';
$proxy_port = 4001;
$proxy_cont = '';
$proxy_fp = fsockopen($proxy_name, $proxy_port);
if (!$proxy_fp) {return false;}
fputs($proxy_fp, "GET $proxy_url HTTP/1.0\r\nHost: $proxy_name\r\n\r\n");
while(!feof($proxy_fp)) {$proxy_cont .= fread($proxy_fp,4096);}
fclose($proxy_fp);
$proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
return $proxy_cont;
}
?>
justin at redwiredesign dot com
14-Jul-2004 09:03
One thing worth noting is that if you use the fopen command to open an HTTP stream, and the URL you're trying to access is invalid or generates an error response, (i.e. 404 Not found), the fopen call will return false.
Jem Tallon
14-Apr-2004 12:11
If you're using fopen to open a URL that requires authorization, you might need to force a HTTP/1.0 request for it since fopen won't support HTTP/1.1 requests. You can do that by setting your user_agent to one that is known only to support HTTP/1.0 (most webservers will be configured to force HTTP/1.0 for some browsers). Here's what worked for me:
<?php
$returned=URLopen("http://$username:$password@example.com");
function URLopen($url)
{
ini_set('user_agent','MSIE 4\.0b2;');
$dh = fopen("$url",'r');
$result = fread($dh,8192);
return $result;
}
?>
php at gotdoof dot com
04-Apr-2004 06:19
Note that opening a fifo with fopen() will block the php process until data is sent to it. That means any function you have registered as a shutdown function (register_shutdown_function()) will not be called when the user disconnects, and the process will keep running in the background, waiting for input. I know of no way around this, besides using some other means of IPC.
richard dot quadling at carval dot co dot uk
04-Feb-2004 02:04
The issue involving some sites requiring a valid user-agent string when using fopen can easily be resolved by setting the user_agent string in the PHP.INI file.
If you do not have access to the PHP.INI file, then the use of
ini_set('user_agent','Mozilla: (compatible; Windows XP)');
should also work.
The actual agent string is up to you. If you want to identify to the sites that you are using PHP ...
ini_set('user_agent','PHP');
would do.
Regards,
Richard Quadling.
29-Jan-2004 08:34
If you are connecting to your ftp server through a router doing NAT (such as the Zyxel 128L prestige router/bridge we are using) by doing say an <? fopen("ftp://ftpusername:ftppassword@ftpserver/".$file_name, "w") ?>, then this could fail. You will get php_hostconnect connection failed error. This is because <?fopen() ?>function uses a passive ftp connection which the Zyxel router does not support, even though your ftp server may be configured to allow the passive connections which php <?fopen?> function is using. Note that $file_name is the file we want to ftp to the remote server eg could be file.txt.
Thus an alternative would be to do create the file you want in a local directory of your machine or in the webserver where your php files reside eg use <?fwrite()?> as documented in the manual. Once you have the $file_name you want to ftp created, do the following:
<?
ftp_connect($ftp_server);
ftp_login ($conn_id, $ftp_username."@".$ftp_server, $ftp_password);
$fp = fopen($PATH."".$file_name, 'r');
ftp_pasv ($conn_id, false);
ftp_fput($conn_id, $file_name, $fp, FTP_ASCII));
?>
Your file should now be in your ftp server, having used an active connection.
sergiopaternoster at tiscali dot it
27-Nov-2003 02: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
26-Nov-2003 12: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 08: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";
?>
phpNO at SPAMperfectweb dot com
31-Jul-2003 10: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
02-Jul-2003 01: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 09: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 05: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 12: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 haven
|