If you're getting "failed to open stream: Permission denied" when trying to use either file() or fopen() to access files on another server. Check your host doesn't have any firewall restrictions in-place which prevent outbound connections. This is the case with my host Aplus.net
file
(PHP 4, PHP 5)
file — ファイル全体を読み込んで配列に格納する
説明
ファイル全体を配列に読み込みます。
注意: ファイルの内容を文字列として返すには file_get_contents() を使用します。
パラメータ
- filename
-
ファイルへのパス。
ヒントfopen wrappers が有効の場合、この関数のファイル名として URL を使用することができます。ファイル名の指定方法に関する詳細は fopen()、サポートされる URL プロトコルの種類 については、(例えば)サポートされるプロトコル/ラッパー を参照してください。
- flags
-
オプションのパラメータ flags は、以下の定数のうちのひとつ、あるいは複数の組み合わせとなります。
- FILE_USE_INCLUDE_PATH
- include_path のファイルを探します。
- FILE_IGNORE_NEW_LINES
- 配列の各要素の最後に改行文字を追加しません。
- FILE_SKIP_EMPTY_LINES
- 空行を読み飛ばします。
- FILE_TEXT
- コンテンツを UTF-8 エンコーディングで返します。 別のエンコーディングを指定するには、独自のコンテキストを作成します。 このフラグは FILE_BINARY と同時に使用することはできません。 このフラグは PHP 6 以降でのみ使用可能です。
- FILE_BINARY
- コンテンツをバイナリデータとして読み込みます。 これはデフォルトの設定で、 FILE_TEXT と同時に使用することはできません。 このフラグは PHP 6 以降でのみ使用可能です。
- context
-
stream_context_create() 関数で作成したコンテキストリソース。
注意: コンテキストのサポートは、 PHP 5.0.0 で追加されました。contexts の説明に関しては、 ストリーム を参照してください。
返り値
ファイルを配列に入れて返します。 配列の各要素はファイルの各行に対応します。改行記号はついたままとなります。 失敗すると file() は FALSE を返します。
注意: FILE_IGNORE_NEW_LINES を指定しない限り、 配列に取り込まれた各行は行末文字も含みます。 行末文字を取り除きたい場合には rtrim() を使用する必要があります。
注意: マッキントッシュコンピュータ上で作成されたファイルを読み込む際に、 PHP が行末を認識できないという問題が発生した場合、 実行時の設定オプションauto_detect_line_endings を有効にする必要が生じるかもしれません。
変更履歴
| バージョン | 説明 |
|---|---|
| 6.0.0 | FILE_TEXT フラグおよび FILE_BINARY フラグをサポートするようになりました。 |
| 5.0.0 | context パラメータが追加されました。 |
| 5.0.0 | PHP 5.0.0 より前のバージョンでは、パラメータ flags でカバーしているのは include_path の設定だけでした。これを有効にするには 1 を指定します。 |
| 4.3.0 | file() はバイナリセーフとなりました。 |
例
Example#1 file() の例
<?php
// ファイルの内容を配列に取り込みます。
// この例ではHTTPを通してURL上のHTMLソースを取得します。
$lines = file('http://www.example.com/');
// 配列をループしてHTMLをHTMLソースとして表示し、行番号もつけます。
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// 他の例として、Webページを文字列に取り込みます。file_get_contents()も参照してください。
$html = implode('', file('http://www.example.com/'));
?>
注意
IIS のような、いくつかの標準に 対応してない Web サーバは、PHP に警告を発生させるような手順でデータを送信します。 このようなサーバを使用する場合は、 error_reporting を警告を発生しないレベルまで小さくする必要があります。 PHP 4.3.7 以降では、https:// ラッパーでストリームをオープンする際に バグがある IIS サーバソフトウエアを検出することができ、この警告を抑制することができます。 あなたが ssl:// ソケットを作性するために fsockopen() を使用している場合、 自らこの警告を検出し、抑制する必要があります。
file
16-Feb-2008 06:15
12-Jul-2007 06:25
This note applies to PHP 5.1.6 under Windows (although may apply to other versions).
It appears that the 'FILE_IGNORE_NEW_LINES' flag doesn't remove newlines properly when reading Windows-style text files, i.e. files whose lines end in '\r\n'.
Solution: Always use 'rtrim()' in preference to 'FILE_IGNORE_NEW_LINES'.
28-Nov-2006 05:33
Using file() for reading large text files > 10 Mb gives problems, therefore you should use this instead. It is much slower but it works fine. $lines will return an array with all the lines.
$handle = @fopen('yourfile...', "r");
if ($handle) {
while (!feof($handle)) {
$lines[] = fgets($handle, 4096);
}
fclose($handle);
}
11-Jul-2006 06:19
justin at visunet dot ie's note of 20-Mar-2003 states
"Note: Now that file() is binary safe it is 'much' slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file()."
I tested fgets(), file_get_contents(), and file() on PHP 4.3.2 and PHP 5 and timed each to be under a second with over 200,000 lines. I do not know if he was testing extremely long lines or what, but I could not duplicate the difference that he mentioned.
01-Feb-2006 07:52
you can use
$file = array_map('rtrim',file('myfile.txt'));
to remove annoying ending lines of the resulting array.
19-Jan-2006 08:16
WARNING ON WINDOWS:
file() function will add "\r\n" in to the end of the row, even if you use only "\n" char to make rows in the file!
On UNIX systems there is no such problem.
13-Sep-2003 06:48
Jeff's array2file function is a good start; here are a couple of improvements (no possibility of handle leak when fwrite fails, additional capability of both string2file and array2file; presumably faster performance through use of implode).
function String2File($sIn, $sFileOut) {
$rc = false;
do {
if (!($f = fopen($sFileOut, "wa+"))) {
$rc = 1; break;
}
if (!fwrite($f, $sIn)) {
$rc = 2; break;
}
$rc = true;
} while (0);
if ($f) {
fclose($f);
}
return ($rc);
}
function Array2File($aIn, $sFileOut) {
return (String2File(implode("\n", $aIn), $sFileOut));
}
If you're generating your string text using a GET or POST from a TEXTAREA (e.g., a mini-web-text-editor), remember that strip_slashes and str_replace of "/r/n" to "/n" may be necessary as well using these functions.
HTH --dir @ badblue com
21-Jul-2003 08:32
after many months of confusion and frustration, i have finally figured out something that i should have noticed the first time around.
you can't file("test.txt") when that same file has been flocked. i guess i didn't have a full understanding of what i was doing when i used flock(). all i had to do was move the flock() around, and all was well.
21-Mar-2003 02:36
Note: Now that file() is binary safe it is 'much' slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:
$fd = fopen ("log_file.txt", "r");
while (!feof ($fd))
{
$buffer = fgets($fd, 4096);
$lines[] = $buffer;
}
fclose ($fd);
The resulting array is $lines.
I did a test on a 200,000 line file. It took seconds with fgets() compared to minutes with file().
You can use file with https if you go to:
http://ftp.proventum.net/pub/php/win32/misc/openssl/.
This is instead of using the php_openssl.dll, so be sure to comment this extension in your php.ini.
17-Mar-2002 04:16
file() has a strange behaviour when reading file with both \n and \r as line delimitator (DOS files), since it will return an array with every single line but with just a \n in the end. It seems like \r just disappears.
This is happening with PHP 4.0.4 for OS/2. Don't know about the Windows version.
10-Feb-2002 05:56
It appears that the file() function causes file access problems for perl cgi scripts accessing the same files. I am using Perl v5.6.0 in linux with PHP/4.0.4pl1. After running a php app using the file() function, any perl cgi trying to access the same file randomly dies returning an internal server error: premature end of script headers.
The simple fix is to use fopen(), fgets() and fclose() instead of file().