Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views22 pages

Unit 5 Advanced PHP

This document covers various PHP functionalities including date and time manipulation, file inclusion, cookie management, session handling, data validation and sanitization, and MySQL integration. It explains how to use functions like date(), time(), setcookie(), and session_start() for managing user data and preferences. Additionally, it discusses the benefits of using PHP with MySQL for database operations, including creating databases and tables.

Uploaded by

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

Unit 5 Advanced PHP

This document covers various PHP functionalities including date and time manipulation, file inclusion, cookie management, session handling, data validation and sanitization, and MySQL integration. It explains how to use functions like date(), time(), setcookie(), and session_start() for managing user data and preferences. Additionally, it discusses the benefits of using PHP with MySQL for database operations, including creating databases and tables.

Uploaded by

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

UNIT-5

PHP

PHP DATE AND TIME


Date and time are some of the most frequently used operations in PHP while executing SQL
queries or designing a website etc. PHP serves us with predefined functions for these tasks.
Some of the predefined functions in PHP for date and time are discussed below.

PHP date() Function: The PHP date() function converts timestamp to a more readable date and
time format.

Why do we need the date() function?

The computer stores dates and times in a format called UNIX Timestamp, which measures time
as a number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean
Time on January 1, 1970, i.e. January 1, 1970, 00:00:00 GMT ). Since this is an impractical
format for humans to read, PHP converts timestamp to a format that is readable and more
understandable to humans.

1. PHP date() Function


The date() function formats a timestamp into a readable date and time.
Syntax
date(format, timestamp);
• format → Specifies the format of the date/time.
• timestamp (optional) → Unix timestamp (seconds since 01 Jan 1970). If omitted,
the current timestamp is used.
Common Date Formats
PHP PROGRAM TO DISPLAY CURRENT DATE AND TIME
<?php

echo "Today is " . date("Y-m-d") . "<br>";

echo "Current time is " . date("h:i:s A");

?>
PHP SCRIPT TO DISPLAY DATE AND TIME USING DIFFERENT FORMATTING
OPTIONS
<?php

echo date("h:i:s") . "\n";

echo date("M,d,Y h:i:s A") . "\n";

echo date("h:i a");

?>
PHP time() Function: The time() function is used to get the current time as a Unix timestamp
(the number of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00
GMT).

The following characters can be used to format the time string:

• h: Represents hour in 12-hour format with leading zeros (01 to 12).


• H: Represents hour in 24-hour format with leading zeros (00 to 23).
• i: Represents minutes with leading zeros (00 to 59).
• s: Represents seconds with leading zeros (00 to 59).
• a: Represents lowercase antemeridian and post meridian (am or pm).
• A: Represents uppercase antemeridian and post meridian (AM or PM).

Example: The below example explains the usage of the time() function in PHP.

<?php

$timestamp = time();

echo($timestamp);

echo "\n";

echo(date("F d, Y h:i:s A", $timestamp));

?>
PHP mktime() Function: The mktime() function is used to create the timestamp for a specific
date and time. If no date and time are provided, the timestamp for the current date and time is
returned.
Syntax:

mktime(hour, minute, second, month, day, year)

PHP INCLUDE AND REQUIRE

The include statement is used to include a file in a PHP script. If the file is missing or has an
error, PHP will show a warning (E_WARNING) but continue executing the script.
Syntax:
include 'filename.php';

Example
Header.php
<?php

echo "<h1>Welcome to My Website</h1>";

?>
Now, we use include in index.php:
<?php

include 'header.php'; // Includes the header

echo "<p>This is the homepage content.</p>";

?>
Output
Welcome to My Website

This is the homepage content.

2. PHP require Statement


The require statement also includes a file, but if the file is missing, it will cause a fatal error
(E_COMPILE_ERROR), stopping script execution.
Syntax:
require 'filename.php';
3. include_once and require_once
• include_once and require_once ensure a file is included only once in a script, preventing
duplicate inclusions.
include_once 'header.php'; // Prevents re-inclusion if already included

require_once 'config.php'; // Prevents multiple inclusions of config settings

PHP COOKIES
• Cookies are small text files stored on the user's browser.
• They are used to remember information about the user, such as preferences, login
details, or other data across different sessions (visits).
• Cookies can have an expiration time (after which they are deleted) or they can be
permanent.
How do Cookies Work in PHP?
1. Setting a Cookie: To set a cookie in PHP, you use the setcookie() function. This sends
the cookie to the user's browser before any content is displayed (since headers need to
be sent first).
2. Reading a Cookie: After the cookie is set, you can access its value using the
$_COOKIE superglobal array.
3. Deleting a Cookie: You can delete a cookie by setting its expiration time to the past.

