PHP and Mysql - Unit-Iv
PHP and Mysql - Unit-Iv
Include
Require
Advantage:
Code Reusability:
By the help of include and require construct, we can reuse HTML code or PHP
script in many PHP scripts.
PHP include is used to include file based on given path. Let us see a simple PHP
include example.
File: footer.php
<?php
?>
File: include1.html
<html>
<body>
</body>
</html>
Require():
The include() and require() statement allow you to include the code contained
in a PHP file within another PHP file. Including a file produces the same result
as copying the script from the file specified and pasted into the location where
it is called.
You can save a lot of time and work through including files – just store a block
of code in a separate file and include it wherever you want by include() and
require() statement instead of typing the entire block of code multiple times.
Example:
<html>
<head>
</head>
<body>
</body>
</html>
file_exists():
Example:
<?php
$flg=file_exists(“Hello.txt”);
If($flg==true)
echo(“File Exist”);
else
clearstatcache();
?>
is_file():
It returns TRUE if the given File is exists and it is a Regular File, otherwise
FALSE.
It can’t check a Directory File or a Special File.
Regular File is available in different Flavors like
o Readable File
o A Binary File
o Image File
o Compressed File
o Symbolic Link, etc.,
It’s a Case Sensitive.
The PHP clearstatcache() function clears the File Status Cache used by
PHP is_file() function.
Example:
<?php
$flg=is_file(“Hello.txt”);
If($flg==true)
else
clearstatcache();
?>
Is_readable():
It checks whether the file has a Readable permission then it returns
TRUE on success otherwise FALSE.
It’s a Case – Sensitive.
It accepts only the Internal representation of the File Path like
(“./Hello.txt”) not like (“https://www.zameer.com/Tutor/Hello.txt”)
The PHP clearstatcache() function clears the File Status Cache used by
PHP is_readable() function.
Example:
<?php
$flg=is_readable(“./Hello.txt”);
If($flg==true)
echo(“File is Readable”);
else
clearstatcache();
?>
is_writable():
It checks whether the file has a Writable permission then it returns TRUE
on success otherwise FALSE.
It’s a Case Sensitive.
Example:
<?php
$flg=is_writable(“Hello.txt”);
If($flg==true)
echo(“File is Writable”);
else
clearstatcache();
?>
is_executable():
Example:
<?php
$flg=is_executable(“./Hello.txt”);
If($flg==true)
{
echo(“File is Executable”);
else
clearstatcache();
?>
filesize():
It returns the Size of the File in Bytes only if Success otherwise FALSE
and a PHP Warning.
The given URL must be referred in an Internal representation like
(“./Hello.txt”) not like (“https://www.zameer.com/Tutor/Hello.txt”)
It returns the accurate size of the File in Bytes But if the size of the file
is greater than 100 MB then result may not be accurate.
The PHP clearstatcache() function clears the File Status Cache used by
PHP filesize() function.
Example:
<?php
$flg=filesize(“./Hello.txt”);
echo($flg);
clearstatcache();
?>
3. Discuss about Creating and Deleting Files.
Creating file:
You can create a file 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”);
Deleting File:
You can remove an existing file with the unlink() function, as did the touch()
function, unlink() accepts a file path:
unlink(“myfile.txt”);
Before you can work with a file, you must first open it for reading or writing, or
for performing both tasks. PHP provides the fopen() function for doing so, 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 fopen() function returns a file resource you use later to work with the
open file.
$fp=fopen(“test.txt”,”r”);
Or, you can use a logical operator to end execution if an essential file
can’t be opened:
If the fopen() function returns true, the rest of the expression is not parsed,
and the die() function (which writes a message to the browser and ends the
script) is never reached. Otherwise, the right side of the or operator is parsed,
and the die() function is called.
Assuming that all is well and you go on to work with your open file, you should
remember to close it when you finish. You can do so by calling fclose(), which
requires the file resource returned from a successful fopen() call as its
argument:
fclose($fp);
PHP provides several functions for reading data from files. These functions
enable you to read by the byte, by the whole line, and even by the single
character.
When you open a file for reading, you might want to access it line by line. To
read a line from an open file, you can use the fgets() function, which requires
the file resource returned from fopen() as its argument. You must also pass
fgets() 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. 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:
$line=fgets($fp,1024);
Although you can read lines with fgets(), you need some way to tell
when you reach 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. The feof()
function requires a file resource as its argument:
feof($fp);
Example Program:
<?php
$filename=”test.txt”;
while(!feof($fp))
$line=fgets($fp,1024);
echo $line.”<br>”;
?>
The fread() function can be used to read a specified number of characters from
a file. The basic syntax of this function can be given with.
Example:
<?php
$file = "data.txt";
if(file_exists($file))
fclose($handle);
echo $content;
else
?>
The above example will produce the following output:
The fread() function can be used in conjugation with the filesize() function to
read the entire file at once. The filesize() function returns the size of the file in
bytes.
Example:
<?php
$file = "data.txt";
if(file_exists($file))
fclose($handle);
echo $content;
else
?>
The easiest way to read the entire contents of a file in PHP is with
the readfile() function. This function allows you to read the contents of a file
without needing to open it. The following example will generate the same
output as above example:
<?php
$file = "data.txt";
if(file_exists($file))
else
?>
<?php
$file = "data.txt";
if(file_exists($file))
echo $content;
else
?>
Similarly, you can write data to a file or append to an existing file using the
PHP fwrite() function. The basic syntax of this function can be given with:
The fwrite() function takes two parameter — A file handle and the string of
data that is to be written, as demonstrated in the following example:
<?php
$file = "note.txt";
$data = "The quick brown fox jumps over the lazy dog.";
fclose($handle);
?>
In the above example, if the "note.txt" file doesn't exist PHP will automatically
create it and write the data. But, if the "note.txt" file already exist, PHP will
erase the contents of this file, if it has any, before writing the new data,
however if you just want to append the file and preserve existing contents just
use the mode a instead of w in the above example.
<?php
$file = "note.txt";
$data = "The quick brown fox jumps over the lazy dog.";
?>
If the file specified in the file_put_contents() function already exists, PHP will
overwrite it by default. If you would like to preserve the file's contents you can
pass the special FILE_APPEND flag as a third parameter to
the file_put_contents() function. It will simply append the new data to the file
instead of overwitting it. Here's an example:
<?php
$file = "note.txt";
$data = "The quick brown fox jumps over the lazy dog.";
?>
PHP includes a set of directory functions to deal with the operations, like,
listing directory contents, and create/ open/ delete specified directory and etc.
These basic functions are listed below.
<?php
?>
This function accepts four arguments as specified. Among them, the first
argument is mandatory, whereas, the remaining set of arguments is optional.
$mode: The mode parameter accepts octal values on which the accessibility of
the newly created directory depends.
$recursive: This parameter is a flag and has values either true or false, that
allow or refuse to create nested directories further.
This function will return boolean data, that is, true on successful
execution, false otherwise.
For listing the contents of a directory, we require two of the above-listed PHP
directory functions, these are, opendir() and readdir(). There are two steps in
directory listing using the PHP program.
<?php
opendir($directory_path, $context);
?>
Unlike PHP mkdir() returning boolean value, this function will return resource
data as like as fopen(), mysql_query() and etc. After receiving the resource
identifier returned by this function, then only we can progress with the
subsequent steps to read, rewind, or close the required directory with the
reference of this resource id.
Otherwise, a PHP error will occur for indicating to the user, that the resource id
is not valid.
For performing this step, we need to call readdir() function recursively until the
directory handle reaches the end of the directory. For that, we need to specify
the resource-id returned while invoking opendir(), indicated as directory
handle.
PHP readdir() will return string data on each iteration of the loop, and this
string will be the name of each item stored in the directory with its
corresponding extension. For example,
<?php
$directory_handle = opendir($directory_path);
?>
And, thereby executing the above code sample, we can list the content of a
directory as expected.
<?php
$directory_handle = opendir($directory_path);
...
...
closedir($directory_handle);
?>
Removing Directory
We have seen in the previous article about how to delete a file from a
directory using PHP unlink(). Similarly, for removing the entire directory, PHP
provides a function named as rmdir() which accepts the same set of
arguments, as mkdir(). These are, the $directory_path and $context(Optional)
as stated below.
<?php
?>
But, this function will remove the directory, if and only if it is empty. For
removing the non-empty directory, we need to create a user define function
that recursively calls unlink() function to remove each file stored in the
directory to be deleted.
$file_pointer=popen(“some command”,mode);
Example program:
<?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 a scalar variable that will
contain the return value (1or 0).
For Example:
exec(“/path/to/somecommand”,$output_array,$return_val);
Program:
<?php
exec(“Is -al.”,$output_array,$return_val);
echo “Returned”.$return_val.”<br>”;
foreach($output_array as $o)
echo $o.”\n”;
?>
system():
system(“/path/to/somecommand’,$return_val);
The system() function differs from exec() in that it outputs information directly
to the browser, without programmatic intervention.
passthru():
The passthru() function follows the syntax of the system() function, but
it behave 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.
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 your image.
Similarly, there’s no Save As functionality, in which your drawing
program automatically creates a GIF, JPEG, PNG, and so on, just because
you ask it to do so.
Instead, you 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.
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:
Several PHP functions can assist you in drawing shapes and lines on your
canvas:
Using these functions requires thinking ahead because you must set up
the points where you want to start and stop the drawing that occurs. Each of
these functions uses x-axis and y-axis coordinates as indicators of where to
start drawing on the canvas. You must also define how far along the x-axis and
y-axis you want the drawing to occur.
For example, the following line draws a rectangle on the canvas beginning at
point (15,15) and continuing on for 80 pixels horizontally and 140 pixels
vertically, so that the lines end at point (95,155). In addition, the lines will be
drawn with the color red, which has already been defined in the variable $red.
If you want to draw another rectangle of the same size but with white lines,
beginning at the point where the previous rectangle stopped, you would use
this code:
Finally, to add another red rectangle aligned with the first, but beginning at the
rightmost point of the white rectangle, use the following:
Example:
<?php
//create the canvas
$myImage = ImageCreate(300,300);
ImagePng($myImage);
ImageDestroy($myImage);
?>
The output produced only outlines of rectangles. PHP has image functions
designed to fill areas as well:
Example:
<?php
$myImage = ImageCreate(300,300);
ImagePng($myImage);
ImageDestroy($myImage);
?>
Example:
<?php
$myImage = ImageCreate(300,300);
//draw a pie
IMG_ARC_PIE);
IMG_ARC_PIE);
ImagePng($myImage);
ImageDestroy($myImage);
?>
ImageFilledArc()
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. Previously, you created a new canvas using the
ImageCreate() function. When creating an image from a new image, you
use the ImageCreateFrom*() family of functions.
You 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
<?php
ImageJpeg($myImage);
ImageDestroy($myImage);
?>
Example:
<?php
if (!$_POST)
//show form
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<h1>Create an Image</h1>
<fieldset>
<legend>Image Size:</legend><br/>
<label for="w">W:</label>
<label for="h">H:</label>
</fieldset>
<fieldset>
<legend>Background Color:</legend><br/>
<label for="b_r">R:</label>
<label for="b_g">G:</label>
<input type="text" id="b_g" name="b_g" size="3" maxlength="3" />
<label for="b_b">B:</label>
</fieldset>
<fieldset>
<legend>Text Color:</legend><br/>
<label for="t_r">R:</label>
<label for="t_g">G:</label>
<label for="t_b">B:</label>
</fieldset>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></p>
<fieldset>
<label for="x">X:</label>
<label for="y">Y:</label>
</fieldset>
</form>
</body>
</html>
<?php
else
//create image
$_POST['b_g'], $_POST['b_b']);
$_POST['t_g'], $_POST['t_b']);
// write the string at the top left
type: image/jpg");
ImageJPEG($myImage);
ImageDestroy($myImage);
?>