0% found this document useful (0 votes)
23 views14 pages

Student PHP1

Session variables allow information to be stored and accessed across multiple pages. A session is started with session_start() and variables are set globally with $_SESSION. Session data is stored on the server instead of the user's computer. Cookies are also used to store and retrieve information across pages using setcookie() and $_COOKIE but the data is stored on the user's computer.

Uploaded by

parveen saini
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)
23 views14 pages

Student PHP1

Session variables allow information to be stored and accessed across multiple pages. A session is started with session_start() and variables are set globally with $_SESSION. Session data is stored on the server instead of the user's computer. Cookies are also used to store and retrieve information across pages using setcookie() and $_COOKIE but the data is stored on the user's computer.

Uploaded by

parveen saini
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/ 14

PHP

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.

What is a 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 (e.g. username, favorite color,
etc). 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.
Start a PHP Session

A session is started with the session_start() function.


Session variables are set with the PHP global variable:
$_SESSION.
first.php
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Note: The session_start() function must be the very first thing in


your document. Before any HTML tags.

second.php

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

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</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>

Include Files

PHP include and require Statements

It is possible to insert the content of one PHP file into another


PHP file (before the server executes it), with the include or
require statement.
The include and require statements are identical, except
upon failure:
• require will produce a fatal error (E_COMPILE_ERROR)
and stop the script
• include will only produce a warning (E_WARNING) and
the script will continue
So, if you want the execution to go on and show users the
output, even if the include file is missing, use the include
statement. Otherwise, in case of FrameWork, CMS, or a
complex PHP application coding, always use the require
statement to include a key file to the flow of execution. This will
help avoid compromising your application's security and
integrity, just in-case one key file is accidentally missing.
Including files saves a lot of work. This means that you can
create a standard header, footer, or menu file for all your web
pages. Then, when the header needs to be updated, you can only
update the header include file.

'footer.php'
<?php
echo "<p>Copyright &copy </p>";
?>

index.php
<!DOCTYPE html>
<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
PHP include vs. require

The require statement is also used to include a file into the PHP
code.
However, there is one big difference between include and
require; when a file is included with the include statement and
PHP cannot find it, the script will continue to execute:
If we do the same example using the require statement, the echo
statement will not be executed because the script execution dies
after the require statement returned a fatal error:

<!DOCTYPE html>
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>
File Handling

PHP readfile() Function

The readfile() function reads a file and writes it to the output


buffer.
Assume we have a text file called "webdictionary.txt", stored on
the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

The PHP code to read the file and write it to the output buffer is
as follows (the readfile() function returns the number of bytes
read on success)
<!DOCTYPE html>
<html>
<body>

<?php
echo readfile("webdictionary.txt");
?>
</body>
</html>

File Open/Read/Close

PHP Open File - fopen()

A better method to open files is with the fopen() function. This


function gives you more options than the readfile() function.
We will use the text file, "webdictionary.txt", during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

The first parameter of fopen() contains the name of the file to be


opened and the second parameter specifies in which mode the
file should be opened. The following example also generates a
message if the fopen() function is unable to open the specified
file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to
open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

PHP Create File - fopen()

The fopen() function is also used to create a file. Maybe a little


confusing, but in PHP, a file is created using the same function
used to open files.
If you use fopen() on a file that does not exist, it will create it,
given that the file is opened for writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The
file will be created in the same directory where the PHP code
resides:
Example
$myfile = fopen("testfile.txt", "w")

PHP File Permissions

If you are having errors when trying to get this code to run,
check that you have granted your PHP file access to write
information to the hard drive.
PHP Write to File - fwrite()

The fwrite() function is used to write to a file.


The first parameter of fwrite() contains the name of the file to
write to and the second parameter is the string to be written.
The example below writes a couple of names into a new file
called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open
file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Notice that we wrote to the file "newfile.txt" twice. Each time


we wrote to the file we sent the string $txt that first contained
"John Doe" and second contained "Jane Doe". After we finished
writing, we closed the file using the fclose() function.
If we open the "newfile.txt" file it would look like this:
John Doe
Jane Doe
COOKIES
What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. 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.

Create Cookies With PHP

• A cookie is created with the setcookie() function.

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

PHP Create/Retrieve a Cookie


• The following example creates a cookie named "user" with the
value "John Doe". The cookie will expire after 30 days (86400 *
30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).

• We then retrieve the value of the cookie "user" (using the global
variable $_COOKIE). We also use the isset() function to find
out if the cookie is set:

Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
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];
}
?>

</body>
</html>

Note: The setcookie() function must appear BEFORE the <html> tag.

Note: The value of the cookie is automatically URLencoded when


sending the cookie, and automatically decoded when received (to
prevent URLencoding, use setrawcookie() instead).

Modify a Cookie Value

To modify a cookie, just set (again) the cookie using


the setcookie() function:

Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<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];
}
?>

</body>
</html>

Delete a Cookie

To delete a cookie, use the setcookie() function with an expiration


date in the past:

Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

You might also like