0% found this document useful (0 votes)
90 views37 pages

Unit - 3 PHP - 3

The document discusses various PHP date and time functions like date(), mktime(), and strtotime() that allow formatting dates and timestamps in PHP. It also covers working with PHP cookies and sessions, including creating, retrieving, updating, and deleting cookies, as well as how PHP sessions allow storing and accessing data across multiple pages.

Uploaded by

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

Unit - 3 PHP - 3

The document discusses various PHP date and time functions like date(), mktime(), and strtotime() that allow formatting dates and timestamps in PHP. It also covers working with PHP cookies and sessions, including creating, retrieving, updating, and deleting cookies, as well as how PHP sessions allow storing and accessing data across multiple pages.

Uploaded by

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

K Mahesh

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabi
• Introduction to PHP: The problem with other
Technologies ( Servelets and JSP),
• Downloading, installing, configuring PHP,
Programming in a Web environment and the
anatomy of a PHP Page.
• Overview of PHP Data types and Concepts: Variables
and data types, Operators, Expressions and
Statements, Strings, Arrays and Functions.
• PHP Advanced Concepts: Using Cookies, Using HTTP
Headers, Using Sessions, Authenticating users, Using
Environment and Configuration variables, Working
with Date and Time.
PHP Advanced Concepts: Date and Time
• The PHP date() function is used to format a date and/or a time.
• The PHP date() function formats a timestamp to a more
readable date and time.

date(format,timestamp)

Parameter Description
format Required. Specifies the format of the timestamp
Timestamp Optional. Specifies a timestamp. Default is the
current date and time

<?php echo date("Y");?>


PHP Date
• The required format parameter of the date() function
specifies how to format the date (or time).
• Here are some characters that are commonly used for
dates:
– d - Represents the day of the month (01 to 31)
– m - Represents a month (01 to 12)
– Y - Represents a year (in four digits)
– l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted


between the characters to add additional formatting.
<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

OUTPUT
Today is 2021/05/24
Today is 2021.05.24
Today is 2021-05-24
Today is Monday
PHP Time
• Here are some characters that are commonly used
for times:
– H - 24-hour format of an hour (00 to 23)
– h - 12-hour format of an hour with leading zeros (01 to
12)
– i - Minutes with leading zeros (00 to 59)
– s - Seconds with leading zeros (00 to 59)
– a - Lowercase Ante meridiem and Post meridiem (am
or pm)

date_default_timezone_set() - sets the timezone


<!DOCTYPE html>
<html>
<body>

<?php
echo "The time is " . date("h:i:sa");
?>

</body>
</html>

OUTPUT
The time is 02:44:18pm
Date With mktime()
• The PHP mktime() function returns the Unix
timestamp for a date.
• The Unix timestamp contains the number of
seconds between the Unix Epoch (January 1 1970
00:00:00 GMT) and the time specified.

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


<!DOCTYPE html>
<html>
<body>

<?php
$d=mktime(11, 14, 54, 3, 11, 2005);
echo $d."<br>";
echo "Created date is " . date("Y-m-d h:i:sa", $d);

echo "<br>Created date is " . date("Y-m-d h:i:sa",$d);


?>
</body>
</html>

OUTPUT
1110536094
Created date is 2005-03-11 11:14:54am
Created date is 2005-03-11 11:14:54am
Date From a String With strtotime()
• The PHP strtotime() function is used to convert a
human readable date string into a Unix timestamp
(the number of seconds since January 1 1970
00:00:00 GMT).

strtotime(time, now)
<!DOCTYPE html>
<html>
<body>

<?php
$d=strtotime("10:30pm May 24 2021");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

</body>
</html>

OUTPUT
Created date is 2021-05-24 10:30:00pm
<!DOCTYPE html>
<html>
<body>

<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";

$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
OUTPUT
</body> 2021-05-25 12:00:00am
</html> 2021-05-29 12:00:00am
2021-08-24 02:54:16pm
PHP Cookies
PHP Cookies
• A cookie is often used to identify a user.
• A cookie is a small file that the server embeds on
the user's computer (clinet browser).
• Each time the same computer requests a page
with a browser, it will send the cookie too.
• With PHP, you can both create and retrieve cookie
values.
• A cookie is created with the setcookie() function.

setcookie(name, value, expire, path, domain, secure, httponly);


– Name: - This sets the name of the cookie and is stored in an environment variable
called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
– Value:-This sets the value of the named variable and is the content that you actually
want to store.
– Expiry:- This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then
cookie will automatically expire when the Web Browser is closed.
– Path:-This specifies the directories for which the cookie is valid. A single forward
slash character permits the cookie to be valid for all directories.
– Domain:- This can be used to specify the domain name in very large domains and
must contain at least two periods to be valid. All cookies are only valid for the host
and domain which created them.
– Security:- This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by
regular HTTP.
– httponly:- When TRUE the cookie will be made accessible only through the HTTP
protocol. This means that the cookie won't be accessible by scripting languages, such
as JavaScript. It has been suggested that this setting can effectively help to reduce
identity theft through XSS attacks (although it is not supported by all browsers), but
that claim is often disputed. Added in PHP 4.2.0. TRUE or FALSE.
PHP Create/Retrieve a Cookie
• A cookie is created with the setcookie() function
• Retrieve the value of the cookie using the global
variable $_COOKIE.
• We also use the isset() function to find out if the
cookie is set
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "mahesh";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p><strong>Note:</strong> You might have to reload the page to see the value of the
cookie.</p>

