0% found this document useful (0 votes)
30 views33 pages

PHP and Mysql - Unit-Iv

Unit4 Php

Uploaded by

gantarojamani3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views33 pages

PHP and Mysql - Unit-Iv

Unit4 Php

Uploaded by

gantarojamani3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit-4

Working with Files and Directories

1. Discuss about Including Files with include () Function.

A. Including a PHP File into Another PHP File:


PHP allows you to include file so that a page content can be reused many
times. There are two ways to include file in PHP.

 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 example:

PHP include is used to include file based on given path. Let us see a simple PHP
include example.

File: footer.php

<?php

Echo “Copy right by G.R.MANI”;

?>

File: include1.html

<html>

<body>

<h1> Welcome to my home page </h1>

<p> Some text </p>

<p> Some more text </p>


<?php include “footer.php”;?>

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

<?php require “footer.php”;?>

<html>

<head>

<title> Mypage </title>

</head>

<body>

<h1> Welcome to Our Website </h1>

<p> Here you will find lost of useful information </p>

<? php include “footer.php”;?>

</body>

</html>

2. Discuss about Validating Files.


A. PHP provides many functions to help you to discover information about files
on your system. Some of the most useful functions are discussed below:

file_exists():

 It is used to check whether the File or Directory is Exist.


 It is mostly used prior to the File Read or Write operation to check the
file is Exist.
 It returns TRUE. If the File or Directory is Exist otherwise FALSE.
 It’s a Case Sensitive.
 The PHP clearstatcache() function clears the File Status Cache used by
PHP file_exists() function.

Example:

<?php

$flg=file_exists(“Hello.txt”);

If($flg==true)

echo(“File Exist”);

else

echo(“File doesn’t Exist”);

/* Clears the File Status Cache */

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)

echo(“Given File is a Regular File”);

else

echo(“Given File is not a Regular File”);

/* Clears the File Status Cache */

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

echo(“Non Readable File”);

/* Clears the File Status Cache */

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

echo(“Non Writable File”);

/* Clears the File Status Cache */

clearstatcache();

?>

is_executable():

 It checks whether the file has a Executable 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_executable() function.

Example:

<?php

$flg=is_executable(“./Hello.txt”);

If($flg==true)
{

echo(“File is Executable”);

else

echo(“Non Executable File”);

/* Clears the File Status Cache */

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

/* Clears the File Status Cache */

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

4. Discuss about 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. 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.

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

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

 You use the following to open a file for writing:


$fp=fopen(“test.txt”,”w”);
 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”);
The fopen() function returns false if the file cannot be opened for any reason.
Therefore, it’s a good idea to test the function’s return value before
proceeding to work with it. You can do so with an if statement:
If($fp=fopen(“test.txt”,”w”))

// do something with the $fp resource

Or, you can use a logical operator to end execution if an essential file
can’t be opened:

($fp=fopen(“test.txt”,”w”)) or die(“Coludn’t open file, sorry”);

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

The resource that became available ($fp) is now unavailable to you.

5. Discuss about Reading from Files, writing or Appending to a file.

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.

Reading Lines from a File with fgets() and feof():

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

// where $fp is the file resource returned by fopen().

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

// where $fp is the file resource returned by fopen()

Example Program:

<?php

$filename=”test.txt”;

$fp=fopen($filename,”r”) or die(“Couldn’t open $filename”);

while(!feof($fp))

$line=fgets($fp,1024);

echo $line.”<br>”;

?>

Reading from Files with PHP fread() Function:

Reading Fixed Number of Characters:

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.

fread(file handle, length in bytes)


This function takes two parameter — A file handle and the number of bytes to
read. The following example reads 20 bytes from the "data.txt" file including
spaces. Let's suppose the file "data.txt" contains a paragraph of text "The quick
brown fox jumps over the lazy dog."

Example:

<?php

$file = "data.txt";

// Check the existence of file

if(file_exists($file))

// Open the file for reading

$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");

// Read fixed number of bytes from the file

$content = fread($handle, "20");

// Closing the file handle

fclose($handle);

// Display the file content

echo $content;

else

echo "ERROR: File does not exist.";

?>
The above example will produce the following output:

The quick brown fox

Reading the Entire Contents of a File

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

// Check the existence of file

if(file_exists($file))

// Open the file for reading

$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");

// Reading the entire file

$content = fread($handle, filesize($file));

// Closing the file handle

fclose($handle);

// Display the file content

echo $content;

else

echo "ERROR: File does not exist.";


}

?>

The above example will produce the following output:

The quick brown fox jumps over the lazy dog.

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

// Check the existence of file

if(file_exists($file))

// Reads and outputs the entire file

readfile($file) or die("ERROR: Cannot open the file.");

else

echo "ERROR: File does not exist.";

?>

The above example will produce the following output:

The quick brown fox jumps over the lazy dog.


