Files in PHP

Posted by Unknown at 18:58
How To Read a Text File into an Array?
If you have a text file with multiple lines, and you want to read those lines into an array, you can use the file() function. It opens the specified file, reads all the lines, puts each line as a value in an array, and returns the array to you. Here is a PHP script example on how to use file():
<?php 
$lines = file("/windows/system32/drivers/etc/services");
foreach ($lines as $line) {
$line = rtrim($line);
print("$line\n");
# more statements...
} ?>
This script will print:# This file contains port numbers for well-known services
 echo           7/tcp
ftp                    21/tcp
telnet                 23/tcp
smtp                  25/tcp
...
Note that file() breaks lines right after the new line character "\n". Each line will contain the "\n" at the end. This is why we suggested to use rtrime() to remove "\n".Also note that, if you are on Unix system, your Internet service file is located at "/etc/services".

How To Read the Entire File into a Single String?
If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents():
<?php 
$file = file_get_contents("/windows/system32/drivers/etc/services");
print("Size of the file: ".strlen($file)."\n");
?>
This script will print:Size of the file: 7116

How To Open a File for Reading?
If you want to open a file and read its contents piece by piece, you can use the fopen($fileName, "r") function. It opens the specified file, and returns a file handle. The second argument "r" tells PHP to open the file for reading. Once the file is open, you can use other functions to read data from the file through this file handle. Here is a PHP script example on how to use fopen() for reading:
<?php 
$file = fopen("/windows/system32/drivers/etc/hosts", "r");
print("Type of file handle: " . gettype($file) . "\n");
print("The first line from the file handle: " . fgets($file));
fclose($file); 
?>
This script will print:Type of file handle: resource.The first line from the file handle: # Copyright (c) 1993-1999
Note that you should always call fclose() to close the opened file when you are done with the file.

How To Open a File for Writing?
If you want to open a new file and write date to the file, you can use the fopen($fileName, "w") function. It creates the specified file, and returns a file handle. The second argument "w" tells PHP to open the file for writing. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for writing:
<?php 
$file = fopen("/temp/todo.txt", "w");
fwrite($file,"Download PHP scripts at dev.pickzycenter.com.\r\n");
fclose($file); 
?>
This script will write the following to the file:Download PHP scripts at dev.pickzycenter.com.
Note that you should use "\r\n" to terminate lines on Windows. On a Unix system, you should use "\n". 

How To Append New Data to the End of a File?
If you have an existing file, and want to write more data to the end of the file, you can use the fopen($fileName, "a") function. It opens the specified file, moves the file pointer to the end of the file, and returns a file handle. The second argument "a" tells PHP to open the file for appending. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for appending:
<?php 
$file = fopen("/temp/cgi.log", "a");
fwrite($file,"Remote host: 64.233.179.104.\r\n");
fclose($file); 
$file = fopen("/temp/cgi.log", "a");
fwrite($file,"Query string: cate=102&order=down〈=en.\r\n");
fclose($file); 
?>
This script will write the following to the file:Remote host: 64.233.179.104.
Query string: cate=102&order=down〈=en. As you can see, file cgi.log opened twice by the script. The first call of fopen() actually created the file. The second call of fopen() opened the file to allow new data to append to the end of the file. 

How To Read One Line of Text from a File?
If you have a text file with multiple lines, and you want to read those lines one line at a time, you can use the fgets() function. It reads the current line up to the "\n" character, moves the file pointer to the next line, and returns the text line as a string. The returning string includes the "\n" at the end. Here is a PHP script example on how to use fgets():
<?php 
$file = fopen("/windows/system32/drivers/etc/services", "r");
while ( ($line=fgets($file)) !== false ) {
$line = rtrim($line);
print("$line\n");
# more statements...
}
fclose($file); 
?>
This script will print:# This file contains port numbers for well-known services
echo   7/tcp
ftp      21/tcp
telnet  23/tcp
smtp  25/tcp
...
Note that rtrim() is used to remove "\n" from the returning string of fgets().

How To Read One Character from a File?
If you have a text file, and you want to read the file one character at a time, you can use the fgetc() function. It reads the current character, moves the file pointer to the next character, and returns the character as a string. If end of the file is reached, fgetc() returns Boolean false. Here is a PHP script example on how to use fgetc():
<?php 
$file = fopen("/windows/system32/drivers/etc/services", "r");
$count = 0;
while ( ($char=fgetc($file)) !== false ) {
if ($char=="/") $count++;
}
fclose($file); 
print("Number of /: $count\n");
?>
This script will print:Number of /: 113
Note that rtrim() is used to remove "\n" from the returning string of fgets().

