PHP and MySql-IV

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Unit-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.

1. Including Files with include ()


You can include the content of a PHP file into another PHP file before the server executes it. There
are two PHP functions which can be used to include one PHP file into another PHP file.

 The include() Function

 The require() Function

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

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> -

<a href="http://www.tutorialtpoint.com/perl">PERL</a> <br />

1 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


Now create as many pages as you like and include this file to create header. For example now your
test.php file can have following content.

<html>

<body>

<?php include("menu.php"); ?>

<p>This is an example to show how to include PHP file!</p>

</body>

</html>

The require() Function

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>

<?php include("xxmenu.php"); ?>

<p>This is an example to show how to include wrong PHP file!</p>

</body>

</html>

2 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


2. Validating Files.
PHP provides many functions to help you to discover information about files on your system. Some
of the more useful functions are discussed below.

1. Checking for Existence with file_exists ():

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’)) {

echo “The file exists!”;

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’)) {

echo “test.txt is a file!”;

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’)) {

echo “/tmp is a directory”;

3. Checking the Status of a File


The is_readable() function tells you whether you can read a file. The is_readable() function accepts the
file path as a string and returns a Boolean value:

Example:

if (is_readable(‘test.txt’)) {

3 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


echo “test.txt is readable”;

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’)) {

echo “test.txt is writable”;

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’)) {

echo “test.txt is executable”;

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:

echo “The size of test.txt is “.filesize(‘test.txt’);

4 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


3. Creating and Deleting Files
If a file does not yet exist, you can create it with the touch() function. Given a string representing a file
path, touch() attempts to create an empty file of that name. If the file already exists, its contents is not
disturbed, but the modification date is updated to reflect the time at which the function executed:

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))

echo ("Error deleting $file");

else

echo ("Deleted $file");

?>

All functions that create, delete, read, write, and modify files on UNIX systems require the correct file
or directory permissions to be set.

5 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


4. Opening a File for Writing, Reading, or Appending
Before you can work with a file, you must first open it for reading or writing, or for performing both
tasks.

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.

i) To open a file for reading, you use the following:

$fp = fopen(“test.txt”, “r”);

ii) You use the following to open a file for writing:

$fp = fopen(“test.txt”, “w”);

iii) To open a file for appending (that is, to add data to the end of a file), you use this:

$fp = fopen(“test.txt”, “a”);

Example:

<!DOCTYPE html>

<html>

<body>

<?php

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");

echo fread($myfile,filesize("webdictionary.txt"));

fclose($myfile);

?>

</body>

</html>

6 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


The file may be opened in one of the following modes:

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 fread() function reads from an open file.

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

$myfile = fopen("webdictionary.txt", "r");

// some code to be executed....

fclose($myfile);

?>

7 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


5. Reading from Files.
PHP provides a number of functions for reading data from files. These functions enable you to read
the byte, by the whole line, and even by the single character.

Reading Line from a File - fgets() – used to read a line from an opened file.

Example:

<?php

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");

echo fgets($myfile);

fclose($myfile);

?>

Note: After a call to the fgets() function, the file pointer has moved to the next line.

PHP Check End-Of-File - feof()

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

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");

// Output one line until end-of-file

while(!feof($myfile)) {

echo fgets($myfile) . "<br>";

fclose($myfile);

?>

8 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


Reading Arbitrary Amounts of Data from a File with fread()

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"));

PHP Read Single Character - fgetc()

The fgetc() function is used to read a single character from a file.

The example below reads the "webdictionary.txt" file character by character, until end-of-file is
reached:

<?php

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");

// Output one character until end-of-file

while(!feof($myfile)) {

echo fgetc($myfile);

fclose($myfile);

?>

9 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


6. Writing or Appending to a File
You can append data into file by using a or a+ mode in fopen() function. Let's see a simple example
that appends data into data.txt file.

PHP Append to File - fwrite()

The PHP fwrite() function is used to write and append data into file.

Example

<?php

$fp = fopen('data.txt', 'a');//opens file in append mode

fwrite($fp, ' this is additional text ');

fwrite($fp, 'appending data');

fclose($fp);

echo "File appended successfully";

?>

7. Working with Directories


As is necessary for any language, PHP has a complete set of directory support functions. PHP gives
you a variety of functions to read and manipulate directories and directory entities.

Creating Directories with mkdir()

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:

mkdir(“testdir”, 0777); // global read/write/execute permissions

mkdir(“testdir”, 0755); // world/group: read/execute; owner: read/write/execute

10 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


Removing a Directory with rmdir()

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”);

Opening a Directory for Reading with opendir()

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”);

In this case, $dh is the directory handle of the open directory.

Reading the Contents of a Directory with readdir()

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);
?>

11 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


8. Open Pipes to and from Process Using popen ()

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:

$file_pointer = popen(“some command”, mode)

The mode is either r (read) or w (write).

<?php
$file_handle = popen(“/path/to/fakefile 2>&1”, “r”);
$read = fread($file_handle, 2096);
echo $read;
pclose($file_handle);
?>

9. Running Commands with exec()

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:

exec(“/path/to/somecommand”, $output_array, $return_val);

<?php
exec(“ls -al .”, $output_array, $return_val);
echo “Returned “.$return_val.”<br/><pre>”;
foreach ($output_array as $o) {
echo $o.”\n”;
}
echo “</pre>”;
?>

12 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)


10. Running Commands with system ( ) or passthru ( ).

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”;
}
?>

13 © www.anuupdates.org Prepared by D.Venkata Reddy. M.Tech(CSE)

You might also like