Note - using fopen in 'w' mode will NOT update the modification time (filemtime) of a file like you may expect. You may want to issue a touch() after writing and closing the file which update its modification time. This may become critical in a caching situation, if you intend to keep your hair.fopen
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
fopen
Референца за `function.fopen.php` со подобрена типографија и навигација.
fopen
(PHP 4, PHP 5, PHP 7, PHP 8)
fopen — Отвора датотека или URL
= NULL
string
$filename,string
$mode,bool
$use_include_path = false,?resource
$context = null): resource|false
fopen() врзува именуван ресурс, специфициран од
filename, на стрим.
Параметри
filename-
Враќа
filenameis of the form "scheme://...", it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as thoughfilenameспецифицира обична датотека.Ако PHP одлучил дека
filenameспецифицира локална датотека, тогаш ќе се обиде да отвори стрим на таа датотека. Датотеката мора да биде достапна за PHP, така што треба да се уверите дека дозволите за пристап до датотеката го дозволуваат овој пристап. Ако сте овозможиле open_basedir може да важат дополнителни ограничувања.Ако PHP одлучил дека
filenameспецифицира регистриран протокол, и тој протокол е регистриран како мрежен URL, PHP ќе провери за да се увери дека allow_url_fopen е овозможено. Ако е исклучено, PHP ќе емитува предупредување и fopen() ќе пропадне.Забелешка:
Списокот на поддржани протоколи може да се најде во Поддржани протоколи и обвивки. Некои протоколи (исто така наречени
wrappers) поддржуваатcontextand/or php.ini опции. Погледнете ја специфичната страница за протоколот што се користи за список на опции што можат да се постават. (на пр. php.ini valueuser_agentсе користи одhttpобвивач).На платформата Windows, внимавајте да ги избегнете сите коси црти што се користат во патеката до датотеката, или користете напредни коси црти.
<?php
$handle = fopen("c:\\folder\\resource.txt", "r");
?> mode-
На
modeпараметарот специфицира тип на пристап што ви е потребен до стримот. Може да биде било кој од следниве:Список на можни режими за fopen() using modemode= NULL 'r'Отвори само за читање; поставете го покажувачот на датотеката на почетокот на датотеката. 'r+'Отвори за читање и пишување; поставете го покажувачот на датотеката на почетокот на датотеката. 'w'Отворено само за пишување; покажувачот на датотеката се поставува на почетокот на датотеката и датотеката се скратува на нула должина. Ако датотеката не постои, се обидува да се создаде. 'w+'Отворено само за пишување; поставете го покажувачот на датотеката на почетокот на датотеката и скратете ја датотеката на нула должина. Ако датотеката не постои, обидете се да ја креирате. 'w'.'a'Отворено за читање и пишување; инаку има исто однесување како fseek() Отворено само за пишување; поставете го покажувачот на датотеката на крајот на датотеката. Ако датотеката не постои, обидете се да ја креирате. Во овој режим, 'a+'нема ефект, запишувањата секогаш се додаваат. fseek() Отворено за читање и пишување; поставете го покажувачот на датотеката на крајот на датотеката. Ако датотеката не постои, обидете се да ја креирате. Во овој режим, 'x'влијае само на положбата за читање, запишувањата секогаш се додаваат. fopen() Креирај и отвори само за пишување; поставете го покажувачот на датотеката на почетокот на датотеката. Ако датотеката веќе постои, повикот falseќе пропадне со враќањеE_WARNINGи генерирање грешка од нивоO_EXCL|O_CREAT. Ако датотеката не постои, обидете се да ја креирате. Ова е еквивалентно на специфицирањеopen(2)знаменца за основен'x+'системски повик. 'x'.'c'Креирај и отвори за читање и пишување; инаку има исто однесување како 'w'Отворете ја датотеката само за пишување. Ако датотеката не постои, таа се креира. Ако постои, таа ниту се скратува (за разлика од'x'), ниту повикот до оваа функција пропаѓа (како што е случајот со flock()). По покажувачот на датотеката се поставува на почетокот на датотеката. Ова може да биде корисно ако сакате да добиете советодавно заклучување (види'w') пред да се обидете да ја измените датотеката, бидејќи користењето на ftruncate() може да ја скрати датотеката пред да се добие заклучувањето (ако се сака скратување,'c+'може да се користи по барањето на заклучувањето). 'c'.'e'Постави го знаменцето close-on-exec на отворениот дескриптор на датотеката. Достапно само во PHP компајлиран на системи што се усогласуваат со POSIX.1-2008. 'n'Поставете знаме close-on-exec на отворениот дескриптор на датотеката. Достапно само во PHP компајлиран на системи што се усогласуваат со POSIX.1-2008. Забелешка:
Поставете знаме non-blocking на отворениот дескриптор на датотеката. Достапно само во PHP компајлиран на системи што се усогласуваат со POSIX.1-2008.
\nРазличните семејства на оперативни системи имаат различни конвенции за завршување на редовите. Кога пишувате текстуална датотека и сакате да вметнете прекин на редот, треба да го користите правилниот(ите) знак(ови) за завршување на редот за вашиот оперативен систем. Системите базирани на Unix користат\r\nкако знак за завршување на редот, системите базирани на Windows користат\rкако знаци за завршување на редот и системите базирани на Macintosh (Mac OS Classic) користеакако знак за завршување на редот.
Ако користите погрешни знаци за завршување на редовите при пишување на вашите датотеки, може да откриете дека другите апликации што ги отвораат тие датотеки ќе „изгледаат чудно“.
't'Windows нуди знаме за превод во текстуален режим (\nto\r\n) што транспарентно ќе преведува'b'при работа со датотеката. Спротивно на тоа, можете да користите и'b'or't'за форсирање на бинарен режим, што нема да ги преведе вашите податоци. За да ги користите овие знамиња, наведете илиmodeparameter.како последен знак од
'b'Стандардниот режим на превод е't'. Можете да го користите\nрежим ако работите со обични текстуални датотеки и користите'b'за разграничување на завршувањето на редовите во вашиот скрипт, но очекувајте вашите датотеки да бидат читливи со апликации како што се старите верзии на notepad. Треба да го користитево сите други случаи.
\r\ncharacters.Забелешка:
Ако го наведете знамето 't' при работа со бинарни датотеки, може да искусите чудни проблеми со вашите податоци, вклучувајќи скршени датотеки со слики и чудни проблеми со
't'За преносливост, исто така е силно препорачливо да го препишете кодот што користи или се потпира на'b'mode наместо тоа.Забелешка: На
modeрежим наместо. php://output, php://input, php://stdin, php://stdout, php://stderr and php://fd се игнорира за use_include_path-
stream wrappers.
use_include_pathИзборниот третtrueпараметар може да се постави на include_pathако сакате да ја пребарувате датотеката во context
Вратени вредности
, исто така. false Враќа ресурс од покажувач на датотека при успех, или
Errors/Exceptions
Бидејќи типот на податоци integer во PHP е со знакот и многу платформи користат 32-битни integers, некои функции за датотечниот систем може да вратат неочекувани резултати за датотеки поголеми од 2GB. E_WARNING се емитува.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 7.0.16, 7.1.2 |
На 'e' опцијата беше додадена.
|
Примери
Пример #1 fopen() examples
<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:[email protected]/somefile.txt", "w");
?>Белешки
при неуспех
close_notify При користење на SSL, Microsoft IIS ќе го прекрши протоколот со затворање на врската без испраќање на error_reporting индикатор. PHP ќе го пријави ова како "SSL: Fatal Protocol Error" кога ќе стигнете до крајот на податоците. За да го заобиколите ова, вредноста на https:// треба да се намали на ниво што не вклучува предупредувања. PHP може да открие буги IIS сервер софтвер кога ќе го отворите stream користејќи го fsockopen() wrapper и ќе го потисне предупредувањето. При користење на
ssl:// за креирање на
Забелешка:
socket, развивачот е одговорен за откривање и потиснување на ова предупредување.
Забелешка:
Ако имате проблеми со читање и пишување на датотеки и користите сервер модул верзија на PHP, запомнете да се уверите дека датотеките и директориумите што ги користите се достапни за серверскиот процес.
filenameОваа функција може исто така да успее когаfilenameе директориум. Ако не сте сигурни дали is_dir() е датотека или директориум, можеби ќе треба да ја користите fopen().
Види Исто така
- Поддржани протоколи и обвивки
- fclose() Пример #2 Користење на UDP серверски приклучници
- fgets() - Затвора отворена датотека
- fread() - Зема ред од датотека
- fwrite() - Бинарно читање од датотека
- fsockopen() - Бинарно запишување во датотека
- file() - Отвора интернет или Unix доменска конекција
- file_exists() - Чита цела датотека во низа
- is_readable() - Проверува дали постои датотека или директориум
- stream_set_timeout() - Проверува дали датотеката постои и може да се чита
- popen() - Поставува период на чекање на поток
- stream_context_create() - Отвора датотека на процес
- umask() - Го менува тековниот umask
- SplFileObject
Белешки од корисници — Трансформирај во XML
/***** GENTLE REMINDER *****/
Really important. Do NOT use the "w" flag unless you want to delete everything in the file.Note that for fopen() to create files when called with such mode, the path you have given needs to exist as fopen() cannot create directories; but only files it can create. This is normal behavior.
<?php
// Write log file, create if not exists
$log = fopen('/var/logs/someapp/error.log', 'wb');
// This will silently fail if /var/logs/someapp directory doesn't exist
?>The verbal descriptions take a while to read through to get a feel for the expected results for fopen modes. This csv table can help break it down for quicker understanding to find which mode you are looking for:
Mode,Creates,Reads,Writes,Pointer Starts,Truncates File,Notes,Purpose
r,,y,,beginning,,fails if file doesn't exist,basic read existing file
r+,,y,y,beginning,,fails if file doesn't exist,basic r/w existing file
w,y,,y,beginning+end,y,,"create, erase, write file"
w+,y,y,y,beginning+end,y,,"create, erase, write file with read option"
a,y,,y,end,,,"write from end of file, create if needed"
a+,y,y,y,end,,,"write from end of file, create if needed, with read options"
x,y,,y,beginning,,fails if file exists,"like w, but prevents over-writing an existing file"
x+,y,y,y,beginning,,fails if file exists,"like w+, but prevents over writing an existing file"
c,y,,y,beginning,,,open/create a file for writing without deleting current content
c+,y,y,y,beginning,,,"open/create a file that is read, and then written back down"With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with fopen() or readfile() requires an extra forwardslash if an absolute path is needed.
i.e., if a file called bullbes.txt is stored under /var/school/ on ftp server example.com and you're trying to access it with user blossom and password buttercup, the url would be:
ftp://blossom:[email protected]//var/school/bubbles.txt
Note the two forwardslashes. It looks like the second one is needed so the server won't interpret the path as relative to blossom's home on townsville.There is an undocumented mode for making fopen non-blocking (not working on windows). By adding 'n' to the mode parameter, fopen will not block, however if the pipe does not exist an error will be raised.
$fp = fopen("/tmp/debug", "a"); //blocks if pipe does not exist
$fp = fopen("/tmp/debug", "an"); //raises error on pipe not existNote that whether you may open directories is operating system dependent. The following lines:
<?php
// Windows ($fh === false)
$fh = fopen('c:\\Temp', 'r');
// UNIX (is_resource($fh) === true)
$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.fopen() will block if the file to be opened is a fifo. This is true whether it's opened in "r" or "w" mode. (See man 7 fifo: this is the correct, default behaviour; although Linux supports non-blocking fopen() of a fifo, PHP doesn't).
The consequence of this is that you can't discover whether an initial fifo read/write would block because to do that you need stream_select(), which in turn requires that fopen() has happened!<?php
#going to update last users counter script since
#aborting a write because a file is locked is not correct.
$counter_file = '/tmp/counter.txt';
clearstatcache();
ignore_user_abort(true); ## prevent refresh from aborting file operations and hosing file
if (file_exists($counter_file)) {
$fh = fopen($counter_file, 'r+');
while(1) {
if (flock($fh, LOCK_EX)) {
#$buffer = chop(fgets($fh, 2));
$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";
?>While opening a file with multibyte data (Ex: données multi-octets), faced some issues with the encoding. Got to know that it uses windows-1250. Used iconv to convert it to UTF-8 and it resolved the issue.
<?php
function utf8_fopen_read($fileName) {
$fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName));
$handle=fopen("php://memory", "rw");
fwrite($handle, $fc);
fseek($handle, 0);
return $handle;
}
?>
Example usage:
<?php
$fh = utf8_fopen_read("./tpKpiBundle.csv");
while (($data = fgetcsv($fh, 1000, ",")) !== false) {
foreach ($data as $value) {
echo $value . "<br />\n";
}
}
?>
Hope it helps.This functions check recursive permissions and recursive existence parent folders, before creating a folder. To avoid the generation of errors/warnings.
/**
* This functions check recursive permissions and recursive existence parent folders,
* before creating a folder. To avoid the generation of errors/warnings.
*
* @return bool
* true folder has been created or exist and writable.
* False folder not exist and cannot be created.
*/
function createWritableFolder($folder)
{
if (file_exists($folder)) {
// Folder exist.
return is_writable($folder);
}
// Folder not exit, check parent folder.
$folderParent = dirname($folder);
if($folderParent != '.' && $folderParent != '/' ) {
if(!createWritableFolder(dirname($folder))) {
// Failed to create folder parent.
return false;
}
// Folder parent created.
}
if ( is_writable($folderParent) ) {
// Folder parent is writable.
if ( mkdir($folder, 0777, true) ) {
// Folder created.
return true;
}
// Failed to create folder.
}
// Folder parent is not writable.
return false;
}
/**
* This functions check recursive permissions and recursive existence parent folders,
* before creating a file/folder. To avoid the generation of errors/warnings.
*
* @return bool
* true has been created or file exist and writable.
* False file not exist and cannot be created.
*/
function createWritableFile($file)
{
// Check if conf file exist.
if (file_exists($file)) {
// check if conf file is writable.
return is_writable($file);
}
// Check if conf folder exist and try to create conf file.
if(createWritableFolder(dirname($file)) && ($handle = fopen($file, 'a'))) {
fclose($handle);
return true; // File conf created.
}
// Inaccessible conf file.
return false;
}i had to do such function to display newest log entries on top to be displayed in browser
its easy to adjust it from anonymous to normal function and/or add content on end
most important is same log can be used by many threads/processes (Swoole, ReactPHP, php_fpm)
also it had to keep reasonable size to load fast
$prependFileThreadSafe = static function (string $file, string $content, int $maxLen = 1024*500): void {
$f = fopen($file, 'c+');
flock($f, LOCK_EX);
$prev = fread($f, $maxLen-strlen($content));
fseek($f, 0);
fwrite($f, $content . $prev);
flock($f, LOCK_UN);
fclose($f);
};
usage:
$prependFileThreadSafe('my.log', "some content\n");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.Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.
<?php
#usage:
$r = new HTTPRequest('http://www.example.com');
echo $r->DownloadToString();
class HTTPRequest
{
var $_fp; // HTTP socket
var $_url; // full URL
var $_host; // HTTP host
var $_protocol; // protocol (HTTP/HTTPS)
var $_uri; // request URI
var $_port; // port
// scan url
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 = '/';
}
// constructor
function HTTPRequest($url)
{
$this->_url = $url;
$this->_scan_url();
}
// download URL to string
function DownloadToString()
{
$crlf = "\r\n";
// generate request
$req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
. 'Host: ' . $this->_host . $crlf
. $crlf;
// fetch
$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);
// split header and body
$pos = strpos($response, $crlf . $crlf);
if($pos === false)
return($response);
$header = substr($response, 0, $pos);
$body = substr($response, $pos + 2 * strlen($crlf));
// parse headers
$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));
// redirection?
if(isset($headers['location']))
{
$http = new HTTPRequest($headers['location']);
return($http->DownloadToString($http));
}
else
{
return($body);
}
}
}
?>a variable $http_response_header is available when doing the fopen(). Which contains an array of the response header.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:
<?php
$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.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);
?>"Do not use the following reserved device names for the name of a file:
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1,
LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names
followed immediately by an extension; for example, NUL.txt is not recommended.
For more information, see Namespaces"
it is a windows limitation.
see:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspxdownload: 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) {
// error reading or opening file
return true;
}
while (!feof($rh)) {
if (fwrite($wh, fread($rh, 1024)) === FALSE) {
// 'Download error: Cannot write to file ('.$file_target.')';
return true;
}
}
fclose($rh);
fclose($wh);
// No error
return false;
}
?>If you need fopen() on a URL to timeout, you can do like:
<?php
$timeout = 3;
$old = ini_set('default_socket_timeout', $timeout);
$file = fopen('http://example.com', 'r');
ini_set('default_socket_timeout', $old);
stream_set_timeout($file, $timeout);
stream_set_blocking($file, 0);
//the rest is standard
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
// generiereHostliste.php
function generiereHostliste($file) {
// aus Rechnerliste.csv lesen
$fp = fopen($file, "r");
while($row = fgetcsv($fp, 0, ";")) {
$liste[]=[$row[0].";10.16.".$row[1].".".$row[2]];
}
fclose($fp);
// in Hostliste.csv schreiben
$fp = fopen("Hostliste.csv", "w");
foreach($liste as $row) {
echo "<pre>";
print_r($row);
echo "</pre>";
fputcsv($fp, $row, ";");
}
fclose($fp);
}
// Test
$file = "Rechnerliste.csv";
generiereHostliste($file);
?>
</body>
</html>Please note that you cannot write to a HTTP resource, for example for doing a PUT request.
You will get this error: 'Failed to open stream: HTTP wrapper does not support writeable connections'
To do a PUT you can only populate the 'content' key of the HTTP context, or use Curl instead.Opening a file in "r+" mode, and then trying to set the file pointer position with ftruncate before reading the file will result in file data loss, as though you opened the file in "w" mode.
EX:
$File = fopen($FilePath,"r+"); // OPEN FILE IN READ-WRITE
ftruncate($File, 0); // SET POINTER POSITION (Will Erase Data)
while(! feof($File)) { // CONTINUE UNTIL END OF FILE IS REACHED
$Line = fgets($File); // GET A LINE FROM THE FILE INTO STRING
$Line = trim($Line); // TRIM STRING OF NEW LINE
}
ftruncate($File,0); // (Will Not Erase Data)
fclose($File);