What's Wrong with "while ($c=fgetc($f)) {}"?
If you are using "while ($c=fgetc($f)) {}" to loop through each character in a file, the loop may end in the middle of the file when there is a "0" character, because PHP treats "0" as Boolean false. To properly loop to the end of the file, you should use "while ( ($c=fgetc($f)) !== false ) {}". Here is a PHP script example on incorrect testing of fgetc():
<?php 
$file = fopen("/temp/cgi.log", "w");
fwrite($file,"Remote host: 64.233.179.104.\r\n");
fwrite($file,"Query string: cate=102&order=down〈=en.\r\n");
fclose($file); 
$file = fopen("/temp/cgi.log", "r");
while ( ($char=fgetc($file)) ) {
print($char);
}
fclose($file); 
?>
This script will print:Remote host: 64.233.179.1
As you can see the loop indeed stopped at character "0".

How To Read a File in Binary Mode?
If you have a file that stores binary data, like an executable program or picture file, you need to read the file in binary mode to ensure that none of the data gets modified during the reading process. You need to:
Open the file with fopen($fileName, "rb").
Read data with fread($fileHandle,$length).
Here is a PHP script example on reading binary file:
<?php 
$in = fopen("/windows/system32/ping.exe", "rb");
$out = fopen("/temp/myPing.exe", "w");
$count = 0;
while (!feof($in)) {
$count++;
$buffer = fread($in,64);
fwrite($out,$buffer);
}
fclose($out); 
fclose($in);
print("About ".($count*64)." bytes read.\n"); 
?>
This script will print:About 16448 bytes read.This script actually copied an executable program file ping.exe in binary mode to new file. The new file should still be executable. Try it: \temp\capptitudebank,blogspot.com.

How To Write a String to a File with a File Handle?
If you have a file handle linked to a file opened for writing, and you want to write a string to the file, you can use the fwrite() function. It will write the string to the file where the file pointer is located, and moves the file pointer to the end of the string. Here is a PHP script example on how to use fwrite():
<?php 
$file = fopen("/temp/todo.txt", "w");
fwrite($file,"Download PHP scripts at  capptitudebank,blogspot.com .\r\n");
fwrite($file,"Download Perl scripts at  capptitudebank,blogspot.com .\r\n");
fclose($file); 
?>
This script will write the following to the file:
Download PHP scripts at  capptitudebank,blogspot.com .
Download Perl scripts at  capptitudebank,blogspot.com .

How To Write a String to a File without a File Handle?
If you have a string, want to write it to a file, and you don't want to open the file with a file handle, you can use the file_put_contents(). It opens the specified file, writes the specified string, closes the file, and returns the number of bytes written. Here is a PHP script example on how to use file_put_contents():<?php
$string = "Download PHP scripts at  capptitudebank,blogspot.com .\r\n";
$string .= "Download Perl scripts at  capptitudebank,blogspot.com .\r\n";
$bytes = file_put_contents("/temp/todo.txt", $string);
print("Number of bytes written: $bytes\n");
?>
This script will print:Number of bytes written: 89
If you look at the file todo.txt, it will contain:
Download PHP scripts at  capptitudebank,blogspot.com .
Download Perl scripts at  capptitudebank,blogspot.com .

How To Write an Array to a File without a File Handle?
If you have an array, want to write it to a file, and you don't want to open the file with a file handle, you can use the file_put_contents(). It opens the specified file, writes all values from the specified string, closes the file, and returns the number of bytes written. Here is a PHP script example on how to use file_put_contents():<?php
$array["one"] = "Download PHP scripts at  capptitudebank,blogspot.com .\r\n";
$array["two"] = "Download Perl scripts at  capptitudebank,blogspot.com .\r\n";
$bytes = file_put_contents("/temp/todo.txt", $array);
print("Number of bytes written: $bytes\n");
?>
This script will print:Number of bytes written: 89
If you look at the file todo.txt, it will contain:
Download PHP scripts at  capptitudebank,blogspot.com .
Download Perl scripts at  capptitudebank,blogspot.com .

How To Read Data from Keyborad (Standard Input)?
If you want to read data from the standard input, usually the keyboard, you can use the fopen("php://stdin") function. It creates a special file handle linking to the standard input, and returns the file handle. Once the standard input is opened to a file handle, you can use fgets() to read one line at a time from the standard input like a regular file. Remember fgets() also includes "\n" at the end of the returning string. Here is a PHP script example on how to read from standard input:<?php
$stdin = fopen("php://stdin", "r");
print("What's your name?\n");
$name = fgets($stdin);
print("Hello $name!\n");
fclose($stdin);
?>
This script will print:
What's your name?
Leo
Hello Leo
!
"!" is showing on the next line, because $name includes "\n" returned by fgets(). You can use rtrim() to remove "\n".If you are using your script in a Web page, there is no standard input.If you don't want to open the standard input as a file handle yourself, you can use the constant STDIN predefined by PHP as the file handle for standard input.