setcookie("user", "John Doe", time() + 3600, "/");:


• "user" is the name of the cookie.
• "John Doe" is the value of the cookie.
• time() + 3600 sets the cookie to expire in 1 hour (3600 seconds).
• "/" makes the cookie available across the entire website.
setcookie(name, value, expire, path, domain, secure, httponly)
• name → The name of the cookie.
• value → The value stored in the cookie.
• expire → Expiration time (in seconds).
• path → Path on the server where the cookie is valid.
• domain → Domain for which the cookie is available.
• secure → If true, only transmits over HTTPS.
• httponly → If true, accessible only via HTTP (not JavaScript).

PHP Code to Implement Cookies


Step 1: Create a PHP File to Set Cookies (set_cookie.php)
• Save the following code as set_cookie.php in the www folder (C:\wamp64\www\).
<?php
// Set a cookie named "user" with the value "John Doe", expires in 1 hour
setcookie("user", "John Doe", time() + 3600, "/");

// Set another cookie with an expiration of 1 day


setcookie("theme", "dark-mode", time() + 86400, "/");

echo "Cookies have been set successfully!";


?>
• The cookie user will store "John Doe" and expire in 1 hour.
• The cookie theme will store "dark-mode" and expire in 1 day.

Step 2: Retrieve and Display Cookies (get_cookie.php)


Create another PHP file (get_cookie.php) to read the stored cookies.
<?php
if(isset($_COOKIE["user"])) {
echo "User Cookie: " . $_COOKIE["user"] . "<br>";
} else {
echo "User cookie is not set!<br>";
}

if(isset($_COOKIE["theme"])) {
echo "Theme Cookie: " . $_COOKIE["theme"] . "<br>";
} else {
echo "Theme cookie is not set!<br>";
}
?>
This script checks if cookies exist and displays their values.

Step 3: Delete a Cookie (delete_cookie.php)


To remove a cookie, set its expiration time in the past.
<?php
// Delete the "user" cookie
setcookie("user", "", time() - 3600, "/");

// Delete the "theme" cookie


setcookie("theme", "", time() - 3600, "/");

echo "Cookies have been deleted!";


?>

• $_COOKIE["user"] retrieves the value of the "user" cookie. If the cookie exists, it prints
the stored value ("John Doe"). If it doesn't exist, it says "Hello, new user!".

• time() - 3600 sets the cookie to expire 1 hour ago, effectively deleting it.
• After deleting the cookie, the script checks if the cookie still exists using isset(). Since
it's expired, it will no longer be available.
USES OF PHP COOKIES
• Cookies help store user-specific data like login credentials, preferences, and shopping
cart items.
• Unlike sessions, which expire when the browser is closed, cookies can store data for a
longer time, enabling personalized user experiences.
• Since cookies are stored on the client-side (user’s browser), they do not consume server
resources, reducing the load on the server.
• Websites use cookies to track user behavior, helping businesses analyze user
interactions, preferences, and browsing patterns for targeted marketing and
improvements.
• PHP provides built-in functions like setcookie() and $_COOKIE to create and access
cookies, making them simple to use in web applications.

SESSIONS IN PHP
A session in PHP is a way for a website to remember information about a user as they move
from one page to another.
When a user visits a website, the web server doesn't remember anything about them because
the internet works on something called HTTP, which is like a "one-time visit" for each page.
This is where sessions come in — they allow the server to keep track of things like:
• Who the user is (Are they logged in?)
• What they have done (What items are in their shopping cart?)
• What preferences they have (Do they prefer dark mode or light mode?)
How does it work?
1. Starting a session: When you visit a website, the server creates a "session" and gives
it a unique ID, which it remembers.
2. Tracking information: The server can then store small pieces of information in this
session, such as your name, whether you're logged in, or what items are in your cart.
3. Keeping it around: Every time you visit another page on the site, the server knows it's
you because your session ID gets sent back to it (usually stored in a cookie in your
browser).
4. Ending the session: When you're done with the website (like when you log out or close
your browser), the session ends, and the information is erased.
Simple Example:
• You log in to a website. The website "remembers" that you're logged in because a
session was started.
• You add a product to your shopping cart. The session keeps track of this.
• Even if you go to a different page on the website, your cart remains because the session
ID keeps things consistent for the server.
In short, a session lets a website "remember" things about you during your visit so that it can
offer a more personalized experience.

Starting a PHP Session: The first step is to start up a session. After a session is started, session
variables can be created to store information. The PHP session_start() function is used to begin
a new session.It also creates a new session ID for the user.

