PHP Unit4
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.
Q) How to
include files in PHP documents.
In PHP,
there are two functions that are used to put the contents of a file
containing PHP source code into another PHP
file. These function are Include() and Require(). These functions
are the same if but they have one difference. The difference is that the
include() function produces a warning, but the script will continue execution,
while the require() function produces a warning and a fatal error i.e. the
script will not continue execution. These two functions are used to put the
data of a file into another PHP
file before it is executed by the server.
Syntax:
include 'filename'; or
require 'filename';
Example:First of all we create a PHP file called masterinformation.php, which is later called by another PHP file.
<html>
<body>
<a href="http://www.masterbasha.com/">Home</a>
<a href=" http://www.masterbasha.com/Forums/">Forums</a>
<a href=" http://www.masterbasha.com/Blogs/">Blogs</a>
<a href=" http://www.masterbasha.com/Videos/">Videos</a>
<a href=" http://www.masterbasha.com/Training/">Training</a>
</body>
</html>
The above file is included as follows in another php file.
<html>
<body bgcolor="pink">
<?php include("masterinformation.php"); ?>
<h2><b>Welcome master basha Tutorials</b></h2>
<p>This page created by Mahaboob basha shaik.</p>
</body>
</html>
Use include with control structures: The include statement can be used with control structures such as
conditional statements and looping statements as shown below.
Example-01:
$test = “1”;
if ($test == “1”)
{
include ‘file.txt’;
}
Example-02:
<?php
for ($x = 1; $x<=3; $x++)
{
$incfile = “incfile”.$x.”.txt”;
echo “Attempting to include “.$incfile.”<br/>”;
include $incfile;
echo “<hr/>”;
}
?>
Q) How to
Validate Files in PHP.
PHP provides many
functions to discover information about files. Such as
1)
Checking for existing of a file.
2)
Checking whether it is a file or a
directory.
3)
Checking status of a file.
4)
Checking the size of a file
1.
Checking for Existence: The existence
of a file can be test 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: To
check whether it is a file or director we use is_file and is_dir () functions.
1) is_file( ): The is_file() function requires the file path and returns
a Boolean value
2) is_dir (). the is_dir() requires the
path to the directory and returns a Boolean value.
Example:
if (is_file(‘test.txt’)) {
echo “test.txt is a file!”;
}
if (is_dir(‘/tmp’)) {
echo “/tmp is a directory”;
}
3.
Checking the Status of a File:
1) The is_readable() function tells
whether it can read a file or not. The is_readable() function accepts the
file path as a string and returns a Boolean value:
Example:
if (is_readable(‘test.txt’)) {
echo “test.txt is readable”;
}
2) The is_writable( ) function tells
about 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”;
}
3) The is_executable( ) function tells
whether it can execute the given file,relying on either the file’s permissions
or its extension, depending on 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: 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’);
Q)
How to creating and deleting files in PHP.
1. Creating a
FILE: The touch( ) function is used to create a file. A string in touch ()
function, represents a file 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’);
2. Deleting a
FILE: we can delete or remove an existing file with the unlink() function.
unlink() accepts a file path:
unlink(‘myfile.txt’);
Q) What are the
different types of Opening modes of a File for Writing, Reading, or Appending.
1) Opening a
FILE:
The PHP fopen()
function is used to open a file. The basic syntax of this function can be given
with:
fopen(filename, mode)
The first parameter
passed to fopen() specifies the name of the file you want to open, and the
second parameter specifies in which mode the file should be opened. The most
common modes are read (r), write (w), and append (a). The different types of file modes are
|
Sr.No
|
Mode & Purpose
|
|
1
|
R: Opens the file for reading only. Places the file
pointer at the beginning of the file.
|
|
2
|
r+ : Opens the file for reading and
writing. Places the file pointer at the beginning of the file.
|
|
3
|
W: Opens the file for writing only. Places
the file pointer at the beginning of the file. and truncates the file to zero
length. If files does not exist then it attempts to create a file.
|
|
4
|
w+: Opens the file for reading and
writing only. Places the file pointer at the beginning of the file and
truncates the file to zero length. If files does not exist then it attempts
to create a file.
|
|
5
|
a: Opens the file for writing only. Places
the file pointer at the end of the file. If files does not exist then it
attempts to create a file.
|
|
6
|
a+: Opens the file for reading and writing only. Places the
file pointer at the end of the file. If files does not exist then it attempts
to create a file.
|
The following code is
used to open a file for reading:
$fp = fopen(“test.txt”, “r”);
The following code is
used to to open a file for writing:
$fp = fopen(“test.txt”, “w”);
The following code is
used to open a file for appending
(that is, to add data to the end of a file):
$fp = fopen(“test.txt”, “a”);
2) closing a
file: The fclose() function is used to close the file.
fclose($fp);
Example:
<?php
$file =
"data.txt";
if(file_exists($file)){
$handle = fopen($file, "r") or
die("ERROR: Cannot open the file.");
fclose($handle);
} else{
echo "ERROR: File does not
exist.";
}
?>
Q) Explain how to read
data from files in PHP.
PHP provides a number
of functions for reading data from files. These functions enable to read by the
byte, by the whole line, and even by the single character.
1. Reading
Lines from a File with fgets() and feof()
a) fgets():The fgets() function is used to read a line from an open file
Syntax
fgets(file,length)
|
Parameter
|
Description
|
|
file
|
Required. Specifies the file to read from
|
|
length
|
Optional. Specifies the number of bytes to read.
Default is 1024 bytes
|
b) feof () :The feof()
function checks if the "end-of-file" (EOF) has been reached.
Syntax:
feof(file);
2. Reading
Arbitrary Amounts of Data from a File with 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.
Syntax:
$chunk = fread($fp, 8);
3. Reading
Characters from a File with fgetc()
The fgetc() function is similar to fgets() except that it returns only a single
character from a file every time it is called. Because a character is always 1
byte in size, fgetc() doesn’t require a length argument.
Syntax:
$char = fgetc($fp);
4. Reading File
Contents with file_get_contents( ): using file_get_contents() to read an
entire file into a string.
Syntax:
$contents = file_get_contents(“file”);
Q) Explain briefly
about Writing or Appending to a FILE.
The processes for
writing to and appending to a file are the same—the difference lies in the mode
with which it call the fopen() function. When it write to a file,it use the mode argument “w”.
$fp = fopen(“test.txt”, “w”);
All subsequent writing
occurs from the start of the file. If the file doesn’t already exist, it is
created. If the file already exists, any prior content is destroyed and
replaced by the data to write. When it append to a file, it use the mode
argument “a”.
$fp = fopen(“test.txt”, “a”);
Any subsequent writes
to file are added to the end of existing content, but if it attempt to append
content to a nonexistent file, the file is created first.
1. fwrite() or
fputs(): The fwrite() writes to an open file. The function will stop at the end of
the file or when it reaches the specified length, whichever comes first. This
function returns the number of bytes written, or FALSE on failure.
Syntax
fwrite(file,string,length)
Example:
<?php
$filename = “test.txt”;
echo “<p>Writing to “.$filename.” ... </p>”;
$fp = fopen($filename, “w”) or
die(“Couldn’t open $filename”);
fwrite($fp, “Hello world\n”);
fclose($fp);
echo “<p>Appending to
“.$filename.” ...</p>”;
$fp = fopen($filename, “a”) or
die(“Couldn’t open $filename”);
fputs($fp, “And another thing\n”);
fclose($fp);
?>
2. file_put_contents():
it is used to write a string to a file. If the file doesn't exist, it will
be created. If the file already exists, it will be overwritten unless you have
used the FILE_APPEND flag to append the new content.
syntax:
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [,
resource $context ]] )
<?php
echo file_put_contents("subjects.txt","Physics, Maths,
Chemistry");
?>
Q) Explain working
with directories.
PHP provides many
functions for working with directories.
1.
mkdir():The mkdir() function
enables to create a directory. The mkdir() function requires a string that
represents the path to the directory to create and an octal number integer that
represents the mode to set for the directory.
Remember, you specify an octal (base 8) number using a leading 0; for
example, 0777 or 0400.
The mode argument has an effect only on UNIX systems. The mode should
consist of three numbers between 0 and 7, representing permissions for the
directory owner, group, and everyone, respectively.
Example:
mkdir(“testdir”, 0777); // global read/write/execute permissions
mkdir(“testdir”, 0755); // world/group: read/execute; owner:
read/write/execute
2.
rmdir(): The rmdir() function
enables to remove a directory from the filesystem. The rmdir() function
requires only a string representing the path to the directory to delete.
Example:
rmdir(“testdir”);
3.
opendir(): Before the contents of
a directory can read, it must first obtain a directory resource. To do it we
use with the opendir() function. The opendir() function requires a string that represents the path to the directory to
open.
Example:
$dh = opendir(“testdir”);
In this case, $dh is the directory handle of the open directory.
4.
readdir(): it is used 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. Note that readdir() returns only the names of its items, rather than full paths.
Q) Explain Opening
Pipes to and from Processes Using popen()
The PHP popen() function
is used to open a pipe to the program specified in the command parameter.
The popen() function is
used like this:
$file_pointer = popen(“some command”, mode)
The mode is either r (read) or w (write).
Example:
<?php
$file_handle = popen(“/path/to/fakefile 2>&1”, “r”);
$read =
fread($file_handle, 2096);
echo $read;
pclose($file_handle); ?>
Q) How to Running Commands with exec( )
The exec() function is
one of several functions use to pass commands to the shell. The exec() function
requires a string representing the path to the command 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).
exec(“/path/to/somecommand”, $output_array,
$return_val);
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 above program Using exec()
and ls to Produce a
Directory Listing
Q) 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>”;
?>
Q) Explain the Image-Creation
Process.
Creating an image with PHP
is not like creating an image with a drawing program (for example, Sumo Paint,
Corel DRAW, or Windows Draw). There’s no pointing and clicking or dragging
buckets of color into a predefined space to fill image. Similarly, there’s no
Save As functionality, in which drawing program automatically creates a GIF,
JPEG, PNG, and so on.
1. To create an image
you have to become the
drawing application.
2. As the programmer,
you must tell the PHP engine what to do at each step along the way.
3. You are responsible
for using the individual PHP functions to define colors, draw and fill shapes,
size and resize the image, and save the image as a specific file type.
4. Use the GD (Graphics
Drawing) library that provides tools for manipulating image data.
Q) What are the Necessary Modifications to PHP?
The GD library is a graphics
drawing library that provides tools for manipulating image data. To enable the use of the GD library at installation time. Linux/UNI X users
must add the following to the configure
parameters when preparing to build PHP.
--with-gd
Windows users who want to
enable GD simply have to activate php_gd2.dll as an extension in the php.ini
file.
When using the GD library,
you are limited to working with GIF files. Working with GIF files might suit
your needs perfectly, but if you want to create JPEG or PNG files on
Linux/UNIX, you must download and install the few libraries listed here and
make some modifications to your PHP installation. (These libraries are included
and enabled in a Windows installation.)
·
JPEG libraries, from http://www.ijg.org/.
·
PNG libraries, from http://www.libpng.org/pub/png/libpng.html.
·
If you are working with PNG files, you should also install the
zlib library, fromhttp://www.zlib.net/.
After installation,
Linux/UNIX users must again reconfigure and rebuild PHP by first adding the
following to the PHP configure parameters (assuming that you want to use all
three;
if not, just add the
applicable ones):
--with-jpeg-dir=[path to jpeg directory]
--with-png-dir=[path to PNG directory]
--with-zlib=[path to zlib directory]
After running the PHP
configure program again, you need to go through the make and make install
process . Your libraries should then be activated and ready for use.
Q) How to Draw a new image.
The basic PHP function used
to create a new image is called ImageCreate(), but creating an image is
not as simple as just calling the function. Creating an image is a stepwise
process and includes the use of several different PHP functions.
Creating an image begins with the ImageCreate()
function, but all this function does is set aside a canvas area for your new
image. The following line creates a drawing area that is 300 pixels wide by 300
pixels high:
$myImage =
ImageCreate(300,300);
With a canvas now defined,
you should next define a few colors for use in that new image. The following
examples define five such colors (black, white, red, green, and blue,
respectively), using the ImageColorAllocate() function and RGB values:
$black =
ImageColorAllocate($myImage, 0, 0, 0);
$white = ImageColorAllocate($myImage,
255, 255, 255);
$red = ImageColorAllocate($myImage, 255, 0, 0);
$green =
ImageColorAllocate($myImage, 0, 255, 0);
$blue =
ImageColorAllocate($myImage, 0, 0, 255);
Drawing Shapes and Lines
Several PHP functions can
assist you in drawing shapes and lines on your canvas:
·
ImageEllipse() is used to draw an ellipse.
·
ImageArc() is used to draw a partial ellipse.
·
ImagePolygon() is used to draw a polygon.
·
ImageRectangle() is used to draw a rectangle.
·
ImageLine() is used to draw a line.
Example:
<?php
//create the canvas
$myImage =
ImageCreate(300,300);
//set up some colors for use on the canvas
$black = ImageColorAllocate($myImage, 0, 0,
0);
$white = ImageColorAllocate($myImage, 255,
255, 255);
$red =
ImageColorAllocate($myImage, 255, 0, 0);
$green = ImageColorAllocate($myImage, 0, 255,
0);
$blue = ImageColorAllocate($myImage, 0, 0,
255);
//draw some rectangles
ImageRectangle($myImage, 15, 15, 95, 155,
$red);
ImageRectangle($myImage, 95, 155, 175, 295,
$white);
ImageRectangle($myImage, 175, 15, 255, 155,
$red);
//output the image to the browser
header (“Content-type: image/png”);
ImagePng($myImage);
//clean up after yourself
ImageDestroy($myImage);
?>
PHP has image functions
designed to fill areas as well:
·
ImageFilledEllipse() is used to fill an ellipse.
·
ImageFilledArc() is used to fill a partial ellipse.
·
ImageFilledPolygon() is used to fill a polygon.
·
ImageFilledRectangle() is used to fill a rectangle.
Q) Explain Getting Fancy with Pie Charts.
Let us creatre a Basic Pie
Chart as follows.
1: <?php
2: //create the canvas
3: $myImage = ImageCreate(300,300);
4:
5: //set up some colors for use on the canvas
6: $white = ImageColorAllocate($myImage, 255,
255, 255);
7: $red =
ImageColorAllocate($myImage, 255, 0, 0);
8: $green = ImageColorAllocate($myImage, 0, 255,
0);
9: $blue = ImageColorAllocate($myImage, 0, 0,
255);
10:
11: //draw a pie
12: ImageFilledArc($myImage, 100, 100, 200, 150,
0, 90, $red, IMG_ARC_PIE);
13: ImageFilledArc($myImage, 100, 100, 200, 150,
90, 180 , $green,
IMG_ARC_PIE);
14: ImageFilledArc($myImage, 100, 100, 200, 150,
180, 360 , $blue,
IMG_ARC_PIE);
15:
16: //output the image to the browser
17: header (“Content-type: image/png”);
18: ImagePng($myImage);
19:
20: //clean up after yourself
21: ImageDestroy($myImage);
22: ?>
Because the first defined
color is white, the color of the canvas will be white. Lines 12–14 use the ImageFilledArc() function, which has
several attributes:
·
The image identifier
·
The partial ellipse centered at x
·
The partial ellipse centered at y
·
The partial ellipse width
·
The partial ellipse height
·
The partial ellipse start point
·
The partial ellipse end point
·
Color
·
Style
ImageFilledArc($myImage,
100, 100, 200, 150, 180, 360 , $blue,
IMG_ARC_PIE);
The arc should be filled
with the defined color $blue and should use the
IMG_ARC_PIE style. The
IMG_ARC_PIE style is one of several built-in styles (actually, defined
constants) used in the display; this one says to create a rounded edge.
Q) How to Modifying Existing Images.
The process of creating
images from other images follows the same essential steps as creating a new
image—the difference lies in what acts as the image canvas.
we created a new canvas
using the ImageCreate()
function. When creating an image from a new image, you use the ImageCreateFrom*() family of functions.
we can create images from
existing GIFs, JPEGs, PNGs,
and plenty of other image types.
The functions used to create images from these formats are called ImageCreateFromGif(), ImageCreateFromJpg(), ImageCreateFromPng(), and so forth.
Example, shows the
base image.
1:<?php
2: //use existing image as a canvas
3: $myImage =
ImageCreateFromPng(“baseimage.png”);
4:
5: //allocate the color white
6: $white = ImageColorAllocate($myImage, 255,
255, 255);
7:
8: //draw on the new canvas
9: ImageFilledEllipse($myImage, 100, 70, 20, 20,
$white);
10:
ImageFilledEllipse($myImage, 175, 70, 20, 20, $white);
11:
ImageFilledEllipse($myImage, 250, 70, 20, 20, $white);
12:
13: //output the image to the
browser
14: header (“Content-type:
image/png”);
15: ImagePng($myImage);
//clean up after yourself
18: ImageDestroy($myImage);
19: ?>
Save this listing as imagefrombase.php and place it in the
document root of your web server. When accessed, it should look something like
Figure 14.6

