PHP 8.3.4 Released!

fopen

(PHP 4, PHP 5, PHP 7, PHP 8)

fopenBir dosya veya URL'yi açar

Açıklama

fopen(
    string $dosyaismi,
    string $kip,
    bool $include_path_kullan = false,
    ?resource $bağlam = null
): resource|false

fopen() işlevi dosyaismi ile belirtilen özkaynak için bir akım açar.

Bağımsız Değişkenler

dosyaismi

Eğer dosyaismi "şema://...", biçeminde belirtilmişse bir URL belirtildiği varsayılır ve PHP bu şema için bir protokol eylemcisi (başka bir deyişle bir sarmalayıcı) bulmaya çalışır. Eğer bu protokol için kayıtlı bir sarmalayıcı yoksa PHP, sorunun giderilmesine yardımcı olmanız için bir uyarı verip belirtilen dosya ismini sıradan bir dosya gibi ele alarak işleme devam eder.

Eğer PHP dosyaismi ile belirtilen dosyanın bir yerel dosya olduğuna karar verirse bu dosya üzerinde bir akım açmaya çalışır. Dosya PHP için erişilebilir olmalıdır, yani dosyanın bu erişim için yeterli izinlere sahip olduğundan emin olmanız gerekir. open_basedir yönergesi etkinse bunlarla ilgili kısıtlamalar uygulanabilir.

Eğer PHP dosyaismi ile belirtilen dosyanın bir URL olduğuna ve bununla ilgili kayıtlı bir protokol olduğuna karar verirse ve bu protokol bir ağ protokolü olarak kaydedilmişse PHP allow_url_fopen yönergesinin etkin olup olmadığına bakar. Eğer yönergeye 'Off' değeri atanmışsa PHP bir uyarı verip işlevin başarısız olmasını sağlar.

Bilginize:

Desteklenen protokolleri Desteklenen Protokoller ve Sarmalayıcılar bölümünde bulabilirsiniz. Bazı protokoller (sarmalayıcılar) bağlam ve/veya php.ini seçeneklerini destekler. Kullanılabilecek seçeneklerin neler olduğunu öğrenmek için protokolle ilgili sayfaya bakınız (örneğin, http sarmalayıcısı user_agent php.ini yönergesini kullanır).

Windows platformunda dosya yolunu belirtmekte kullanılan tersbölü çizgilerini öncelemeyi unutmayın. Daha da iyisi dosya yolunu belirtmek için bölü çizgilerini kullanın. Örnek:

<?php
$dt
= fopen("c:\\dizin\\kaynak.txt", "r");
?>

kip

kip bağımsız değişkeninde akım için gerekli erişim türü belirtilir. Şunlardan biri olabilir:

