Unit - Iv (DS & Stat)
Unit - Iv (DS & Stat)
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().
………………………………………………………………………………………………….
.
Syntax:
include 'filename';
or
require 'filename';
Source Code:
Vars.php
<?php
$color='red';
$car='BMW';
?>
inc.php
<html>
<body>
?>
</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.
Syntax:
is_file( filename );
Source Code:
$filename = 'path/to/file.txt';
if (is_file($filename)) {
else
2.) is_dir() :
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)) {
} else {
// File doesn't exist or is not readable
4.) is_writable()
Source Code:
$filename = 'path/to/file.txt';
if (is_writable($filename)) {
} else {
5.) is_executable()
Source Code:
$filename = 'path/to/file.txt';
if (is_executable($filename)) {
} else {
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);
} else {
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.
………………………………………………………………………………………………
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
?>
Note: When run above php code the file abc.txt, abc.pdf and abc.doc will be created in PHP
program folder.
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
?>
Source Code:
<?php
?>
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.
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 functions :
fopen() – open file
fread() – read file
fclose() – close file
Syntax – (fopen() )
<?php
?>
Source Code:
<?php
?>
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>
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
fwrite($myfile, $txt);
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
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
…………………………………………………………………………………………………..
ii.) fgets()
iii.) fgetc()
The PHP fread() function is used to read data of the file. It requires two arguments: file
resource and file size.
Syntax:
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:
The PHP fgets() function is used to read single line from the file.
Syntax:
Source Code:
<?php
$fp = fopen("c:\\file1.txt", "r"); //open file in read mode
echo fgets($fp);
fclose($fp);
?>
Output:
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:
<?php
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output:
…………………………………………………………………………………………………..
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.
Source Code:
<?php
?>
Output:
(
[0] => .
[1] => ..
[2] => aboutus.php
[3] => contact.php
[4] => index.php
[5] => terms.php
)
Removing Directory:
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:
<?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>
………………………………………………………………………………………………….
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.
Source Code:
<?php
// opening a pipe
$my_file= popen("/bin/ls", "r");
?>
Output:
1
…………………………………………………………………………………………………..
Syntax:
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
…………………………………………………………………………………………………..
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
if ($return_var === 0) {
} else {
?>
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
if ($return_var === 0) {
} else {
?>
Syntax
Parameters
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.