0% found this document useful (0 votes)
7 views

Working With Directories in PHP Unit-2

The document provides an overview of working with directories, files, cookies, sessions, and JSON in PHP. It explains directory functions such as creating, opening, and deleting directories, as well as managing file permissions. Additionally, it covers how to use cookies and sessions for user data management, and introduces JSON for data interchange, including its syntax and PHP functions for encoding and decoding JSON data.

Uploaded by

xiaochuuyan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Working With Directories in PHP Unit-2

The document provides an overview of working with directories, files, cookies, sessions, and JSON in PHP. It explains directory functions such as creating, opening, and deleting directories, as well as managing file permissions. Additionally, it covers how to use cookies and sessions for user data management, and introduces JSON for data interchange, including its syntax and PHP functions for encoding and decoding JSON data.

Uploaded by

xiaochuuyan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

Working with Directories in PHP

Overview of PHP Directory Functions


Understanding File Types and Permissions

• File types affect how information is stored in files and retrieved rom
them.

• File permissions determine the actions that a specific user can an


cannot perform on a file.
Working with File Permissions
• Files and directories have three levels of access:
 User
 Group
 Other
• The three typical permissions for files and directories are:
• Read (r)
• Write (w)
• Execute (x)
Working with File Permissions
Four-digit Octal (base 8) Value
1.The first digit is always 0
2.Sum of 3 bits per digit
3.Matches 3 permissions bits per level of access

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.

• PHP provides various functions to work with directories, allowing you to


manipulate directories and files efficiently.
PHP Directory Functions
The mainly used PHP Directory Functions are:
1.mkdir() function
2.rmdir() function
3.opendir() function
4.scandir() function
5.is_dir() function
6.getcwd() function
7.chdir() function
8.closedir() function
1. Create a Directory
•You can create a directory using the mkdir() function.
Syntax:
mkdir(string $pathname, int $mode = 0777)
<?php
$dir = "new_directory"; // Directory name
// Create the directory if it doesn't exist
if (!is_dir($dir)) {
mkdir($dir);
echo "Directory '$dir' created!";
} else {
echo "Directory '$dir' already exists.";
}
?>
2. Open a Directory (opendir())
•The opendir() function opens a directory to read its contents.
Syntax:
opendir(string $dirname)
Example:
<?php
$dir = "some_directory";
$handle = opendir($dir); // open directory

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.

•Once cookie is set, you can access it by $_COOKIE superglobal variable.

Syntax:

setcookie(name, value, expire);


PHP COOKIES
Example 1:
•In the example below, we will create a cookie named "user" and assign the
value "vamsi" to it. We also specify that the cookie should expire after one
hour:
<?php
Setcookie("user", "vamsi", time()+3600);
?>
<html>
…….
Hint…. 60*60
PHP COOKIES
Example 2:
•You can also set the expiration time of the cookie in another way. It
may be easier than using seconds.
<?php
$expire=time()+60*60*24*30;
Setcookie("user", "vamsi", $expire);
?>
<html>
•In the example above the expiration time is set to a month (60 sec *60
min *24 hours * 30 days).
How To Retrieve a COOKIE VALUE?
• In the example below, we retrieve the value of the cookie named
"user" and display it on a page:
<?php
//print a cookie
Echo $_COOKIE["user"];

// A way to view all cookie


Print_r($_COOKIE);
?>
How To Retrieve a COOKIE VALUE?
• In the following example we use the isset() function to find out if a cookie has
been set:
<html>
<body>
<?php
If (isset($_COOKIE["user"]))
echo "Welcome". $_COOKIE["user"] . "<br>";
else
echo "Welcome guest!<br>";
?>
</body>
</html>
Example PHP Create/Retrieve a Cookie
<?php
// Set a cookie
$cookie_name = "user";
$cookie_value = "Vamsi";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1
day
?>
Contd.
<html>

<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

// Store session data


$_SESSION["username"] = "Vamsi";
$_SESSION["role"] = "Admin";

echo "Session variables are set.";


?>
Note: session_start() must be called before any HTML output.
Contd.
2. Access Session Data
•Session data can be retrieved using the $_SESSION superglobal array.
<?php
session_start(); // Resume the session

if (isset($_SESSION["username"])) {
echo "Welcome, " . $_SESSION["username"]; // Output: Welcome, Vamsi
} else {
echo "Session not set.";
}
?>
Contd.
3. Modify Session Data

•Session values can be updated at any time.

<?php

session_start();

$_SESSION["username"] = "Chandra"; // Update session value

echo "Username updated to " . $_SESSION["username"];


Contd.
4. Destroy the Entire Session
•To remove all session data and destroy the session:
<?php
session_start();
session_destroy(); // Destroy session
echo "Session destroyed.";
?>
•After session_destroy(), the session variables will no longer be accessible.
Difference between Cookies and
Sessions
Cookies Session
Stored on client-side (browser) Stored on server
Cookies end on the lifetime set by the Ends when the browser is closed or
user. session timeout occurs
Cookies stored on a limited data.
Can store larger data
(maximum capacity of 4 KB.)
Session are more secured compare than
Cookies are not secured.
cookies.
Cookies stored data in text file. Session save data in encrypted form.
In PHP, to get the data from Cookies , In PHP , to get the data from Session,
$_COOKIES the global variable is $_SESSION the global variable is used
used
JSON (JavaScript Object Notation)
• JSON (JavaScript Object Notation) is a lightweight data-interchange
format.
• A common use of JSON is to read data from a web server, and display
the data in a web page.
• JSON is a syntax for storing and exchanging data.
• JSON is an easier-to-use alternative to XML (Extensible Markup
Language).
• It is based on a subset of the JavaScript Programming Language.
• A JSON file type is .json
JSON vs XML
s.n JSON XML
o
1 It is JavaScript Object Notation It is Extensible markup language

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.

6 It doesn’t use end tag. It has start and end tags.


contd.
JSON Style: XML Style:
{ <students>
"Students": [
{ <student>
"name": "Vamsi", <name>Vamsi</name><age>23</age>
"age" : "23",
"city": "Delhi" <city>Delhi<city>
}, </student>
{
"name": "Chandra", <student>
"age" : "25", <name>Chandra</name><age>25</age>
"city" : "Chennai"
} <city>Chennai</city>
] </student>
}
</students>
JSON Syntax
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
{ objects
•Data is in name/value pairs
"Students": [ arrays
•Data is separated by commas {
"name": "Vamsi",
•Curly braces hold objects "age" : "23",
•Square brackets hold arrays "city": "Delhi"
},
{
"name": "Chandra",
"age" : "25",
"city" : "Chennai"
}
]
}
JSON Data Types
• In JSON, values must be one of the following data types:
1. string Ex: {"name":"John"}
2. number Ex: {"age":30}
3.object (JSON object)
Ex:
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
4.Array
Ex:
{
"employees":["John", "Anna", "Peter"]
}
5. Boolean Ex: {"sale":true}

6. Null Ex: {"middlename":null}


PHP and JSON
• PHP has some built-in functions to handle JSON.
• First, we will look at the following two functions:
1.json_encode()
2.json_decode()
3.json_last_error()
PHP - json_encode()
• The json_encode() function is used to encode a value to JSON format.
Example:
This example shows how to encode an associative array into a JSON
object:
<?php
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);

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)

You might also like