Below is the PHP code to start a new session:

<?php

session_start();

?>
Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal
array.The stored data can be accessed during lifetime of a session.

Below is the PHP code to store a session with two session variables Rollnumber and Name:

<?php

session_start();

$_SESSION["Name"] = "Ajay";

?>
Accessing Session Data: Data stored in sessions can be easily accessed by firstly
calling session_start() and then by passing the corresponding key to
the $_SESSION associative array.
<?php

session_start();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';

?>

Destroying Complete Session: The session_destroy() function is used to completely destroy


a session. The session_destroy() function does not require any argument.

<?php

session_start();
session_destroy();

?>

USES OF PHP SESSIONS

1. Data Persistence Across Sessions


2. Reduces Server Load
3. Easy to Implement and Use
4. Helps in User Authentication
5. Stores User Preferences
6. Improves User Experience

VALIDATING AND SANITIZING DATA WITH PHP FILTERS


PHP provides the filter_var() function to validate and sanitize user input to ensure security
and prevent malicious attacks.
1. Validating Data
Validation checks if input data meets specific criteria (e.g., email format, integer check, etc.).
Example: Validate an Email
<?php
$email = "[email protected]";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
?>
Returns "Valid email" if correct, otherwise "Invalid email".
2. Sanitizing Data
Sanitization removes or modifies unwanted characters from input to prevent attacks.
Example: Sanitize an Email
<?php
$email = "test@!example.com";
$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);

echo $sanitized_email; // Output: [email protected]


?>
<?php
$email = "test@!example.com";
$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);

echo $sanitized_email; // Output: [email protected]


?>
Removes special characters not allowed in an email.

PHP AND MYSQL


PHP is a language that gives you the flexibility to connect and work with
different databases while developing your webpage. There are different databases, both
commercial and free to use. Amongst them, MySQL is the most commonly used database
alongside PHP.

MySQL is an open-source, free-to-use relational database management system (RDBMS). It


is a fast, simple, and highly scalable program and hence can be used for small as well as huge
businesses.

What is MySQL?
MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP. MySQL is developed, distributed, and supported by
Oracle Corporation.

• The data in a MySQL database are stored in tables which consists of columns and
rows.
• MySQL is a database system that runs on a server.
• MySQL is ideal for both small and large applications.
• MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
• MySQL compiles on a number of platforms.

WHY PHP AND MYSQL?


Here are the key reasons why PHP is used with MySQL:
1. Open-Source and Free
• Both PHP and MySQL are open-source, meaning they are free to use and have strong
community support.
2. Seamless Integration
• PHP has built-in functions (mysqli and PDO) to interact with MySQL databases
easily.
3. Cross-Platform Compatibility
• PHP and MySQL can run on various operating systems like Windows, Linux, and
macOS.
4. High Performance and Scalability
• MySQL is a powerful database that can handle large amounts of data efficiently.
• PHP processes requests quickly, making the combination ideal for scalable
applications.
5. Easy to Learn and Use
• PHP has a simple syntax and works well with HTML and JavaScript.

CONNECT TO MYSQL
How to connect PHP with MySQL Database?
PHP 5 and later can work with a MySQL database using:
1. MySQLi extension.
2. PDO (PHP Data Objects).

Example: PHP Connecting to MySQL


<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "test_db";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

echo "Connected successfully";

// Close connection

$conn->close();

?>
CREATING DATABASE AND TABLES
You can create a MySQL database using PHP’s mysqli or PDO functions.
Example: Creating a Database
<?php

$servername = "localhost";

$username = "root";

$password = "";
// Create a connection

$conn = new mysqli($servername, $username, $password);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Create database

$sql = "CREATE DATABASE mydatabase";

if ($conn->query($sql) === TRUE) {

echo "Database created successfully!";

} else {

echo "Error creating database: " . $conn->error;

// Close connection

$conn->close();

?>
2️.Create a Table in MySQL using PHP
Once the database is created, you need to connect to it and create tables.
Example: Creating a Table
<?php

$servername = "localhost";

$username = "root";

$password = "";
$database = "mydatabase";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Create table

$sql = "CREATE TABLE users (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(50) NOT NULL,

email VARCHAR(50) UNIQUE,

password VARCHAR(255) NOT NULL,

reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP

)";