fopen() işlevinin kip bağımsız değişkeninde belirtilebilecek kip çeşitleri
Kip Açıklama
'r' Akım sadece okumak için açılır; dosya konumlayıcı dosyanın başlangıcına yerleştirilir.
'r+' Akım hem okumak hem de yazmak için açılır; dosya konumlayıcı dosyanın başlangıcına yerleştirilir.
'w' Akım sadece yazmak için açılır; dosya konumlayıcı dosyanın başlangıcına yerleştirilir ve dosya uzunluğu sıfır yapılır. Dosya mevcut değilse oluşturulmaya çalışılır.
'w+' Akım hem okumak hem de yazmak için açılması dışında 'w' gibidir.
'a' Akım sadece yazmak için açılır; dosya konumlayıcı dosyanın sonuna yerleştirilir. Dosya mevcut değilse oluşturulmaya çalışılır. fseek() işlevi bu kipte etkisiz olup daima dosyanın sonuna yazar.
'a+' Akım hem okumak hem de yazmak için açılır; dosya konumlayıcı dosyanın sonuna yerleştirilir. Dosya mevcut değilse oluşturulmaya çalışılır. fseek() işlevi bu kipte etkisiz olup daima dosyanın sonuna yazar.
'x' Dosya oluşturulur ve sadece yazmak için açılır; dosya konumlayıcı dosyanın başlangıcına yerleştirilir. Dosya zaten mevcutsa fopen() false döndürürek başarısız olur ve E_WARNING seviyesinde bir hata üretir. Dosya mevcut değilse oluşturulmaya çalışılır. Bu işlem, open(2) sistem çağrısı için O_EXCL|O_CREAT seçeneklerini belirtmeye eşdeğerdir.
'x+' Dosya oluşturulur ve hem okumak hem de yazmak için açılır; aksi takdirde 'x' verilmiş gibi davranır. eşdeğerdir.
'c' Dosya yalnızca yazmak için açılır. Dosya yoksa oluşturulur. Varsa, ne kesilir ('w' bağımsız değişkenininin aksine), ne de bu işleve yapılan çağrı başarısız olur ('x' durumunda olduğu gibi). Dosya konumlayıcı dosyanın başlangıcına yerleştirilir. Dosyayı değiştirmeye çalışmadan önce bir tavsiye kilidi (flock() bölümüne bakın) isteniyorsa bu yararlı olabilir, 'w' kullanımındaki gibi kilitlenmeden önce dosyayı kesebilir (kesme istenirse, kilit talep edildikten sonra ftruncate() kullanılabilir). requested).
'c+' Dosya hem okumak hem de yazmak için açılır; aksi takdirde, 'c' bağımsız değişkenindeki gibi davranır.
'e' Açık dosya konumlayıcıya close-on-exec bayrağını uygular. Sadece PHP, POSIX.1-2008 uyumlu sistemler üzerinde derlenmişse kullanılabilir.

Bilginize:

Her işletim sistemi ailesinin farklı satır sonlandırma kuralları vardır. Bir metin dosyasını yazarken işletim sisteminizin gerektirdiği satır sonlandırma karakterlerini kullanmanız gerekir. Unix ve türevleri satırları sonlandırmak için \n, Windows ailesi \r\n, Mac'ler ise (Mac OS Classic) \r karakterini kullanır.

Dosyalarınızı yazarken yanlış satır sonlandırma karakterleri kullanırsanız, dosyayı başka uygulamalarda açtığınızda tuhaf görünebilir.

Windows'un \n karakterlerini şeffaf olarak \r\n karakterlerine dönüştürmesini sağlayan bir metin kipi dönüşüm seçeneği ('t') vardır. Eğer satır sonlandırma karakterlerinin değişmeden kalmasını istiyorsanız ikil kipi devreye sokan 'b' seçeneğini kullanabilirsiniz. Bu seçenekleri ('b' veya 't') kip bağımsız değişkeninde daima son karakter olarak belirtin.

Öntanımlı dönüşüm kipi 'b''dir. Salt metin dosyalarla çalışıyorsanız ve betiğinizde satır sonu karakteri olarak \n kullanıyorsanız, fakat dosyalarınızın notepad'in eski sürümleri gibi uygulamalarla da okunabilmesini istiyorsanız 't' kipini kullanmanız, diğer tüm durumlarda ise 'b' kipini kullanmanız gerekir.

İkil dosyalarla çalışırken 't' seçeneğini belirseniz, verinizle ilgili tuhaf sorunlarla karşılaşabilirsiniz (örneğin, bozuk görüntü dosyaları ve \r\n karakterlerine bağlı tuhaf sorunlar).

Bilginize:

Uyumluluk adına, dosyanızı 't' seçeneğinin kullanılmasını gerektirmeyecek satır sonlandırma karakterleri ile yazmanızı ve dosyayı açarken daima 'b' seçeneğini kullanmanızı hararetle tavsiye ederiz.

Bilginize: php://output, php://input, php://stdin, php://stdout, php://stderr ve php://fd akım sarmalayıcıları için kip yok sayılır.

include_path_kullan

Açacağınız dosyanın aranacağı yollara include_path yönergesinde belirtilen yolları da dahil etmek isterseniz, isteğe bağlı olan bu üçüncü bağımsız değişkenle '1' veya true değerini aktarmalısınız.

bağlam

Akım bağlamı özkaynağı.

Dönen Değerler

Başarı durumunda bir dosya tanıtıcısı aksi takdirde false döner.

Hatalar/İstisnalar

Başarısızlık durumunda bir E_WARNING çıktılanır.

