Professional Documents
Culture Documents
PHP and MySql-IV
PHP and MySql-IV
PHP and MySql-IV
Working with Files and Directories: Including Files with include(), Validating Files, Creating and
Deleting Files, Opening a File for Writing, Reading or Appending, Reading from Files, Writing or
Appending to a File, Working with Directories, Open Pipes to and from Process Using popen (),
Running Commands with exec(), Running Commands with system ( ) or passthru ( ).
Working with Images: Understanding the Image-Creation Process, Necessary Modifications to PHP,
Drawing a New Image, Getting Fancy with Pie Charts, Modifying Existing Images, Image Creation
from User Input.
You can save a lot of time and work through including file-Just store a block of code in a separate file
and include it wherever you want by include() and required statement instead of typing the entire
block of code multiple times. A typical example is including the header, footer and menu file in all the
pages of a website.
The basic syntax of the include () and required () statement can be given with:
Include(“path/to/filename”);
Required(“path/to/filename”);
The include() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the include() function generates a
warning but the script will continue execution.
Assume you want to create a common menu for your website. Then create a file menu.php with the
following content.
<a href="http://www.tutorialtpoint.com/index.htm">Home</a> -
<a href="http://www.tutorialtpoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialtpoint.com/ajax">AJAX</a> -
<html>
<body>
</body>
</html>
The require() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the require() function generates a fatal
error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is
recommended to use the require() function instead of include(), because scripts should not continue
executing if files are missing or misnamed.
<html>
<body>
</body>
</html>
You can test for the existence of a file with the file_exists () function. This function requires a string
representation of an absolute or relative path to a file, which might or might not be present. If the file
is found, the file_exists () function returns true; otherwise, it returns false:
Example: if (file_exists(‘test.txt’)) {
2. A File or a Directory?
You can confirm that the entity you’re testing is a file, as opposed to a directory, using the is_file()
function. The is_file() function requires the file path and returns a Boolean value:
Example: if (is_file(‘test.txt’)) {
Conversely, you might want to check that the entity you’re testing is a directory. You can do this with
the is_dir() function. is_dir() requires the path to the directory and returns a Boolean value:
Example: if (is_dir(‘/tmp’)) {
Example:
if (is_readable(‘test.txt’)) {
The is_writable() function tells you whether you have the proper permission to write to a file. As with
is_readable(), the is_writable() function requires the file path and returns a Boolean value.
Example:
if (is_writable(‘test.txt’)) {
The is_executable() function tells you whether you can execute the given file, relying on either the
file’s permissions or its extension, depending on your platform. The function accepts the file path and
returns a Boolean value.
Example:
if (is_executable(‘test.txt’)) {
4. Determining File Size with filesize() Given the path to a file, the filesize() function attempts to
determine and return its size in bytes. It returns false if it encounters problems:
Example:
touch(‘myfile.txt’);
You can remove an existing file with the unlink() function. As did the touch() function, unlink()
accepts a file path:
unlink(‘myfile.txt’);
Example:
<?php
$file = "test.txt";
if (!unlink($file))
else
?>
All functions that create, delete, read, write, and modify files on UNIX systems require the correct file
or directory permissions to be set.
a) Opening file using fopen():A better method to open files is with the fopen() function. This function
gives you more options than the readfile() function.
The first parameter of fopen() contains the name of the file to be opened and the second parameter
specifies in which mode the file should be opened. The following example also generates a message if
the fopen() function is unable to open the specified file:
The fopen() function returns a file resource you use later to work with the open file.
iii) To open a file for appending (that is, to add data to the end of a file), you use this:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
</body>
</html>
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
Open a file for write only. Erases the contents of the file or creates a new file if it doesn't
w
exist. File pointer starts at the beginning of the file
Open a file for write only. The existing data in file is preserved. File pointer starts at the
a
end of the file. Creates a new file if the file doesn't exist
b) fread()
The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
c) fclose()
The fclose() function is used to close an open file. The fclose() requires the name of the file (or a
variable that holds the filename) we want to close:
<?php
fclose($myfile);
?>
Reading Line from a File - fgets() – used to read a line from an opened file.
Example:
<?php
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the next line.
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
<?php
while(!feof($myfile)) {
fclose($myfile);
?>
Rather than reading text by the line, you can choose to read a file in arbitrarily defined chunks. The
fread() function accepts a file resource as an argument, as well as the number of bytes you want to
read. The fread() function returns the amount of data you requested, unless the end of the file is
reached first:
fread($myfile,filesize("webdictionary.txt"));
The example below reads the "webdictionary.txt" file character by character, until end-of-file is
reached:
<?php
while(!feof($myfile)) {
echo fgetc($myfile);
fclose($myfile);
?>
The PHP fwrite() function is used to write and append data into file.
Example
<?php
fclose($fp);
?>
The mkdir() function enables you to create a directory. The mkdir() function requires a string that
represents the path to the directory you want to create and an octal number integer that represents
the mode you want to set for the directory.
Example:
The rmdir() function enables you to remove a directory from the file system if the process running
your script has the right to do so, and if the directory is empty. The rmdir() function requires only a
string representing the path to the directory you want to delete.
rmdir(“testdir”);
Before you can read the contents of a directory, you must first obtain a directory resource. You can
do so with the opendir() function. The opendir() function requires a string that represents the path to
the directory you want to open. The opendir() function returns a directory handle unless the directory
isn’t present or readable; in that case, it returns false:
$dh = opendir(“testdir”);
Just as you use the fgets() function to read a line from a file, you can use readdir() to read a file or
directory name from a directory. The readdir() function requires a directory handle and returns a
string containing the item name. If the end of the directory is reached, readdir() returns false.
<?php
$dirname = “.”;
$dh = opendir($dirname) or die(“Couldn’t open directory”);
while (!(($file = readdir($dh)) === false ) ) {
if (is_dir(“$dirname/$file”)) {
echo “(D) “;
}
echo $file.”<br/>”;
}
closedir($dh);
?>
The PHP poned() function is used to create a new pipe connection for the program that was specified
by command parameters. The popen() function is used like this:
<?php
$file_handle = popen(“/path/to/fakefile 2>&1”, “r”);
$read = fread($file_handle, 2096);
echo $read;
pclose($file_handle);
?>
The exec() function is one of several functions you can use to pass commands to the shell. The exec()
function requires a string representing the path to the command you want to run, and optionally
accepts an array variable that will contain the output of the command and a scalar variable that will
contain the return value (1 or 0).
For example:
<?php
exec(“ls -al .”, $output_array, $return_val);
echo “Returned “.$return_val.”<br/><pre>”;
foreach ($output_array as $o) {
echo $o.”\n”;
}
echo “</pre>”;
?>
The system() function is similar to the exec() function in that it launches an external application, and it
utilizes a scalar variable for storing a return value:
system(“/path/to/somecommand”, $return_val);
The system() function differs from exec() in that it outputs information directly to the browser,
without programmatic intervention. The following snippet of code uses system() to print a man page
for the man command, formatted with the <pre></pre> tag pair:
<?php
echo “<pre>”;
system(“man man | col –b”, $return_val);
echo “</pre>”;
?>
the passthru() function follows the syntax of the system() function, but it behaves differently. When
you are using passthru(), any output from the shell command is not buffered on its way back to you;
this is suitable for running commands that produce binary data rather than simple text data.
<?php
if ((isset($_GET[‘imagename’])) && (file_exists($_GET[‘imagename’]))) {
header(“Content-type: image/gif”);
passthru(“giftopnm “.$_GET[‘imagename’].” |
pnmscale -xscale .5 -yscale .5 | ppmtogif”);
} else {
echo “The image “.$_GET[‘imagename’].” could not be found”;
}
?>