0% found this document useful (0 votes)
5 views24 pages

Unit - Iv (DS & Stat)

This document covers various aspects of working with files and directories in PHP, including file creation, deletion, validation, and reading/writing operations. It also discusses image handling and directory management functions such as mkdir(), rmdir(), and scandir(). Key PHP functions like include(), fopen(), fwrite(), fread(), and various validation functions are highlighted for effective file manipulation.

Uploaded by

Divya Gurram
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)
5 views24 pages

Unit - Iv (DS & Stat)

This document covers various aspects of working with files and directories in PHP, including file creation, deletion, validation, and reading/writing operations. It also discusses image handling and directory management functions such as mkdir(), rmdir(), and scandir(). Key PHP functions like include(), fopen(), fwrite(), fread(), and various validation functions are highlighted for effective file manipulation.

Uploaded by

Divya Gurram
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/ 24

UNIT – IV

SYLLABUS
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, 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.

………………………………………………………………………………………………….
.

Working With Files and Directories


File:
 A file is a collection of data or information that’s stored and organized under a
specific name on a computer or other digital storage device.
 Files can contain text, images, programs, soreadsheets, databases, or any other type of
data. They are managed by the operating system and are accessed, modified, or
deleted by users or applications.
 Ex: documents, pdf, pictures, …..etc.

Including Files with include():


 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.
 Including files is very useful when you want to include the same PHP, HTML, or
text on multiple pages of a website.
 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 included one PHP file into
another PHP file.
They are : i.) The include() function
ii.) The require() function
 This is a strong point of PHP which helps in creating functions headers, footers, or
elements that can be reused on multiple pages.
Uses of include() and require():

 include(): include will only produce a warning (E_WARNING) and the


script will continue

 require(): require will produce a fatal error (E_COMPILE_ERROR) and


stop the script

Syntax:

include 'filename';

or

require 'filename';

Source Code:

Vars.php

<?php
$color='red';
$car='BMW';
?>

inc.php

<html>

<body>

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

<?php include 'vars.php';

echo "I have a $color $car.";

?>

</body>

</html>

Output:
…………………………………………………………………………………………………..

Validating Files
 PHP provides many functions to help you to discover information about files on
your system.
 Some of the most useful functions are given below:
They are: i.) is_file()
ii.) is_dir()
iii.) is_readable()
iv.) is_writable()
v.) is_executable()
vi.) filesize()
 In PHP, the functions is_file(), is_dir(), is_readable(), is_writable(), and
is_executable() and filesize() are used to perform various file and directory
validations.

 is_file() - Checks whether a file is a regular file or not.

Syntax:

is_file( filename );
Source Code:

$filename = 'path/to/file.txt';

if (is_file($filename)) {

// File exists and is a regular file

echo “$filename is a regular file”;

else

// File doesn't exist or is not a regular file

echo “ $filename is not a regular file or doesn’t exist”;

 2.) is_dir() :

is_dir($dirname)- Checks if the given $dirname exists and is a directory.

Source Code:

$dirname = 'path/to/directory';
if (is_dir($dirname)) {
// Directory exists
echo "$dirname is exists";
} else {
// Directory doesn't exist or is not a directory
echo "$dirname is not exist";
}
 3.) is_readable():
is_readable($filename) - Checks if the file specified by $filename exists and is
readable.

Source Code:

$filename = 'path/to/file.txt';

if (is_readable($filename)) {

// File exists and is readable

echo “ $filename is readable”;

} else {
// File doesn't exist or is not readable

echo “$filename is not readable”;

 4.) is_writable()

is_writable($filename) - Checks if the file specified by $filename exists and is


writable.

Source Code:

$filename = 'path/to/file.txt';

if (is_writable($filename)) {

// File exists and is writable

echo “$filename is writable”;

} else {

// File doesn't exist or is not writable

echo “$filename is not writable”;

 5.) is_executable()

is_executable($filename) - Checks if the file specified by $filename exists and is


executable.

Source Code:

$filename = 'path/to/file.txt';

if (is_executable($filename)) {

echo "File $filename is executable.";

} else {

echo "File $filename is either not executable or does not exist.";

 6.) filesize()
In PHP, the filesize() function is used to get the size of a file in bytes. It takes a
filename as its parameter and returns the size of the file in bytes. Here's an example of
how you can use filesize():

Source Code:

$filename = 'path/to/file.txt';