Q) Explain Image Creation
from User Input.
In addition to creating
images from other images and drawing images on your own, you can create images
based on user input. No fundamental difference exists in how the scripts are
created except for the fact that you gather values from a form instead of
hard-coding them into your script.
creates an all-in-one form
and script that asks for user input for a variety of attributes ranging from
image size to text and background colors, as well as a message string. You are
introduced to the imagestring()
function, which is used to “write” a string onto an image
1:<?php
2: if (!$_POST) {
3: //show form
4: ?>
5: <!DOCTYPE html>
6: <html>
7: <head>
8: <title>Image Creation
Form</title>
9:
10: <style
type=”text/css”>
11: fieldset{border: 0;
padding: 0px 0px 12px 0px;}
12: fieldset label {margin-left: 24px;}
13: legend, label {font-weight:bold;}
14: </style>
15:
16: </head>
17: <body>
18: <h1>Create an
Image</h1>
19: <form method=”POST”
action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>”>
20:
21: <fieldset>
22: <legend>Image
Size:</legend><br/>
23: <label
for=”w”>W:</label>
24: <input type=”text”
id=”w” name=”w” size=”5” maxlength=”5” />
25: <label
for=”h”>H:</label>
26: <input type=”text”
id=”h” name=”h” size=”5” maxlength=”5” />
27: </fieldset>
28:
29: <fieldset>
30: <legend>Background
Color:</legend><br/>
31: <label
for=”b_r”>R:</label>
32: <input type=”text”
id=”b_r” name=”b_r” size=”3” maxlength=”3” />
33: <label
for=”b_g”>G:</label>
34: <input type=”text”
id=”b_g” name=”b_g” size=”3” maxlength=”3” />
35: <label
for=”b_b”>B:</label>
36: <input type=”text”
id=”b_b” name=”b_b” size=”3” maxlength=”3” />
37: </fieldset>
38:
39: <fieldset>
40: <legend>Text
Color:</legend><br/>
41: <label
for=”t_r”>R:</label>
42: <input type=”text”
id=”t_r” name=”t_r” size=”3” maxlength=”3” />
43: <label
for=”t_g”>G:</label>
44: <input type=”text”
id=”t_g” name=”t_g” size=”3” maxlength=”3” />
45: <label
for=”t_b”>B:</label>
46: <input type=”text”
id=”t_b” name=”t_b” size=”3” maxlength=”3” />
47: </fieldset>
48:
49: <p><label
for=”string”>Text String:</label>
50: <input type=”text”
id=”string” name=”string” size=”35” /></p>
51:
52: <p><label
for=”font_size”>Font Size:</label>
53: <select id=”font_size”
name=”font_size”>
54: <option
value=”1”>1</option>
55: <option
value=”2”>2</option>
56: <option
value=”3”>3</option>
57: <option
value=”4”>4</option>
<option value=”5”>5</option>
59: </select></p>
60:
61: <fieldset>
62: <legend>Text Starting
Position:</legend><br/>
63: <label
for=”x”>X:</label>
64: <input type=”text”
id=”x” name=”x” size=”3” maxlength=”3” />
65: <label
for=”y”>Y:</label>
66: <input type=”text”
id=”y” name=”y” size=”3” maxlength=”3” />
67: </fieldset>
68:
69: <button type=”submit”
name=”submit” value=”create”>Create Image</button>
70: </form>
71: </body>
72: </html>

73: <?php
74: } else {
75: //create image
76: //create the canvas
77: $myImage = ImageCreate($_POST[‘w’],
$_POST[‘h’]);
78:
79: //set up some colors
80: $background = ImageColorAllocate ($myImage,
$_POST[‘b_r’],
81: $_POST[‘b_g’], $_POST[‘b_b’]);
82: $text = ImageColorAllocate ($myImage,
$_POST[‘t_r’],
83: $_POST[‘t_g’], $_POST[‘t_b’]);
84:
85: // write the string at the top left
86: ImageString($myImage, $_POST[‘font_size’],
$_POST[‘x’],
87: $_POST[‘y’], $_POST[‘string’], $text);
88:
89: //output the image to the browser
90: header (“Content-type: image/png”);
91: ImagePNG($myImage);
92:
93: //clean up after yourself
94: ImageDestroy($myImage);
95: }
96: ?>

Comments
Post a Comment