Working With Directories in PHP Unit-2
Working With Directories in PHP Unit-2
• File types affect how information is stored in files and retrieved rom
them.
Table: Octal values for the mode parameter of the chmod() function
PHP Directory Introduction
• A directory is a container or folder in a file system that holds files and
other directories (subdirectories). Directories are essential for organizing
files in a structured manner. When working with PHP, you often need to
interact with directories — creating, reading, modifying, and deleting
them.
if ($handle) {
echo "Directory '$dir' opened successfully.";
closedir($handle); // Close the directory when done.
} else {
echo "Failed to open directory '$dir'.";
}
?>
3. Delete a Directory (rmdir())
•The rmdir() function deletes an empty directory.
Syntax:
rmdir(string $dirname)
Example:
<?php
$dir = "empty_directory";
if (rmdir($dir)) {
echo "Directory '$dir' deleted successfully!";
} else {
echo "Failed to delete directory '$dir'. It may not be empty.";
}
?>
4. Check if a Directory Exists (is_dir())
•The is_dir() function checks whether a given path is a directory.
Syntax:
is_dir(string $filename)
Example:
<?php
$dir = "some_directory";
if (is_dir($dir)) {
echo "'$dir' is a directory.";
} else {
echo "'$dir' is not a directory.";
}
?>
5. List All Files in a Directory (scandir())
•The scandir() function returns an array of files and directories inside the specified directory.
Syntax:
scandir(string $directory)
Example:
<?php
$dir = "some_directory";
$files = scandir($dir);
echo "Files in '$dir':<br>";
foreach ($files as $file) {
if ($file != '.' && $file != '..') { // Skip special entries
echo "$file<br>";
}
}
Example PHP Code to Create, Read, and Delete
Directory:
<?php
// 1. Create a directory
$dir = "example_folder";
if (!is_dir($dir)) {
mkdir($dir, 0777);
echo "Directory '$dir' created successfully!<br>";
} else {
echo "Directory '$dir' already exists.<br>";
}
Contd.
// 2. Create a file inside the directory
$file = $dir . "/example.txt";
file_put_contents($file, "This is a test file inside '$dir'.");
echo "File '$file' created inside '$dir'.<br>";
// 3. Read the directory contents
echo "Contents of '$dir':<br>";
$handle = opendir($dir);
while (($entry = readdir($handle)) !== false) {
if ($entry != "." && $entry != "..") { // Skip . and ..
echo "$entry<br>";
}
}
Contd.
closedir($handle);
// 4. Delete the file and directory
unlink($file); // Delete the file
rmdir($dir); // Delete the directory
echo "File '$file' and directory '$dir' deleted.<br>";
?>
Output:
PHP COOKIES
• PHP cookie is a small piece of information which is stored at client browser. It is
used to recognize the user.
• Cookie is created at server side and saved to client browser. Each time when
client sends request to the server, cookie is embedded with request. Such way,
cookie can be received at the server side.
What Are Cookies?
•A cookie is a text file that is stored on a user's device when they visit a
website. It contains information such as:
1. User preferences
2. Session identifiers
3. Tracking data
4. Authentication tokens
•Cookies are essential for creating persistent sessions, personalizing user
experiences, and tracking user behavior.
•In short, cookie can be created, sent and received at server end.
•Note: PHP Cookie must be used before <html> tag.
PHP setcookie() function:
•PHP setcookie() function is used to set cookie with HTTP response.
Syntax:
<body>
<?php
// Check if the cookie is set
if (!isset($_COOKIE[$cookie_name])) {
echo "Cookie is not set!";
} else {
echo "Cookie '{$cookie_name}' is set!<br>";
echo "Value: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
PHP SESSIONS
• A session in PHP is a way to store and manage user data across multiple pages
during a single user visit. PHP session is used to store and pass information from
one page to another temporarily (until user close the website).
• PHP session technique is widely used in shopping websites where we need to
store and pass cart information e.g. username, product code, product name,
product price etc from one page to another.
• PHP session creates unique user id for each browser to recognize the user and
avoid conflict between multiple browsers.
• Unlike cookies, which store data on the client’s browser, session data is stored on
the server and is assigned a unique session ID.
Key Features of Sessions:
• Server-Side Storage: Session data is stored on the server, making it more
secure than cookies.
• Unique Session ID: Each session is identified by a unique session ID, which
is sent to the client via a cookie (PHPSESSID).
• Automatic Expiry: Sessions automatically expire when the user closes the
browser or after a specified timeout period.
• Large Data Storage: Unlike cookies (limited to ~4 KB), sessions can store
larger amounts of data.
How to Starting a PHP Session?
• Before you can store user information in your PHP session, you must first start
up the session.
• Note: The session_start() function must appear BEFORE the <html>tag:
<?php Session_start(); ?>
<html>
<body>
</body>
</html>
• The code above will register the user's session with server, allow you to start
saving user information, an assign a UID for that user's session.
Creating and Using Sessions in PHP
1. Start a Session
•To use a session, you must first call session_start() at the beginning of your PHP
script.
<?php
session_start(); // Start the session
if (isset($_SESSION["username"])) {
echo "Welcome, " . $_SESSION["username"]; // Output: Welcome, Vamsi
} else {
echo "Session not set.";
}
?>
Contd.
3. Modify Session Data
<?php
session_start();
2 JSON is lightweight thus simple to read and XML is less simple than JSON.
write
3 JSON supports array data structure XML doesn't support array data structure
4 JSON files are more human readable XML files are less human readable
5 Provides scalar data types and the ability to Does not provide any notion of data types.
express structured data through arrays and One must rely on XML Schema for adding
objects type information.
echo json_encode($age);
?>
Output: {"Peter":35,"Ben":37,"Joe":43}
PHP - json_decode()
• The json_decode() function is used to decode a JSON object into a PHP
object or an associative array.
Example:
This example decodes JSON data into a PHP object:
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
var_dump(json_decode($jsonobj));
?>
Output:
object(stdClass)#1 (3) { ["Peter"]=> int(35) ["Ben"]=> int(37) ["Joe"]=>
int(43) }
Common Applications of JSON
1. Web APIs
Data exchange between servers and clients (e.g., Twitter, Google Maps)
2. Mobile Apps
Data transfer for apps (e.g., Uber, Instagram)
3. Configuration Files
Stores app configurations (e.g., Node.js)
4. NoSQL Databases
Data storage (e.g., MongoDB)
5. Microservices Communication
Data exchange in distributed systems (e.g., AWS, Azure)
6. IoT Devices
Data exchange in smart devices (e.g., Smart Home)