if (file_exists($filename)) {

$size = filesize($filename);

echo "The size of '$filename' is: $size bytes";

} else {

echo "File '$filename' does not exist.";

NOTE: This function returns the file size if the file exists and is accessible; otherwise, it
returns FALSE. It's important to verify if the file exists using file_exists() before calling
filesize() to avoid errors or unexpected behaviour.

………………………………………………………………………………………………

Creating and Deleting Files


In this PHP tutorial we will learn how to create a file and how to delete a file on the server.

 Create a File – touch() ,


 Create a File, if does not exist – fopen()
 Delete a file – unlink()

PHP – Create a File

 The touch() function is used to create a file on server.


 The fopen() function is also used to create a file in PHP.
 If we use fopen() function on a file the file does not exist, then it will create it.
 The touch() function and fopen() work same for creating a file on server where the
php file directory code.

Syntax ( touch() ):

<?php
touch(“filename with extension”);

?>

Source Code:

Here we use PHP touch() function to create a new file called ‘abc.txt’, ‘abc.doc’ and
‘abc.pdf’ on server.

<?php

//create text file


touch("abc.txt");

//create ms word .doc file


touch("abc.doc");

//create pdf file


touch('abc.pdf');

?>

Note: When run above php code the file abc.txt, abc.pdf and abc.doc will be created in PHP
program folder.

PHP – fopen() function:

When we use fopen() function for creating a new file, must assign mode character with
function (w) for writing mode or (a) for appending mode.

Syntax ( fopen() ):

<?php

fopen(“filename with extension”, “mode char”);

?>

Source Code:
<?php

//create text file


fopen("abc.txt","w");

//create ms word .doc file


fopen("abc.doc","w");

//create pdf file


fopen('abc.pdf',"w");

?>

The fopen() function has following modes :

 w = write only. if file exist open it, if not then create a new file.
 w+ = read/write
 r = read only
 r += read / write
 a = append file
 a+ = read / append
 x = write only. create new file, returns error if file already exists.
 x+ = read/write.

PHP – Deleting a file:

The unlink() function is used to delete a file.

Syntax ( unlink() ):

<?php

unlink(“filename”);

?>

Source Code:

<?php
//delete txt file
unlink("abc.txt");
//delete ms word .doc file
unlink("abc.doc");
//delete pdf file
unlink('abc.pdf");
?>
………………………………………………………………………………………………….
Opening a File for Writing, Reading, or Appending:
In PHP, you can open files for reading, writing, and appending using different modes with the
fopen() function. This function is used to open a file or URL and returns a file pointer
resource on success, or false on failure.

PHP file open & read:


In this php tutorial we will learn how to open file , read file and close file using file handling
functions.

PHP functions :
 fopen() – open file
 fread() – read file
 fclose() – close file

Syntax – (fopen() )

<?php

fopen(“filename with extension”, “mode char”);

?>

Source Code:

<?php

//open text file


fopen("abc.txt","w");

//open ms word .doc file


fopen("abc.doc","w");

//open pdf file


fopen('abc.pdf',"w");

?>

Read file ( fread() ):


Reading (r): Opens the file for reading only. The file pointer is placed at the beginning of the
file.

Syntax ( fread() ):

<?php

fread(“filename”, “filesize”);

?>

Source Code:

<!DOCTYPE html>
<html>
<body>
<?php)

$file = fopen("test.txt","r");

fread($file,filesize("test.txt"));

fclose($file);

?>
</body>
</html>

Write file ( fwrite() )

Writing (w): Opens the file for writing only. It truncates the file to zero length or creates a
new file if it doesn't exist. The file pointer is placed at the beginning of the file.

Syntax ( fwrite() ):

<?php

fwrite(“filename”,”text to be written”);

?>

Source Code:
<?php

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

$txt = "John Doe\n";

fwrite($myfile, $txt);

$txt = "Jane Doe\n";

fwrite($myfile, $txt);

fclose($myfile);

?>

Appending to 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.
 Let's see the data of file first.

Data.txt

welcome to php file write

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

Source Code:

<?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";
?>
Output: data.txt
welcome to php file write this is additional text appending data

…………………………………………………………………………………………………..

Reading from files:


 PHP provides various functions to read data from file. There are different functions
that allow you to read all file data, read data line by line and read data character by
character.
 The available PHP file read functions are given below.

They are : i.) fread()

ii.) fgets()

iii.) fgetc()

PHP Read file - fread()

The PHP fread() function is used to read data of the file. It requires two arguments: file
resource and file size.

Syntax:

string fread (resource $handle , int $length )

 $handle represents file pointer that is created by fopen() function.


 $length represents length of byte to be read.

Source Code:
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r"); //open file in read mode
$contents = fread($fp, filesize($filename)); //read file
echo "<pre>$contents</pre>"; //printing data of file
fclose($fp); //close file
?>
Output:

this is first line


this is another line
this is third line
PHP Read file – fgets()

The PHP fgets() function is used to read single line from the file.

Syntax:

string fgets ( resource $handle [, int $length ] )

Source Code:

<?php
$fp = fopen("c:\\file1.txt", "r"); //open file in read mode
echo fgets($fp);
fclose($fp);
?>
Output:

this is first line

PHP Read file – fgetc()

The PHP fgetc() function is used to read single character from the file. To get all data using
fgetc() function, use !feof() function inside the while loop.

Syntax:

string fgetc ( resource $handle )


Source Code:

<?php

$fp = fopen("c:\\file1.txt", "r"); //open file in read mode

while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output:

this is first line this is another line this is third line

…………………………………………………………………………………………………..

Working with Directories:


In web development, managing directories is a common task. PHP offers a set of powerful
functions to handle directories, enabling developers to create, delete, traverse, and perform
various operations on directories effortlessly. Understanding directory manipulation functions
in PHP can greatly enhance your ability to work with file systems and organize data
effectively.

Creating Directory:

 PHP provides the mkdir() function to create directories. It takes the directory path as
an argument and an optional parameter to specify permissions.
 The mkdir() function is used to create a new directory in computer.

Syntax:

<?php

mkdir(“directory_name”);

?>
Example:
<?php

mkdir("Data");

?>

Source Code:
<HTML>
<head>
<title>Create Directory in PHP</title>
</head>
<body>
<FORM method="POST">
Enter Directory Name : <input type="text" name="str"> <br/> <br/>
<input type="submit" name="Submit1" value="Create Directory">
</FORM>

<?php
if(isset($_POST["Submit1"]))
{
mkdir($_POST["str"]);
echo "Directory Created.";
}
?>
</body>
</HTML>

Listing Directory:

To retrieve a list of files and subdirectories within a directory, PHP offers scandir() and
glob() functions.

PHP scandir() Function

scandir() - Returns an array of files and directories of a specified directory

Source Code:

<?php

$mydir = '/docs'; // Specifying directory

$myfiles = scandir($mydir); // Scanning files in a given directory in ascending order

print_r($myfiles); // Displaying the files in the directory

?>
Output:

(
[0] => .
[1] => ..
[2] => aboutus.php
[3] => contact.php
[4] => index.php
[5] => terms.php
)

Removing Directory:

The rmdir() function is used to remove a directory from computer system.

Syntax:

<?php

rmdir(“directory_name”);

?>

Example:

<?php

rmdir("data");

?>

Source Code:

<HTML>
<head>
<title>Remove Directory in PHP</title>
</head>
<body>
<FORM method="POST">
Enter Directory Name : <input type="text" name="str"> <br/> <br/>
<input type="submit" name="Submit1" value="Remove Directory">
</FORM>
<?php
if(isset($_POST["Submit1"]))
{
rmdir($_POST["str"]);
echo "Directory Removed.";
}
?>
</body>
</HTML>

Open Directory:
The opendir() function is used to open files from directory.

Syntax:

<?php

$dir = opendir(“directory_name”);

?>

Example:

<?php

$dir=opendir("data");

?>

 Here, we use opendir() function to open directory “data” and store in $dir variable, we
use the $dir variable for read content of file in future.
 Read files from directory using readdir() function and opendir() function.

Source Code:

<HTML>
<head>
<title>Read Diretory in PHP</title>
</head>
<body>
<FORM method="POST">
Enter Directory Name : <input type="text" name="str"> <br/> <br/>
<input type="submit" name="Submit1" value="Read Files">
</FORM>

<?php
if(isset($_POST["Submit1"]))
{
$dir=opendir($_POST["str"]);
while($file=readdir($dir))
{
echo $file ."<br/>";
}
}
?>
</body>
</HTML>

Read Directory:

 Read files from directory in PHP.


 The readdir() function is used to read files from directory in PHP.
Syntax:

<?php

$file=readdir(“directory_name”);

?>

Example:

<HTML>
<head>
<title>Read Directory in PHP</title>
</head>
<body>
<FORM method="POST">
Enter Directory Name : <input type="text" name="str"> <br/> <br/>
<input type="submit" name="Submit1" value="Read Files">
</FORM>