How To Open Standard Output as a File Handle?
If you want to open the standard output as a file handle yourself, you can use thefopen("php://stdout") function. It creates a special file handle linking to the standard output, and returns the file handle. Once the standard output is opened to a file handle, you can use fwrite() to write data to the starndard output like a regular file. Here is a PHP script example on how to write to standard output:
<?php
$stdout = fopen("php://stdout", "w");
fwrite($stdout,"To do:\n");
fwrite($stdout,"Looking for PHP hosting provider!\n");
fclose($stdout);
?>
This script will print:What's your name?
To do:Looking for PHP hosting provider!
If you don't want to open the standard output as a file handle yourself, you can use the constant STDOUT predefined by PHP as the file handle for standard output.If you are using your script in a Web page, standard output is merged into the Web page HTML document.print() and echo() also writes to standard output.

How To Create a Directory?
You can use the mkdir() function to create a directory. Here is a PHP script example on how to use mkdir():
<?php 
if (file_exists("/temp/download")) {
print("Directory already exists.\n");
} else {
mkdir("/temp/download");
print("Directory created.\n");
}
?>
This script will print:Directory created.
If you run this script again, it will print:Directory already exists.

How To Remove an Empty Directory?
If you have an empty existing directory and you want to remove it, you can use the rmdir(). Here is a PHP script example on how to use rmdir():
<?php 
if (file_exists("/temp/download")) {
rmdir("/temp/download");
print("Directory removed.\n");
} else {
print("Directory does not exist.\n");
}
?>
This script will print:Directory removed.If you run this script again, it will print:Directory does not exist.

How To Remove a File?
If you want to remove an existing file, you can use the unlink() function. Here is a PHP script example on how to use unlink():
<?php
if (file_exists("/temp/todo.txt")) {
unlink("/temp/todo.txt");
print("File removed.\n");
} else {
print("File does not exist.\n");
}
?>
This script will print:File removed.If you run this script again, it will print:File does not exist.

How To Copy a File?
If you have a file and want to make a copy to create a new file, you can use the copy() function. Here is a PHP script example on how to use copy():
<?php
unlink("/temp/myPing.exe");
copy("/windows/system32/ping.exe", "/temp/myPing.exe");
if (file_exists("/temp/myPing.exe")) {
print("A copy of ping.exe is created.\n"); 
}
?>
This script will print:A copy of ping.exe is created.

How To Dump the Contents of a Directory into an Array?
If you want to get the contents of a directory into an array, you can use the scandir() function. It gets a list of all the files and sub directories of the specified directory and returns the list as an array. The returning list also includes two specify entries: (.) and (..). Here is a PHP script example on how to use scandir():
<?php
mkdir("/temp/download");
$array["one"] = "Download PHP scripts at dev.pickzycenter.com.\r\n";
$array["two"] = "Download Perl scripts at dev.pickzycenter.com.\r\n";
$bytes = file_put_contents("/temp/download/todo.txt", $array);
$files = scandir("/temp/download");
print_r($files);
?>
This script will print:Array
(
[0] => .
[1] => ..
[2] => todo.txt
)

How To Read a Directory One Entry at a Time?
If you want to read a directory one entry at a time, you can use opendir() to open the specified directory to create a directory handle, then use readdir() to read the directory contents through the directory handle one entry at a time. readdir() returns the current entry located by the directory pointer and moves the pointer to the next entry. When end of directory is reached, readdir() returns Boolean false. Here is a PHP script example on how to use opendir() and readdir():
<?php
mkdir("/temp/download");
$array["one"] = "Download PHP scripts at dev.pickzycenter.com.\r\n";
$array["two"] = "Download Perl scripts at dev.pickzycenter.com.\r\n";
$bytes = file_put_contents("/temp/download/todo.txt", $array);
print("List of files:\n");
$dir = opendir("/temp/download");
while ( ($file=readdir($dir)) !== false ) {
print("$file\n");
}
closedir($dir);
?>
This script will print:List of files:
.
..
todo.txt

How To Get the Directory Name out of a File Path Name?
If you have the full path name of a file, and want to get the directory name portion of the path name, you can use the dirname() function. It breaks the full path name at the last directory path delimiter (/) or (\), and returns the first portion as the directory name. Here is a PHP script example on how to use dirname():
<?php
$pathName = "/temp/download/todo.txt";
$dirName = dirname($pathName);
print("File full path name: $pathName\n");
print("File directory name: $dirName\n");
print("\n");
?>
This script will print:File full path name: /temp/download/todo.txt
File directory name: /temp/download

How To Break a File Path Name into Parts?
If you have a file name, and want to get different parts of the file name, you can use the pathinfo() function. It breaks the file name into 3 parts: directory name, file base name and file extension; and returns them in an array. Here is a PHP script example on how to use pathinfo():
<?php
$pathName = "/temp/download/todo.txt";
$parts = pathinfo($pathName);
print_r($parts);
print("\n");
?>
This script will print:Array
(
[dirname] => /temp/download
[basename] => todo.txt
[extension] => txt
)


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

© 2011. All Rights Reserved | Interview Questions | Template by Blogger Widgets

Home | About | Top