Another way to read the whole contents of a file without needing to open it is
with the file_get_contents() function. This function accepts the name and path
to a file, and reads the entire file into a string variable. Here's an example:

<?php

$file = "data.txt";

// Check the existence of file

if(file_exists($file))

// Reading the entire file into a string

$content = file_get_contents($file) or die("ERROR: Cannot open the file.");

// Display the file content

echo $content;

else

echo "ERROR: File does not exist.";

?>

Writing the Files Using PHP fwrite() Function

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:

fwrite(file handle, string)

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

// String of data to be written

$data = "The quick brown fox jumps over the lazy dog.";

// Open the file for writing

$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");

// Write data to the file

fwrite($handle, $data) or die ("ERROR: Cannot write the file.");

// Closing the file handle

fclose($handle);

echo "Data written to the file successfully.";

?>

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.

An alternative way is using the file_put_contents() function. It is counterpart


of file_get_contents() function and provides an easy method of writing the
data to a file without needing to open it. This function accepts the name and
path to a file together with the data to be written to the file. Here's an
example:

<?php

$file = "note.txt";

// String of data to be written

$data = "The quick brown fox jumps over the lazy dog.";

// Write data to the file


file_put_contents($file, $data) or die("ERROR: Cannot write the file.");

echo "Data written to the file successfully.";

?>

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

// String of data to be written

$data = "The quick brown fox jumps over the lazy dog.";

// Write data to the file

file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the


file.");

echo "Data written to the file successfully.";

?>

6. Discus about Working with Directories.

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.

 mkdir(): To make new directory.


 opendir(): To open directory.
 readdir(): To read from a directory after opening it.
 closedir(): To close directory with resource-id returned while opening.
 rmdir(): To remove directory.

Creating New Directory:


For creating a new directory using PHP programming script, mkdir() function is
used, and, the usage of this function is as follows.

<?php

mkdir($directory_path, $mode, $recursive_flag, $context);

?>

This function accepts four arguments as specified. Among them, the first
argument is mandatory, whereas, the remaining set of arguments is optional.

$directory_path: By specifying either relative and absolute path, a new


directory will be created in such location if any, otherwise, will return an error
indicating that there are no such locations.

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

$context: As similar as we have with PHP unlink() having a stream for


specifying protocols and etc.

This function will return boolean data, that is, true on successful
execution, false otherwise.

Listing Directory Content in PHP

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.

Step 1: Opening the directory.

Step 2: Reading content to be listed one by one using a PHP loop.

Step 1: Opening Directory Link


As its name, opendir() function is used to perform this step. And, it has two
arguments, one is compulsory for specifying the path of the directory, and the
other is optional, expecting stream context if any. The syntax will be,

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

Step 2: Reading Directory Content

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