<?php
if(isset($_POST["Submit1"]))
{
$dir=opendir($_POST["str"]);
while($file=readdir($dir))
{
echo $file ."<br/>";
}
}
?>
</body>
</HTML>
………………………………………………………………………………………………….

Open pipes to and from process using popen():


In PHP, the popen() function allows you to open a process for reading or writing. However,
it's important to note that it opens a pipe to or from a process and provides a file pointer. This
means you can read from or write to the process using standard I/O functions like fread() and
fwrite().

Syntax:

popen(command, mode)

Parameters Used:
The popen() function in PHP accepts two parameters.
1. command : It is a mandatory parameter which specifies the command to be
executed.
2. mode : It is a mandatory parameter which specifies the connection mode such as
read only(r) or write only(w).

Return Value:
It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional
in nature.

Errors And Exceptions:


1. The file pointer initiated by the popen() function must be closed with pclose().
2. If the command to be executed could not be found, then the popen() function
returns a valid resource.

Source Code:

<?php

// opening a pipe
$my_file= popen("/bin/ls", "r");
?>

Output:
1

…………………………………………………………………………………………………..

Running Commands with exec():


The exec() function is an inbuilt function in PHP which is used to execute an external
program and returns the last line of the output. It also returns NULL if no command run
properly.

Syntax:

string exec( $command, $output, $return_var )

Parameters: This function accepts three parameters as mentioned above and described
below:
 $command: This parameter is used to hold the command which will be
executed.
 $output: This parameter is used to specify the array which will be filled with
every line of output from the command.
 $return_var: The $return_var parameter is present along with the output
argument, then it returns the status of the executed command will be written to
this variable.

Return Value: This function returns the executed command, be sure to set and use the
output parameter.

Source Code:

<?php
// (on a system with the "iamexecfunction" executable in the path)
echo exec('iamexecfunction');
?>

Output:
Geeks.php

…………………………………………………………………………………………………..

Running Commands with system() or passthru():


In PHP, system() and passthru() are other functions used to execute shell commands similar
to exec(). These functions differ in how they handle command output and execution:

system():

 system() executes the command specified as its parameter and displays the output
directly to the output buffer or console.
 It returns the last line of the command output as a string or false if the command fails.
 This function is suitable when you need to display the command's output or when
you're interested in the exit status of the command.
Source Code:

<?php
// Execute a command and display its output

$output = system('ls -l', $return_var);

// Check if the command executed successfully

if ($return_var === 0) {

echo "Command executed successfully.\n";

echo "Output: $output\n"; // Output the last line of command's output

} else {

echo "Error executing the command.\n";

?>

Passthru():

 passthru() executes the command and directly passes the output to the output buffer
or console without capturing it.
 It returns the exit code of the command or false if the command fails.

Source Code:

<?php

$return_var = passthru('ls -l'); // Execute a command and directly display its output

// Check if the command executed successfully

if ($return_var === 0) {

echo "Command executed successfully.\n";

} else {

echo "Error executing the command.\n";

?>

Working with Images:


The imagecreate() function is used to create a new image. It is preferred to use
imagecreatetruecolor() to create an image instead of imagecreate(). This is because the image
processing occurs on the highest quality image possible which can be created using
imagecreatetruecolor().

Syntax

imagecreate( $width, $height )

Parameters

 width: The width of image


 height: The height of image.

Example
<?php
$img = imagecreate(500, 300);
$bgcolor = imagecolorallocate($img, 150, 200, 180);
$fontcolor = imagecolorallocate($img, 120, 60, 200);
imagestring($img, 12, 150, 120, "Demo Text1", $fontcolor);
imagestring($img, 3, 150, 100, "Demo Text2", $fontcolor);
imagestring($img, 9, 150, 80, "Demo Text3", $fontcolor);
imagestring($img, 12, 150, 60, "Demo Text4", $fontcolor);
header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>

Output
What are necessary modifications to image in PHP?
1. Resizing. $imagick->resizeImage(300, 200, Imagick::FILTER_LANCZOS, 1); ...
2. Cropping. $imagick->cropImage(200, 100, 50, 50); ...
3. Rotating. $imagick->rotateImage('white', 45); ...
4. Blurring. $imagick->blurImage(5, 3); ...
5. Sharpening. $imagick->sharpenImage(0, 1); ...
6. Color Adjustments.

You might also like