Sürüm Bilgisi

Sürüm: Açıklama
7.0.16, 7.1.2 'e' seçeneği eklendi.

Örnekler

Örnek 1 - fopen() örnekleri

<?php
$dt
= fopen("/home/rasmus/file.txt", "r");
$dt = fopen("/home/rasmus/file.gif", "wb");
$dt = fopen("http://www.example.com/", "r");
$dt = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

Notlar

Uyarı

Microsoft IIS, SSL kullanırken bir close_notify göndermeden bağlantıyı kapatarak protokolle çelişir. Verinin sonuna ulaştığınız zaman PHP bunu "SSL: Fatal Protocol Error" (SSL: "Ölümcül Protokol Hatası") olarak raporlar. Bu sorunu bertaraf etmek için error_reporting değerini uyarıları içermeyecek bir seviyeye indirmek gerekir. PHP, akımı https:// şeması kullanılarak açılırsa hatalı IIS sunucu yazılımını saptayıp uyarıları engelleyebilir. Bir ssl:// soketi oluşturmak için fsockopen() kullanılacaksa uyarıları saptayıp engellemekten geliştirici sorumludur.

Bilginize:

PHP'nin sunucu modülü sürümünü kullanıyorsanız ve dosyaları okumak ve yazmak ile ilgili sorunlar bakımından deneyimliyseniz, sunucu sürecinin bu dosya ve dizinlere erişim izninin olması gerektiğini aklınızdan çıkarmamalısınız.

Bilginize:

dosyaismi bir dizin olduğunda da bu işlev başarılı olabilir. dosyaismi'nin bir dosya mı yoksa bir dizin mi olduğundan emin olamıyorsanız fopen() işlevini çağırmadan önce is_dir() kullanmanız gerekebilir.

Ayrıca Bakınız

add a note

User Contributed Notes 24 notes

up
143
chapman at worldtakeoverindustries dot com
12 years ago
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.
up
37
Anon.
3 years ago
/***** GENTLE REMINDER *****/
Really important. Do NOT use the "w" flag unless you want to delete everything in the file.
up
9
php-manual at merlindynamics dot com
3 years ago
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 exist
up
22
php at delhelsa dot com
15 years ago
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:buttercup@example.com//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.
up
8
petepostma-deletethis at gmail dot com
6 years ago
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"
up
11
ideacode
18 years ago
Note 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.
up
6
durwood at speakeasy dot NOSPAM dot net
18 years ago
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.
up
4
php at richardneill dot org
12 years ago
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!
up
7
splogamurugan at gmail dot com
12 years ago
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.
up
3
etters dot ayoub at gmail dot com
6 years ago
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;
}
up
4
dan at cleandns dot com
20 years ago
<?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";

?>
up
5
info at b1g dot de
18 years ago
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);
}
}
}
?>
up
2
ken dot gregg at rwre dot com
20 years ago
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.
up
2
apathetic012 at gmail dot com
11 years ago
a variable $http_response_header is available when doing the fopen(). Which contains an array of the response header.
up
-1
bohwaz
1 month ago
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.
up
-2
Derrick
1 year ago
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);
up
0
kasper at webmasteren dot eu
12 years ago
"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).aspx
up
0
flobee
18 years ago
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) {
// 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;
}
?>
up
0
keithm at aoeex dot NOSPAM dot com
22 years ago
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);
?>
up
-1
wvss at gmail dot com
1 year ago
<!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>
up
-3
ceo at l-i-e dot com
17 years ago
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
?>
up
-4
wvss at gmail dot com
1 year ago
<!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>
up
-9
k-gun at git dot io
4 years ago
Seems not documented here but keep in mind, when $filename contains null byte (\0) then a TypeError will be thrown with message such;

TypeError: fopen() expects parameter 1 to be a valid path, string given in ...
up
-16
sean downey
16 years ago
when using ssl / https on windows i would get the error:
"Warning: fopen(https://example.com): failed to open stream: Invalid argument in someSpecialFile.php on line 4344534"

This was because I did not have the extension "php_openssl.dll" enabled.

So if you have the same problem, goto your php.ini file and enable it :)
To Top