Files
Testing files, lets test for some existence and status of a file called text1.txt
<?php
// Checking its existence
if (file_exists("text1.txt")) {
echo "The file text1.txt exists!";
}
// checking the status of files
if (is_readable("text1.txt")) {
echo "The file text1.txt is readable";
}
if (is_writeable("text1.txt")) {
echo "The file text1.txt is writeable";
}
if (is_executable("text1.txt")) {
echo "The file text1.txt is exectuable";
}
?>
You probably only see "The file text1.txt exists". If you only see this, you will need to chmod the read,write and execute settings on that file.
Reading data from files
<?php
$filename = "text1.txt";
$fp = fopen($filename, "r") or die ("Could not open $filename");
while (!feof($fp)) { // While not end of file
$data = fread($fp, 16); // Reading the file in chunkcs of 16 bytes
echo "$data <br>";
}
?>
There are multiple ways you can read from a file includes
Fgets() : Reading line by line
Fgetc() : Reading a character
Writing to a file
<?php
$filename = "text1.txt";
echo "Begin writing to file $filename <br>";
$fp = fopen($filename, "w") or die ("Could not open $filename"); // OPen for writing
fwrite ($fp, "I'm making changes \n");
fclose($fp);
?>
If you have trouble writing to the file, it could be a permission setting. Try chmod 777
Appending to a file
<?php
$filename = "text1.txt";
echo "Appending to a file $filename <br>";
$fp = fopen($filename, "a") or die ("Could not open $filename"); // OPen for writing
fputs ($fp, "\n Another thing I want to add \n");
fclose($fp);
?>
The file text1.txt will have a new line called Another thing I want to add.
Directories
Creating a new directory
<?php
mkdir ("testdir", 0755);
?>
If you failed to create a directory, again it usually means you have incorrect permissions settings.
Directory listing
<?php
$dirname = ".";
$dn = opendir($dirname) or die ("Could not open directory");
while (!(($file = readdir($dn)) === false ) ) {
if (is_dir("$dirname/$file")) {
echo "(D) "; // To signify a folder
}
echo "$file <br>";
}
closedir ($dn);
?>
0 comments:
Post a Comment