while ($directory_item = readdir($directory_handle)) {

echo $directory_item . "<br>";

?>
And, thereby executing the above code sample, we can list the content of a
directory as expected.

Closing Directory Link

Once the directory link is opened to perform a set of dependent operations


like reading directory content, we need to close this link after completing the
related functionalities required. For example,

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

rmdir($directory_path, $mode, $recursive_flag, $context);

?>

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.

7. Discuss about Open Pipes to and from Process Using popen()?


The PHP popen() function is used to create a new pipe connection for the
program that was specified by command parameters.

Opening pipes to and from processes using popen():

The popen() function is used like this:

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

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

Example program:

<?php

$file_handle=popen(“/path/to/fakefile 2>&1”,”r”);

$read=fread($file_handle,2096);

echo $read;

pclose($file_handle);

?>

 We first call the utilizes the popen() function in line 2, attempting to


open a file for reading.
 In line 3, any error message stored in the $file_handle pointer is read
and printed to the screen in line 4.
 Finally, line 5 closes the file pointer opened in line 2.
 You will see the following error message displayed on your screen:

Sh:/path/to/fakefile: no such file or directory

8. Discuss about 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 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”;

?>

 line 2 issues the Is command using the exec() function.


 The output of the command is placed into the $output_array array and
the return value in the $return_val variable.
 Line 3 simply prints the return values, whereas the foreach loop in lines
4 – 6 prints out each element in $output_array.

9. Discuss about Running Commands with system() or passthru().

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.

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.

Working with Images

10. Discuss about 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 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.

11. Discuss about Necessary Modifications to PHP.

 Current versions of the PHP distribution include a bundled version of


Thomas Boutell’s GD graphics library.
 The inclusion of this library eliminates the need to download and install
several third – party libraries, but this library needs to be activated at
installation time.
 To enable the use of the GD library at installation time, Linux/Unix users
must add the following to the configure parameters when preparing to
build PHP:
--with-gd
 After running the PHP configure program again, you must go through
the make and make install process through “Installing and Configuring
PHP.” 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.
o JPEG libraries, from http://www.ijg.org/
o PNG libraries, from http://www.libping.org/pub/png/libpng.html
o If you are working with PNG files, you should also install the
zlib library, from http://www.zlib.net/.

12. Discuss about Drawing 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.

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.

ImageRectangle($myImage, 15, 15, 95, 155, $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:

ImageRectangle($myImage, 95, 155, 175, 295, $white);

Finally, to add another red rectangle aligned with the first, but beginning at the
rightmost point of the white rectangle, use the following:

ImageRectangle($myImage, 175, 15, 255, 155, $red);

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

?>

Using a Color Fill

The output produced only outlines of rectangles. 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.

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

ImageFilledRectangle($myImage, 15, 15, 95, 155, $red);

ImageFilledRectangle($myImage, 95, 155, 175, 295, $white);

ImageFilledRectangle($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);

?>

13. Discuss about Getting Fancy with Pie Charts.


You can use this same sequence of events to expand your scripts to create
charts and graphs, using either static or dynamic data for the data points draws
a basic pie chart.

Example:

<?php

//create the canvas

$myImage = ImageCreate(300,300);

//set up some colors for use on the canvas

$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 a pie

ImageFilledArc($myImage, 100, 100, 200, 150, 0, 90, $red, IMG_ARC_PIE);

ImageFilledArc($myImage, 100, 100, 200, 150, 90, 180 , $green,

IMG_ARC_PIE);

ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue,

IMG_ARC_PIE);

//output the image to the browser

header ("Content-type: image/png");

ImagePng($myImage);

//clean up after yourself

ImageDestroy($myImage);

?>
ImageFilledArc()

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

14. Discuss about 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. 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

//use existing image as a canvas

$myImage = ImageCreateFromJpeg("1 001.jpg");

//allocate the color white

$white = ImageColorAllocate($myImage, 255, 255, 255);

//draw on the new canvas

ImageFilledEllipse($myImage, 100, 70, 20, 20, $white);


ImageFilledEllipse($myImage, 175, 70, 20, 20, $white);

ImageFilledEllipse($myImage, 250, 70, 20, 20, $white);

//output the image to the browser

header ("Content-type: image/jpg");

ImageJpeg($myImage);

//clean up after yourself

ImageDestroy($myImage);

?>

15. Discuss about 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.

Example:

<?php

if (!$_POST)

//show form

?>

<!DOCTYPE html>

<html>
<head>

<title>Image Creation Form</title>

<style type="text/css">

fieldset{border: 0; padding: 0px 0px 12px 0px;}

fieldsetlabel {margin-left: 24px;}

legend, label {font-weight:bold;}

</style>

</head>

<body>

<h1>Create an Image</h1>

<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<fieldset>

<legend>Image Size:</legend><br/>

<label for="w">W:</label>

<input type="text" id="w" name="w" size="5" maxlength="5" />

<label for="h">H:</label>

<input type="text" id="h" name="h" size="5" maxlength="5" />

</fieldset>

<fieldset>

<legend>Background Color:</legend><br/>

<label for="b_r">R:</label>

<input type="text" id="b_r" name="b_r" size="3" maxlength="3" />

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

<input type="text" id="b_b" name="b_b" size="3" maxlength="3" />

</fieldset>

<fieldset>

<legend>Text Color:</legend><br/>

<label for="t_r">R:</label>

<input type="text" id="t_r" name="t_r" size="3" maxlength="3" />

<label for="t_g">G:</label>

<input type="text" id="t_g" name="t_g" size="3" maxlength="3" />

<label for="t_b">B:</label>

<input type="text" id="t_b" name="t_b" size="3" maxlength="3" />

</fieldset>

<p><label for="string">Text String:</label>

<input type="text" id="string" name="string" size="35" /></p>

<p><label for="font_size">Font Size:</label>

<select id="font_size" name="font_size">

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

<legend>Text Starting Position:</legend><br/>

<label for="x">X:</label>

<input type="text" id="x" name="x" size="3" maxlength="3" />

<label for="y">Y:</label>

<input type="text" id="y" name="y" size="3" maxlength="3" />

</fieldset>

<button type="submit" name="submit" value="create">Create


Image</button>

</form>

</body>

</html>

<?php

else

//create image

//create the canvas

$myImage = ImageCreate($_POST['w'], $_POST['h']);

//set up some colors

$background = ImageColorAllocate ($myImage, $_POST['b_r'],

$_POST['b_g'], $_POST['b_b']);

$text = ImageColorAllocate ($myImage, $_POST['t_r'],

$_POST['t_g'], $_POST['t_b']);
// write the string at the top left

ImageString($myImage, $_POST['font_size'], $_POST['x'],

$_POST['y'], $_POST['string'], $text);

//output the image to the

browser header ("Content-

type: image/jpg");

ImageJPEG($myImage);

//clean up after yourself

ImageDestroy($myImage);

?>

You might also like