「PHP Programming/Files」の版間の差分

Use lowercase variable and function names for consistency throughout the book and usual conventions
M (+category)
(Use lowercase variable and function names for consistency throughout the book and usual conventions)
Working with files is an important part of any programming language and PHP is no different. Whatever your reasons are for wanting to manipulate files, PHP will happily accommodate them through the use of a handful of functions. You should have read and be comfortable with the concepts presented in the first five sections of this book before beginning here.
 
==Fopenfopen() and Fclosefclose()==
Fopenfopen() is the basis for file manipulation. It opens a file in a certain mode (which you specify) and returns a handle. Using this handle you can read and/or write to the file, before closing it with the fclose() function.
 
{{Code:Basic
|<source lang="php">
<?php
$Handlehandle = fopen('data.txt', 'r'); // Open the file for reading
fclose($Handlehandle); // Close the file
?>
</source>
|<source lang="php">
<?php
$Contentscontents = file_get_contents('data.txt');
echo $Contentscontents;
?>
</source>
|<source lang="php">
<?php
$Lineslines = file('data.txt');
foreach($Lineslines as $Key => $Lineline) {
$LineNumlineNum = $Keykey + 1;
echo "Line $LineNumlineNum: $Lineline";
}
?>
|<source lang="php">
<?php
$Handlehandle = fopen('data.txt', 'r');
$Stringstring = fread($Handlehandle, 64);
fclose($Handlehandle);
echo $Stringstring;
?>
</source>
|<source lang="php">
<?php
$Filefile = 'data.txt';
function DetectLineEndingsdetectLineEndings($Contentscontents) {
if(false !== strpos($Contentscontents, "\r\n")) return "\r\n";
elseif(false !== strpos($Contentscontents, "\r")) return "\r";
else return "\n";
}
/* This is equivalent to file_get_contents($Filefile) but is less efficient */
$Handlehandle = fopen($Filefile, 'r');
$Contentscontents = fread($Handlehandle, filesize($Filefile));
fclose($Handlehandle);
/* This is equivalent to file($Filefile) but requires you to check for the line-ending
type. Windows systems use \r\n, Macintosh \r and Unix \n. File($Filefile) will
automatically detect line-endings whereas fread/file_get_contents won't */
$LineEndinglineEnding = DetectLineEndingsdetectLineEndings($Contentscontents);
$Contentscontents = file_get_contents($Filefile);
$Lineslines = explode($LineEndinglineEnding, $Contentscontents);
/* This is also equivalent to file_get_contents($Filefile) */
$Lineslines = file($Filefile);
$Contentscontents = implode("\n", $Lineslines);
/* This is equivalent to fread($Filefile, 64) if the file is ASCII encoded */
$Contentscontents = file_get_contents($Filefile);
$Stringctring = substr($Contentscontents, 0, 64);
?>
</source>
|<source lang="php">
<?php
$Handlehandle = fopen('data.txt', 'w'); // Open the file and delete its contents
$Datadata = "I am new content\nspread across\nseveral lines.";
fwrite($Handlehandle, $Datadata);
fclose($Handlehandle);
echo file_get_contents('data.txt');
|<source lang="php">
<?php
$Handlehandle = fopen('data.txt', 'a'); // Open the file for appending
$Datadata = "\n\nI am new content.";
fwrite($Handlehandle, $Datadata);
fclose($Handlehandle);
echo file_get_contents('data.txt');
|<source lang="php">
<?php
$Handlehandle = fopen('newfile.txt', 'x'); // Open the file only if it doesn't exist
$Datadata = "I am this file's first ever content!";
fwrite($Handlehandle, $Datadata);
fclose($Handlehandle);
echo file_get_contents('newfile.txt');
|<source lang="php">
<?php
$Handlehandle = @ fopen('data.txt', 'r');
if(!$Handlehandle) {
echo 'PHP does not have permission to read this file or the file
in question doesn\'t exist.';
} else {
$Stringstring = fread($Handlehandle, 64);
fclose($Handlehandle);
}
$Handlehandle = @ fopen('data.txt', 'w'); // The same applies for 'a'
if(!$Handlehandle) {
echo 'PHP either does not have permission to write to this file or
it does not have permission to create this file in the current directory.';
} else {
fwrite($Handlehandle, 'I can has content?');
fclose($Handlehandle);
}
$Handlehandle = @ fopen('data.txt', 'x');
if(!$Handlehandle) {
echo 'Either this file exists or PHP does not have permission to
create this file in the current directory.';
} else {
fwrite($Handlehandle, 'I can has content?');
fclose($Handlehandle);
}
?>
|<source lang="php">
<?php
$Filefile = 'data.txt';
if(!file_exists($Filefile)) {
// No point in reading since there is no content
$Contentscontents = '';
// But might want to create the file instead
$Handlehandle = @ fopen($File, 'x'); // Still need to error-check ;)
if(!$Handlehandle) {
echo 'PHP does not have permission to create a file in the current directory.';
} else {
fwrite($Handlehandle, 'Default data');
fclose($Handlehandle);
}
} else {
// The file does exist so we can try to read its contents
if(is_readable($Filefile)) {
$Contentscontents = file_get_contents($Filefile);
} else {
echo 'PHP does not have permission to read that file.';
}
if(file_exists($Filefile) && is_writeable($Filefile)) {
$Handlehandle = fopen($Filefile, 'w');
fwrite($Handlehandle, 'I can has content?');
fclose($Handlehandle);
}
?>
Why is this important? Well, when you read a file into a string with [http://php.net/file_get_contents file_get_contents()], the string will be one long line with those line-endings all over the place. Sometimes they will get in the way of things you want to do with the string so you can remove them with:
<source lang="php"><?php
$Stringstring = str_replace(array("\n", "\r"), '', $Stringstring);
?></source>
 
Other times you may need to know what kind of line-ending is being used throughout the text in order to be consistent with any new text you add. Luckily, in 99% of cases, the line-endings will never change type throughout the text so the custom function 'DetectLineEndingsdetectLineEndings' can be used as a quick way of checking:
<source lang="php"><?php
function DetectLineEndingsdetectLineEndings($Stringstring) {
if(false !== strpos($Stringstring, "\r\n")) return "\r\n";
elseif(false !== strpos($Stringstring, "\r")) return "\r";
else return "\n";
}
<?php
/* This part of the script saves the data to a file */
$Datadata = array(
'id' => 114,
'first name' => 'Foo',
'country' => 'England'
);
$Stringstring = serialize($Datadata);
$Handlehandle = fopen('data.dat', 'w');
fwrite($Handlehandle, $Stringstring);
fclose($Handlehandle);
/* Then, later on, we retrieve the data from the file and output it */
$Stringstring = file_get_contents('data.dat');
$Datadata = unserialize($Stringstring);
$Outputoutput = '';
foreach($Datadata as $Keykey => $Datumdatum) {
$Fieldtield = ucwords($Keykey);
$Outputoutput .= "$Fieldfield: $Datumdatum\n";
}
echo $Outputoutput
?>
</source>
|<source lang="php">
<?php
$Filefile = 'data.txt';
$Contentcontent = 'New content.';
 
// PHP 4, overwrite entire file with data
$Handlehandle = fopen($Filefile, 'w');
fwrite($Handlehandle, $Contentcontent);
fclose($Handlehandle);
// PHP 5
file_put_contents($Filefile, $Contentcontent);
// PHP 4, append to a file
$Handlehandle = fopen($Filefile, 'a');
fwrite($Handlehandle, $Contentcontent);
fclose($Handlehandle);
// PHP 5
file_put_contents($Filefile, $Contentcontent, FILE_APPEND);
?>
</source>
<?php
if(!function_exists('file_put_contents')) {
function file_put_contents($Filefile, $Datadata, $Appendappend = false) {
if(!$Appendappend) $Modemode = 'w';
else $Modemode = 'a';
$Handlehandle = @ fopen($Filefile, $Modemode);
if(!$Handlehandle) return false;
$Bytesbytes = fwrite($Handlehandle, $Datadata);
fclose($Handlehandle);
return $Bytesbytes;
}
}