</body>
</html>
Update a Cookie

<?php
$cookie_name = "user";
$cookie_value = “newuser";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
Delete a Cookie
• To delete a cookie, use the setcookie() function
with an expiration date in the past:

<!DOCTYPE html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Show all Cookies
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_COOKIE);
echo "<br>";
foreach($_COOKIE as $key=>$val)
{
echo $key.' is '.$val."<br>\n";
}
?>
</body>
</html>
PHP Sessions
• A session is a way to store information (in variables) to be used
across multiple pages.
• Unlike a cookie, the information is not stored on the users
computer.
• PHP Session : When you work with an application, you open it, do
some changes, and then you close it. This is much like a Session.
• The computer knows who you are. It knows when you start the
application and when you end.
• But on the internet there is one problem: the web server does not
know who you are or what you do, because the HTTP address
doesn't maintain state.
• Session variables solve this problem by storing user information to
be used across multiple pages.
• By default, session variables last until the user closes the browser.
• So; Session variables hold information about one single user, and
are available to all pages in one application.
PHP Sessions
• An alternative way to make data accessible across the various pages
of an entire website is to use a PHP Session.
• A session creates a file in a temporary directory on the server
where registered session variables and their values are stored. This
data will be available to all pages on the site during that visit.
• The location of the temporary file is determined by a setting in
the php.ini file called session.save_path. Before using any session
variable make sure you have setup this path.
• When a session is started following things happen −
– PHP first creates a unique identifier for that particular session which is a random
string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
– A cookie called PHPSESSID is automatically sent to the user's computer to store
unique session identification string.
– A file is automatically created on the server in the designated temporary directory
and bears the name of the unique identifier prefixed by sess_ ie
sess_3c7foj34c3jj973hjkop2fc937e3443.
Start a PHP Session
• A session is started with
the session_start() function.
• Session variables are set with the PHP global
variable: $_SESSION.
• Session id will get with session_id() function.
<?php
session_start();

if( isset( $_SESSION['counter'] ) ) {


$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}

$msg = "You have visited this page ". $_SESSION['counter'];


$msg .= "in this session.";
?>

<html>

<head>
<title>Setting up a PHP session</title>
</head>

<body>
<?php echo ( $msg ); ?>
</body>

</html>
show all the session variable values

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>
Destroy a PHP Session
To remove all global session variables and destroy the session,
use session_unset() and session_destroy().
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();

echo "All session variables are now removed, and the session is destroyed."
?>

</body>
</html>
HTTP Headers
• The header() function is an inbuilt function in PHP which
is used to send a raw HTTP header.
• The HTTP functions are those functions which manipulate
information sent to the client or browser by the Web
server, before any other output has been sent.
• The PHP header() function send a HTTP header to a client
or browser in raw form.
• Before HTML, XML, JSON or other output has been sent
to a browser or client, a raw data is sent with request
(especially HTTP Request) made by the server as header
information.
• HTTP header provide required information about the
object sent in the message body more precisely about the
request and response.
HTTP Headers
void header ( string $headerstring [, bool $replace = true
[, int $http_response_code ]] )
• headersring: The header string.
• replace: The optional replace parameter indicates
whether the header should replace a previous similar
header, or add a second header of the same type. By
default it will replace, but if you pass in FALSE as the
second argument you can force multiple headers of the
same type.
• http response code: Forces the HTTP response code to
the specified value. Note that this parameter only has an
effect if the string is not empty.
Header string

• There are two special-case header calls.


– The first is a header that starts with the string "HTTP/"
(case is not significant), which will be used to figure
out the HTTP status code to send.
header("HTTP/1.0 404 Not Found");
– The second special case is the "Location:" header. 
header("Location: http://www.example.com/");
replace

<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>
EX-1: Redirecting to a Different Location

<?php
// PHP program to describes header function

// Redirect the browser


header("Location: http://www.geeksforgeeks.org");

// The below code does not get executed


// while redirecting
exit;

?>
headers_list() Function
• The headers_list() function returns a list of response
headers to be sent to the browser.

headers_list()
Ex-2: To prevent caching
<?php
// Set a past date
header("Expires: Sun, 25 Jul 1997 06:02:34 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
<html>
<body>
<p>Hello World!</p>

<!-- PHP program to display header list -->


<?php
print_r(headers_list());
?>
</body>
</html>
header_remove() Function
• The header_remove() function removes an HTTP header
previously set with the header() function.
header_remove(headername)
• Headername is Optional. Specifies a header name to be
removed. If omitted, all previously set headers are
removed
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");

header_remove("Pragma");
?>
headers_sent() Function
• The headers_sent() function checks if/where headers
have been sent.
headers_sent(file,line)
Parameter Description
File Optional. If the file and line parameters are set, headers_sent() will put the
PHP source file name and line number where output started in the file and
line variables
Line Optional. Specifies the line number where the output started

<?php
if (!headers_sent()) {
  header("Location: https://www.w3schools.com/");
  exit;
}
?>
Sending Content Types Other Than HTML

• The Content-Type header field is used to specify the nature of the


data in the body of an entity, by giving type and subtype
identifiers, and by providing auxiliary information that maybe
required for certain types.
<?php
header("Content-type:application/pdf");
$output=downloaded;
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename=".$output.".pdf");
// The PDF source is in original.pdf readfile("original.pdf");
?>

You might also like