KEMBAR78
PHP File Handling | PDF | Http Cookie | Php
0% found this document useful (0 votes)
4 views12 pages

PHP File Handling

This document covers PHP file handling and cookie/session management. It explains functions for creating, reading, and writing files, such as readfile(), fopen(), fread(), and fwrite(), along with their usage examples. Additionally, it introduces cookies and sessions, detailing how to create, modify, and delete cookies, as well as how to manage session variables across multiple pages.

Uploaded by

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

PHP File Handling

This document covers PHP file handling and cookie/session management. It explains functions for creating, reading, and writing files, such as readfile(), fopen(), fread(), and fwrite(), along with their usage examples. Additionally, it introduces cookies and sessions, detailing how to create, modify, and delete cookies, as well as how to manage session variables across multiple pages.

Uploaded by

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

UNIT – IV

PHP File Handling


PHP Manipulating Files

PHP has several functions for creating, reading, uploading, and editing files.
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):

Ex
<!DOCTYPE html>
<html>
<body>

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

</body>
</html>
Ans
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 Language236

The readfile() function is useful if all you want to do is open up a file and read its contents.

The next chapters will teach you more about file handling.
PHP File Open/Read/Close

In this chapter we will teach you how to open, read, and close a file on the server.

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
<!DOCTYPE html>
<html>
<body>

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

</body>
</html>
Ans
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

Tip: The fread() and the fclose() functions will be explained below.

The file may be opened in one of the following modes:

Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file

a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file.
Creates a new file if the file doesn't exist

x Creates a new file for write only. Returns FALSE and an error if file already exists

r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file.
Creates a new file if the file doesn't exist

x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
PHP Read File - fread()
The fread() function reads from an open file.

The first parameter of fread() contains the name of the file to read from and the second parameter specifies the
maximum number of bytes to read.

The following PHP code reads the "webdictionary.txt" file to the end:

fread($myfile,filesize("webdictionary.txt"));

PHP Close File - fclose()

The fclose() function is used to close an open file.

It's a good programming practice to close all files after you have finished with them. You don't want an open file
running around on your server taking up resources!

The fclose() requires the name of the file (or a variable that holds the filename) we want to close:

Ex
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Read Single Line - fgets()

The fgets() function is used to read a single line from a file.

The example below outputs the first line of the "webdictionary.txt" file:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>

</body>
</html>
Ans
AJAX = Asynchronous JavaScript and XML

Note: After a call to the fgets() function, the file pointer has moved to the next line.
PHP Check End-Of-File - feof()

The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>

</body>
</html>
Ans
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
PHP Read Single Character - fgetc()

The fgetc() function is used to read a single character from a file.

The example below reads the "webdictionary.txt" file character by character, until end-of-file is reached:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>

</body>
</html>
Ans
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
Note: After a call to the fgetc() function, the file pointer moves to the next character.
PHP File Create/Write

In this chapter we will teach you how to create and write to a file on the server.

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:

ExampleGet your own PHP Server


$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
PHP Overwriting

Now that "newfile.txt" contains some data we can show what happens when we open an existing file for writing.
All the existing data will be ERASED and we start with an empty file.

In the example below we open our existing file "newfile.txt", and write some new data into it:

Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just wrote is
present:

Mickey Mouse
Minnie Mouse

PHP Append Text

You can append data to a file by using the "a" mode. The "a" mode appends text to the end of the file, while the
"w" mode overrides (and erases) the old content of the file.

In the example below we open our existing file "newfile.txt", and append some text to it:

Example
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "Donald Duck\n";
fwrite($myfile, $txt);
$txt = "Goofy Goof\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

If we now open the "newfile.txt" file, we will see that Donald Duck and Goofy Goof is appended to the end of
the file:

Mickey Mouse
Minnie Mouse
Donald Duck
Goofy Goof
UNIT - V

PHP 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);

Only the name parameter is required. All other parameters are optional.

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:

ExampleGet your own PHP Server


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

Check if Cookies are Enabled


The following example creates a small script that checks whether cookies are enabled. First, try to create
a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>

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

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.

Tip: If you need a permanent storage, you may want to store the data in a database.

Start a PHP Session


A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and
set some session variables:

ExampleGet your own PHP Server


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

Run example »

Note: The session_start() function must be the very first thing in your document. Before any HTML
tag

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we will access the session
information we set on the first page ("demo_session1.php").

Notice that session variables are not passed individually to each new page, instead they are retrieved
from the session we open at the beginning of each page (session_start()).

Also notice that all session variable values are stored in the global $_SESSION variable:

Example
<?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>

Run example »

Another way to show all the session variable values for a user session is to run the following code:

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>

</body>
</html>

Run example »

How does it work? How does it know it's me?

Most sessions set a user-key on the user's computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the
computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.

Modify a PHP Session Variable


To change a session variable, just overwrite it:

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

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

Run example »

Destroy a PHP Session


To remove all global session variables and destroy the session,
use session_unset() and session_destroy():

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

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

// destroy the session


session_destroy();
?>

</body>
</html>

Run example »

You might also like