Chapter 5 & 6
Chapter 5 & 6
Hello World!
Example 2
<?php <?php
include ("file1.php"); // All of the lollowing
include_once ("file2.php"); syntax will work the
require ("file3.php"); same
require_once ("file4.php"); include ("my_file.php");
// All 4 files would be included into
your main script include "my_file.php";
// file1.php and file3.php can be include 'my_file.php';
included multiple times ?>
// file2.php and file4.php cannot be
included multiple times
?>
PHP File Handling
• File handling is an important part of any web
application. You often need to open and process a
file for different tasks.
• PHP has several functions for creating, reading,
uploading, and editing files.
Creating and Deleting Files Through Code in PHP
• We can use touch() function to create file, and the
unlink() function to delete them.
• Both functions are part of the File system family of
functions.
• You can check to see whether a file exists before you
attempt either function.
▪ touch() will create the file if it does not exist already.
▪ unlink() will delete any type of file from your server.
Example-create a file
<?php
$file_x = "my_file.txt";
$createFile = touch($file_x);
if (file_exists($file_x)) {
echo "The file has been created";
} else {
echo "The file has not been created";
}
?>
9
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
• If an attempt to open a file fails then fopen returns a
value of false otherwise it returns a file pointer which is
used for further reading or writing to that file.
• After making a changes to the opened file it is
important to close it with the fclose() function.
• The fclose() function requires a file pointer as its
argument and then returns true when the closure
succeeds or false if it fails.
• It is important to note that any time you use several of
the modes above, the target file will be created on
server if it does not yet exist. Which makes it operate
as a file creation method like the touch() function.
• Here is a code example showing how to use a couple of
the modes above for reading and writing files:
11
Example-creating, writing and closing file
<?php
// Here we define the file path and name
$target_file = "my_file.txt";
// Here we define the string data that is to be placed into the file
$target_file_data = "This is the string data or code I want
to place in the newly created file.";
// Here we are creating a file(since it does not yet exist) and
adding data to it
$handle = fopen($target_file, "w");
fwrite($handle, $target_file_data); // write it
fclose($handle);
12
Cont..
// Here we are opening and appending to the file
$handle = fopen($target_file, "a");
// Here we define the string data that is to be appended to the data
already in file
$target_file_data = "Here is more data I want to append to the file.";
fwrite($handle, $target_file_data); // write it
fclose($handle);
// Here we display the file contents by including it
include($target_file);
?>
This is the string data or code I want to place in the newly created file. Here is more data I want
to append to the file.
In the code example above we created a file, wrote to it, closed it, appended data to it, then
13
displayed its contents.
Reading a file
• Once a file is opened using fopen() function it can be read
with a function called fread().
• This function requires two arguments which is the file pointer
and the length of the file expressed in bytes.
• The files's length can be found using the filesize() function
which takes the file name as its argument and returns the
size of the file expressed in bytes.
• Steps
▪ Open a file using fopen() function.
▪ Get the file's length using filesize() function.
▪ Read the file's content using fread() function.
▪ Close the file with fclose() function.
▪ The readfile() function is also useful to open a file and read its
contents. 14
Example
<html> <head> $filesize = filesize( $filename );
<title>Reading a file using $filetext = fread( $file, $filesize );
PHP</title> fclose( $file );
</head> <body>
<?php echo ( "File size : $filesize bytes" );
$filename = “my_file.txt"; echo ("<pre>$filetext</pre>" );
$file = fopen( $filename, "r" ); ?>
if( $file == false ) </body> </html>
{
echo ( "Error in opening file" );
exit();
}
Reading a file line by line
<?php
$filename = “my_file.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
Reading a File Character by Character
<?php
$filename = “my_file.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
{
echo fgetc($file);
}
fclose($file);
?>
Writing to a file
• A new file can be written or text can be appended to
an existing file using the PHP fwrite() function.
• This function requires two arguments specifying a file
pointer and the string of data that is to be written.
• Optionally a third integer argument can be included to
specify the length of the data to write.
• If the third argument is included, writing would will
stop after the specified length has been reached.
• The following example creates a new text file then
writes a short text inside.
• After closing this file its existence is confirmed using
file_exist() function which takes file name as an
argument
18
Example
html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
<?php
$filename = "newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
19
<?php
if( file_exist( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
{
echo ("File $filename does not exit" );
}
?>
</body>
</html>
20
PHP File Upload
• A PHP script can be used with an HTML form to
allow users to upload files to the server.
• Initially files are uploaded into a temporary
directory and then relocated to a target
destination by a PHP script.
• Information in the phpinfo.php page describes
the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum
permitted size of files that can be uploaded is
stated as upload_max_filesize.
• These parameters are set into PHP configuration
file php.ini
• Web applications allow visitors to upload files from their local
computer to the server
• Files are uploaded through an HTML form using the “post”
method
• The enctype attribute of the <form> tag specifies which content-
type to use when submitting the form.
• "multipart/form-data" is used when a form requires binary
data, like the contents of a file, to be uploaded
• The file input field creates a Browse button for the user to
navigate to the appropriate file to upload
<input type="file" name=“text-file" />
• The MAX_FILE_SIZE (uppercase) attribute of a hidden form field
specifies the maximum number of bytes allowed in the
uploaded file
▪ The MAX_FILE_SIZE hidden field must appear before the file
input field
Retrieving the File Information
• When the form is posted, information for the uploaded
file is stored in the $_FILES autoglobal array
• The $_FILES[] array contains five elements:
▪ $_FILES['picture_file']['error'] //Contains the error code
associated with the file
▪ $_FILES['picture_file']['tmp_name'] //Contains the
temporary location of the file contents
$_FILES['picture_file']['name'] // Contains the name of the
original file
▪ $_FILES['picture_file']['size'] // Contains the size of the
uploaded file in bytes
▪ $_FILES['picture_file']['type'] // Contains the type of the
file
23
The process of uploading a file follows these steps
• The user opens the page containing a HTML form featuring
a text files, a browse button and a submit button.
• The user clicks the browse button and selects a file to
upload from the local PC.
• The full path to the selected file appears in the text filed
then the user clicks the submit button.
• The selected file is sent to the temporary directory on the
server.
• The PHP script that was specified as the form handler in the
form's action attribute checks that the file has arrived and
then copies the file into an intended directory.
• The PHP script confirms the success to the user.
• As usual when writing files it is necessary for both
temporary and final locations to have permissions set that
enable file writing. If either is set to be read-only then
process will fail. 24
Creating an upload form:
• The following HTML code below creates an uploader form.
<html>
<head>
<title>File Uploading Form</title></head>
<body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="uploader.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" /> <br />
<input type="submit" value="Upload File" />
</form></body></html>
?> 25
• The following example below attempts to copy a file uploaded
by the HTML Form listed in previous section page to upload/
directory using copy() function. (uploader.php)
<html>
<head> <title>Uploading Complete</title>
<?php
if( $_FILES['file']['name'] != "" ){
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. "; }
else{
copy($_FILES["file"]["tmp_name"],"upload/" .
$_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; }
}else{
die("No file specified!"); } ?>
Display the information about the
uploaded file ..cont
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body></html>
• Use the copy() function to copy a file with
PHP
• The function returns a value of true if it is
successful or false if it is not
• The syntax for the copy() function is:
copy(source, destination)
• For the source and destination arguments:
▪ Include just the name of a file to make a copy in
the current directory, or
▪ Specify the entire path for each argument
Using move_uploaded_file() function to
<?php
upload file
if ($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br />"; }
else {
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"]; }
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. "; }
else{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
} echo "</br>"; ?>
Restrictions on Upload
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/ping"))
&& ($_FILES["file"]["size"] < 20000))
{
[...]
}
else
{
echo "Invalid file";
}
?>
PHP download
<?php
$file = "ab.jpg";
echo "<a href='download.php?
name=".$file."'>download</a> ";
?>
PHP download
<?php
$name= $_GET['name'];
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"" .
basename($name) . "\";");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name));
ob_clean();
flush();
readfile("upload/".$name); //showing the path to the
server where the file is to be download
exit;
?>
Renaming Files and Directories
• Use the rename() function to rename a file
or directory with PHP
• The rename() function returns a value of
true if it is successful or false if it is not
• The syntax for the rename() function is:
rename(old_name, new_name)
33
Removing Files and Directories
• Use the unlink() function to delete files and
the rmdir() function to delete directories
• Pass the name of a file to the unlink()
function and the name of a directory to the
rmdir() function
• Both functions return a value of true if
successful or false if not
• Use the file_exists() function to
determine whether a file or directory name
exists before you attempt to delete it
34
Creating and Removing Directories (folders)
• It is a simple matter to create or remove
directories(folders) on your server through script.
• To create directories all you have to do is supply two
arguements to the mkdir() function.
• The first arguement is the path and name of the
directory to be created.
• The second arguement is the folder's
chmod(permission) settings.
• To remove or delete directories with PHP we use the
rmdir() function.
• We give the directory path and name to the function
and it will remove it from that location.
35
Example: Create directory
• Here is a code example showing how to use the mkdir() to
create a folder, and rmdir() to remove it:
<?php
// Define path and new folder name
$newfolder = "upload/myNewFolder";
mkdir($newfolder, 0777);
// Make new folder and set file permissions on it ( chmod )
// check to see if it has been created or not using is_dir
if (is_dir($newfolder)) {
echo "The $newfolder directory has been created
<br /><br />";
}
36
Example: Remove a directory
// it is good to check and see if it is_dir before we remove
it , check to see if the directory exists
if (!file_exists($newfolder)) {
rmdir($newfolder); //removes the directory
echo "The $newfolder directory has been
removed<br /><br />";
}
else {
echo "ERROR: Trouble removing $newfolder directory";
}
?>
37
PHP Cookies
• 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.
<html>
<head><title>Cookie example</title><head><body>
How to Retrieve a Cookie Value?
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Mr x", $expire);
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?></body></html>
Using isset() function to check if a cookie
• 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>
Deleting a cookie
How to Delete a Cookie?
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
PHP Sessions: Starting 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>
Cont..
▪ In the example below, we create a simple page-
views counter.
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
• The unset() function is used to free the specified
session variable:
<?php
session_start();
if(isset($_SESSION['views']))
unset($_SESSION['views']);
?>
• You can also completely destroy the session by
calling the session_destroy() function:
<?php
session_destroy();
?>