unit-4
Q) How to include files in PHP documents.
Include statement enables to incorporate other files (usually
other PHP scripts) into PHP documents. The
include (or require) statement takes all the text/code/markup that exists in
the specified file and copies it into the file that uses the include statement.
Syntax:
include 'filename';
or
require 'filename';
or
require 'filename';
Example:
footer.php
<?php
echo "<p>Welcome to my Website</p>";
?>
echo "<p>Welcome to my Website</p>";
?>
Xyz.php
<html><body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php
<p>Some text.</p>
<p>Some more text.</p>
<?php
include 'footer.php';
?>
</body>
</html>
</body>
</html>
The include statement can be used with control structures
such as conditional statements and looping statements.
Example-conditional statement:
$test = “1”;
if ($test == “2”) {
include ‘file.txt’; //
won’t be included
}
Example-looping statement:
<?php
for ($x = 1; $x<=3; $x++) {
$incfile = “incfile”.$x.”.txt”;
echo “Attempting to
include “.$incfile.”<br/>”;
include $incfile;
echo “<hr/>”;
}
?>
Q) How to move files from one server to another server
When
project move to a new server, we have to change a hundred or more include paths, if this is
hard-coded in a hundred or more files. we can escape this fate by setting the include_path directive in php.ini file:
include_path .:/home/user/bob/htdocs/project4/lib/
The include_path value can include as
many directories as you want, separated by colons (semicolons in Windows). The
order of the items in the include_path directive determines the order in which the directories
are searched for the named file. The first dot (.) before the first colon indicates “current directory,”
and should be present.
Q) How to Validate Files in PHP.
PHP
provides many functions to help 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?:
is_file( ) and is_dir ( ): To check
whether it is a file or director we use is_file and is_dir () functions. The is_file() function requires the file path and returns a Boolean
value and 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.
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’);
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.
Opening a FILE: PHP provides the fopen() function to open a
file and this function requires a string that contains the file path, followed
by a string that contains the mode in which the file is to be opened. The most
common modes are read (r), write (w), and append (a).
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”);
closing a file: using fclose() we can close the file.
fclose($fp);
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. fgets() and feof():
fgets(): The fgets() function is used to read a line from an open file. The
fgets() function reads the
file until it reaches a newline character (“/n”), the number of bytes specified in the length argument,
or the end of the file—whichever comes first:
In fgets() function we can pass an integer as a second argument, which specifies the
number of bytes that the function should read if it doesn’t first encounter a
line end or the end of the file.
$line = fgets($fp,
1024);
feof(): The feof() function is
used to tell that it reaches to the end of the file. The feof() function does this by
returning true when the end of the
file has been reached and false otherwise.
Example: feof($fp);
2. fread(): Rather than reading
text by the line, we can read a file in arbitrarily defined chunks. The fread() function accepts a
file resource as an argument, as well as the number of bytes want to read. The fread() function returns the amount
of data requested, unless the end of the file is reached first.
Example:
$chunk = fread($fp,
8);
3. 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.
Example:
$char = fgetc($fp);
4. file_get_contents( ): using
file_get_contents() to read an entire file into a string.
Example:
$contents =
file_get_contents(“test.txt”);
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.
Writing to a File with fwrite() or fputs()
The fwrite() function
accepts a file resource and a string, and then writes the string to the file.
The fputs() function works in exactly the same way:
fwrite($fp, “hello world”);
fputs($fp, “hello world”);
<?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);
?>
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.
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(): The opendir() function requires a string that represents the path to
the directory to open. The opendir() function returns a directory handle unless the directory
isn’t present or readable; in that case, it returns false:
Example:
$dh =
opendir(“testdir”);
In this case, $dh is the directory
handle of the open directory.
4.
readdir(): 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()
We can open a pipe to
a process using the popen() function. 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) Explain the following Running Commands
a) exec( )
b) system() or passthru()
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
System(): 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
Working with Images
PHP has
many built-in functions for dynamically creating and manipulating images.
Popular uses include the creation of charts and graphs and the modifications of
existing images to display watermarks.
Understanding 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.
Instead, we
have to become the drawing application. As the
programmer, you must tell the PHP engine what to do at each step along the way.
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.
Example:
<?php
$my_img = imagecreate( 200, 80 );
$background = imagecolorallocate( $my_img, 0, 0, 255 );
$text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 4, 30, 25, "thesitewizard.com", $text_colour );
imagesetthickness ( $my_img, 5 );
imageline( $my_img, 30, 45, 165, 45, $line_colour );
header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );
?>
$my_img = imagecreate( 200, 80 );
$background = imagecolorallocate( $my_img, 0, 0, 255 );
$text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 4, 30, 25, "thesitewizard.com", $text_colour );
imagesetthickness ( $my_img, 5 );
imageline( $my_img, 30, 45, 165, 45, $line_colour );
header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );
?>
Q) How to
Draw a new image.
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
$myImage =
ImageCreate(300,300);
$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);
ImageRectangle($myImage, 15, 15, 95, 155, $red);
ImageRectangle($myImage, 95, 155, 175, 295,
$white);
ImageRectangle($myImage, 175, 15, 255, 155,
$red);
header
(“Content-type: image/png”);
ImagePng($myImage);
ImageDestroy($myImage);
?>
Comments
Post a Comment