if ($conn->query($sql) === TRUE) {

echo "Table 'users' created successfully!";

} else {

echo "Error creating table: " . $conn->error;

// Close connection
$conn->close();

?>
HOW TO RUN THE CODE?
• Save each script as .php files.
• Run them on a WAMP/XAMPP/LAMP/MAMP server.
• Verify in phpMyAdmin that the database and table are created.
INSERTING SINGLE AND MULTIPLE ROWS
Inserting Single and Multiple Rows into MySQL Table using PHP
After creating a table in MySQL, you can insert data using PHP.
Insert a Single Row
<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "mydatabase";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Insert a single record

$sql = "INSERT INTO users (name, email, password) VALUES ('John Doe',
'[email protected]', '123456')";

if ($conn->query($sql) === TRUE) {

echo "Record inserted successfully!";


} else {

echo "Error inserting record: " . $conn->error;

// Close connection

$conn->close();

?>

Insert Multiple Rows


<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "mydatabase";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Insert multiple records

$sql = "INSERT INTO users (name, email, password) VALUES

('Alice Smith', '[email protected]', 'alice123'),

('Bob Johnson', '[email protected]', 'bob123'),


('Charlie Brown', '[email protected]', 'charlie123')";

if ($conn->query($sql) === TRUE) {

echo "Multiple records inserted successfully!";

} else {

echo "Error inserting records: " . $conn->error;

// Close connection

$conn->close();

?>

Retrieve the Last Inserted ID in PHP


After inserting a record, you can retrieve the last inserted ID using mysqli_insert_id().
<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "mydatabase";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}
// Insert a record and get the last inserted ID

$sql = "INSERT INTO users (name, email, password) VALUES ('David Miller',
'[email protected]', 'david123')";

if ($conn->query($sql) === TRUE) {

$last_id = $conn->insert_id;

echo "Record inserted successfully! Last Inserted ID: " . $last_id;

} else {

echo "Error inserting record: " . $conn->error;

// Close connection

$conn->close();

?>

MYSQL PREPARED STATEMENT


A prepared statement in PHP is used to execute SQL queries securely and efficiently. It helps
prevent SQL injection attacks and improves performance when executing the same query
multiple times.

Steps to Use a MySQL Prepared Statement


1. Create a connection to MySQL.
2. Prepare the SQL statement using prepare().
3. Bind parameters using bind_param().
4. Execute the statement using execute().
5. Close the statement and connection.

Insert Data Using Prepared Statement


<?php

$servername = "localhost";

$username = "root";
$password = "";

$database = "mydatabase";

// Step 1: Create connection

$conn = new mysqli($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Step 2: Prepare the SQL statement

$stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");

// Step 3: Bind parameters (s = string, i = integer, d = double)

$stmt->bind_param("sss", $name, $email, $password);

// Step 4: Set values and execute the statement

$name = "Alice Johnson";

$email = "[email protected]";

$password = "alice123";

$stmt->execute();

echo "Record inserted successfully!";


// Step 5: Close statement and connection

$stmt->close();

$conn->close();

?>

"sss" means:

• First parameter is a string (s).


• Second parameter is a string (s).
• Third parameter is a string (s).

UPDATING AND DELETING DATA

UPDATE Data (Modify Records)


This code updates a user’s name in the database.
🔹 Code: Update a User’s Name
<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "mydatabase";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Prepare the UPDATE statement

$stmt = $conn->prepare("UPDATE users SET name = ? WHERE email = ?");


$stmt->bind_param("ss", $new_name, $email);

// Set values and execute the update

$new_name = "Alice Brown";

$email = "[email protected]";

$stmt->execute();

echo "Record updated successfully!";

// Close statement and connection

$stmt->close();

$conn->close();

?>

DELETE Data (Remove Records)


This code deletes a user from the database.
🔹 Code: Delete a User
<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "mydatabase";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}
// Prepare DELETE statement

$stmt = $conn->prepare("DELETE FROM users WHERE email = ?");

$stmt->bind_param("s", $email);

// Set email and execute the delete statement

$email = "[email protected]";

$stmt->execute();

echo "Record deleted successfully!";

// Close statement and connection

$stmt->close();

$conn->close();

?>

LIMITING DATA
LIMIT Data (Fetch Limited Rows)
This code selects a limited number of rows.
🔹 Code: Fetch Limited Rows
<?php

$servername = "localhost";

$username = "root";

$password = "";

$database = "mydatabase";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);


if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Prepare statement to fetch only 3 users

$stmt = $conn->prepare("SELECT id, name, email FROM users LIMIT ?");

$stmt->bind_param("i", $limit);

// Set limit and execute query

$limit = 3;

$stmt->execute();

$stmt->bind_result($id, $name, $email);

// Fetch and display data

while ($stmt->fetch()) {

echo "ID: $id - Name: $name - Email: $email <br>";

// Close statement and connection

$stmt->close();

$conn->close();

?>

You might also like