0% found this document useful (0 votes)
25 views61 pages

Advanced IP-Chapter-3 - Lect-6, 7

The document discusses PHP functions for including files and navigating directories and files. It covers include(), require(), file paths, touch() for creating files, unlink() for deleting files, and functions for opening, writing, appending, reading and closing files.

Uploaded by

Abrham Tegegne
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)
25 views61 pages

Advanced IP-Chapter-3 - Lect-6, 7

The document discusses PHP functions for including files and navigating directories and files. It covers include(), require(), file paths, touch() for creating files, unlink() for deleting files, and functions for opening, writing, appending, reading and closing files.

Uploaded by

Abrham Tegegne
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/ 61

1

Chapter 3 :

Working with
Files and Directories
include() and require() Functions
2

 These two PHP functions can be used to included one PHP


file into another PHP file.
 You can include the content of a PHP file into another PHP
file before the server executes it.
 This is a strong point of PHP which helps in creating
functions, headers, footers, or elements that can be reused
on multiple pages.
 This will help developers to make it easy to change the
layout of complete website with minimal effort.
 If there is any change required then instead of changing
thousand of files just change included file.
include() and require() Function…
3

 When you use the include(), include_once(),


require(), or require_once() statements in PHP,
you are instructing a certain file and all of its
contents to be "included" into your script that is
calling it.
 This is very handy for making modular reusable
code structures, even in simple applications.
 The include() statement will include the desired
file if the file can be found through the path
specified in the statement.
include() and require() Function…
4

 If the desired file cannot be found, no errors will


occur, but the file and its contents will not be
included.
 The same file can be included multiple times into the
calling script.
 Using include_once() you can command the calling
script to only include a certain file one time and no
more.
 The require() statement works a lot like the include()
statement in the respect that will bring another file
and its contents into the calling script.
include() and require() Function…
5

 It is recommended to use the require() function instead


of include(), because scripts should not continue
executing if files are missing or misnamed.
 The big difference is that using require() will "require"
the file to be at the specified location on server.
 If the desired file to require cannot be found, an error
will occur in your script, and the script will terminate.
 Using require_once() you can command the calling
script to only require a certain file one time and no
more.
For the following code examples we first need a file to
include, let's create that now:
6

 Name this file "my_file.php" and make sure it


is living in the same directory as the calling
file:

<?php
$var1=“Hello world!”;
?>
Now let's include that file into our main calling file by
doing the following:
7

<?php
include("my_file.php");
echo $var1;
?>

Hello World!
Here is an example of using each type:
8
<?php
include ("file1.php");
include_once ("file2.php");
require ("file3.php");
require_once ("file4.php");
// All 4 files would be included into your main
script
// file1.php and file3.php can be included
multiple times
// file2.php and file4.php cannot be included
multiple times
?>
Here are alternate ways of writing your include and
require statement values that all work the same:
9

<?php
// All of the lollowing syntax will work the same
include ("my_file.php");
include "my_file.php";
include 'my_file.php';
?>
Communicate Between Two Servers Using PHP
includes
10
 Using the include or require statements we can also
perform cross domain scripting from one server, to a
completely different server.
 This comes in handy when you are looking to create
PHP processing scripts and engines that nobody can
view the source to but you.
 It remains on your server but you can allow other
sites to connect to it.
 Maybe even for a fee if the application performs
some cool task that helps people's business.
Here is an example of placing a full URL to
perform PHP scripting between two servers.
11

<?php
// include a script into another script from another server
include "http://www.yourwebsite.com/yourScript.php";
?>
 And here is an example of sending variables
through the URL string to the script waiting to
be included.
 That script can then process and return values

and information according to those variables.


12

<?php
// include a script into a caller script from another server, and send variables
include "http://www.yourwebsite.com/yourScript.php?name=John&pin=8558";
?>
 Since the include, require, require_once, and
include_once statements all work in a similar way,
all four could be used to script from one server to
another using PHP.
Here are alternate ways of writing the inclusion.
13

<?php
include "http://www.yourwebsite.com/yourScript.php?
name=John&pin=8558";
include_once "http://www.yourwebsite.com/yourScript.php?
name=John&pin=8558";
require "http://www.yourwebsite.com/yourScript.php?
name=John&pin=8558";
require_once "http://www.yourwebsite.com/yourScript.php?
name=John&pin=8558";
14

// Or you may see them wrapped in parenthesis like this:


include ("http://www.yourwebsite.com/yourScript.php?
name=John&pin=8558");
// Which is not required but will also not break the script
// include and require are not functions, they are language
constructs
// so the parenthesis are not needed at all at this time
?>
File Paths and Directory Script Navigation
15

In this quick simple lesson you will learn how to


navigate to directories and file paths through
code to connect to the files you need no matter
where they reside on your server.
Here are code examples of directory and file
path navigation:
<?php
// These first 5 examples use relative referenced
paths(relative to where script is)
16

$my_file = "somefile.php"; // Connect to file in same folder


$my_file = "myFolder/somefile.php"; // File in a folder
within the current folder
// Connect to file in a folder within a folder
$my_file = "myFolder/anotherFolder/somefile.php";
$my_file = "../somefile.php"; // Connect to file in parent
directory(jump up one level)
$my_file = "../../somefile.php"; // File 2 parent folders
up(jump up two levels)
// This example is referencing the file by full URL
$my_file =
"http://www.anyDomainName.com/somefile.php";
?>
17
 Referencing a file path using the full URL can
lead to errors using some functions.
 It is best to always use a relative path to reference
a file if possible.
 As you can see in the code example it is very
simple to grasp.
 There are only two directions you can go...
in(into folders) and up(into parent folders).
 And that is all the file navigation you need when
scripting within your own domain or server.
Creating and Deleting Files Through Code in PHP
18

 We can create or delete files through code using the


touch() function to create them, and the unlink()
function to delete them.
 Both functions are part of the Filesystem family of
functions.
 You can check to see whether a file exists before you
attempt either function, and you can also check to see
if the file exists to verify that touch created it for you
if it was not already there.
 touch() will create the file if it does not exist already.
 unlink() will delete any type of file from your server.
Here is an example showing how to use the touch()
function to create a file:
19

<?php
// you can create any extension type file(html, php, xml, etc...)
$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";
}
?>

The file has been created


Here is an example showing how to use the
unlink() function to delete a file:
20

<?php
// you can delete any extension type file(html, php, jpg, gif,
flv, swf, etc...)
$file_x = "my_file.txt";
if (file_exists($file_x)) {
unlink($file_x); // delete it here only if it exists
echo "The file has been deleted";
} else {
echo "The file was not found and could not be deleted";
}
?>
The file has been deleted
Opening, Writing, Appending, Closing, and
Reading Files in PHP
21

 There may be times when you need to open a


file for reading, writing, or appending it.
 Using the PHP Filesystem function of fopen()

gives us options when opening a file.


 The PHP fopen() function is used to open a

file. It requires two arguments stating first the


file name and then mode in which to operate.
 You simply choose the mode that you want

when you execute the fopen() function.


22

 Files modes can be specified as one of the


options in the following table.
 The three most widely used modes are "w",

"a", and "r".


 After the file is opened we use fwrite() to

place the data we desire into it.


 We also utilize the fclose() function to close

the file handler.


Mode Mode Functionality
w Write to a file. If the file does not exist, attempt to create it.
23

w+ Reading and writing to a file. If the file does not exist, attempt to create it.
a Write to a file. If the file does not exist, attempt to create it.
a+ Reading and writing. If the file does not exist, attempt to create it.
r Reading file only.
r+ Reading and writing to a file.
Create and open for writing only. If the file already exists, fopen() will fail by returning
x
FALSE and generating an error. If the file does not exist, attempt to create it.
Create and open for reading and writing. If the file already exists, fopen() will fail by
x+
returning FALSE and generating an error. If the file does not exist, attempt to create it.
24
 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.
25

 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:
26
<?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);
27

// 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);
?>
28

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
displayed its contents.
Reading a file
29
 Once a file is opened using fopen() function it
can be read with a function called fread().
 This function requires two arguments. These

must be 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.
So here are the steps required to read a file with PHP.
30

 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 following example assigns the content of a text file to
a variable then displays those contents on the web page.
31

<html> <head>
<title>Reading a file using PHP</title>
</head> <body>
<?php
$filename = “my_file.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
32

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
</body> </html>
Writing a file
33

 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 heading in site it.
 After closing this file its existence is confirmed using
file_exist() function which takes file name as an argument
<?php
$filename = "/home/user/guest/newfile.txt";
34 $file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
html>
<head>
<title>Writing a file using PHP</title>
</head>
<?php
if( file_exist( $filename ) )
35 {
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
{
echo ("File $filename does not exit" );
}
?>
</body>
</html>
Uploading Files
36

 A PHP script can be used with a 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
Uploading Files

37

 Web applications allow visitors to upload files to


and from from their local computer (often referred
to as the client)
 The files that are uploaded and downloaded may be
simple text files or more complex file types, such as
images, documents, or spreadsheets…
Selecting the File

38

 Files are uploaded through an (X)HTML form using


the “post” method
 An enctype attribute in the opening form tag
must have a value of “multipart/form-data,” which
instructs the browser to post multiple sections – one
for regular form data and one for the file contents
Selecting the File (continued)

39

 The file input field creates a Browse button for


the user to navigate to the appropriate file to upload
<input type="file" name="picture_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

40

 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
Retrieving the File Information (continued)
41

// Contains the name of the original file


$_FILES['picture_file']['name']

// Contains the size of the uploaded file in bytes


$_FILES['picture_file']['size']

// Contains the type of the file


$_FILES['picture_file']['type']
Creating an upload script:
42
 There is one global PHP variable called $_FILES.
 This variable is an associate double dimension array and keeps
all the information related to uploaded file.
 So if the value assigned to the input's name attribute in
uploading form was file, then PHP would create following five
variables:
 $_FILES['file']['tmp_name']- the uploaded file in the temporary
directory on the web server.
 $_FILES['file']['name'] - the actual name of the uploaded file.
 $_FILES['file']['size'] - the size in bytes of the uploaded file.
 $_FILES['file']['type'] - the MIME type of the uploaded file.
 $_FILES['file']['error'] - the error code associated with this file
upload.
The process of uploading a file follows these steps
43

 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 process of uploading a file follows these steps cont…
44

 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.
 An uploaded file could be a text file or image file or any
document.
Creating an upload form:
45

 The following HTML code below creates an uploader form.


 This form is having method attribute set to post and
enctype attribute is set to multipart/form-data
<html> <head><title>File Uploading Form</title></head>
<body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="/php/file_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>
Cont…
46

 This will display following result:


File Upload:
Select a file to upload:

 NOTE: This is just dummy form and would not work.


Cont…
47

 The following example below attempts to copy a


file uploaded by the HTML Form listed in previous
section page to /var/www/html directory which is
document root of your PHP server and it will
display all the file's detail upon completion.
 Please note that if you are going to display
uploaded file then don't try with binary files like
images or word document.
Cont…
48

 Here is the code of uploader.php script which will take care of


uploading a file.
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "/var/www/html" ) or
die( "Could not copy file!");
}
else
{
die("No file specified!");
}
?>
Cont…
49

<html> <head> <title>Uploading Complete</title>


</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>
Cont…
50
 When you will upload a file using upload form
and upload script, it will display following result:
 Uploaded File Info:

 Sent file: uploadedfile.txt

 File size: 2003 bytes

 File type: image/jpg


copy() function : How to make a copy of a file
using PHP script
51

 The PHP built in copy() function will make a copy


of a file that you specify on the server, and place
the new copy where you specify.
 It requires those two pieces of
information(function arguments) to perform its
operation, the source file to copy, and the
destination.
Cont…
52

 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
Cont…
53

<?php
// Try any file type with any extensions(.jpg, .html, .doc, .pdf, etc...)
$targetFile = "test.html";
$targetCopy = "test_copy.html";
// Use the built in copy function now
copy($targetFile, $targetCopy);
// Now you can choose to run a check to see if the new copy exists,
// or you have the option to do nothing and assume it is made
if (file_exists($targetCopy)) {
echo "Success : $targetCopy has been made";
} else {
echo "Failure: $targetCopy does not exist";
}
?>
Cont…
54

if (file_exists(“sfweather.txt”)) {
if(is_dir(“history”)) {
if (copy(“sfweather.txt”,
“history\\sfweather01-27-2006.txt”))
echo “<p>File copied
successfully.</p>”;
else
echo “<p>Unable to copy the
file!</p>”;
}
else
echo (“<p>The directory does not
exist!</p>”);
}
else
echo (“<p>The file does not exist!</p>”);
Renaming Files and Directories
55

 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)
Removing Files and Directories
56

 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
Creating and Removing Directories (folders)
57

 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.
Cont…
58
 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 = "myNewFolder";
mkdir($newfolder, 0777); //The mode is 0777 by default,
//which means the widest possible access. mode is
//ignored on Windows.
// 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 />";
// it is good to check and see if it is_dir before we remove it
chmod(file,mode)
The mode parameter consists of four numbers:
 The first number is always zero
59  The second number specifies permissions for the owner

 The third number specifies permissions for the owner's user group

 The fourth number specifies permissions for everybody else

Possible values (to set multiple permissions, add up the following numbers):
1 = execute permissions
2 = write permissions
4 = read permissions
Example
<?php
// Read and write for owner, nothing for everybody else
chmod("test.txt",0600);
// Read and write for owner, read for everybody else
chmod("test.txt",0644);
/ Everything for owner, read and execute for everybody else
chmod("test.txt",0755);
// Everything for owner, read for owner's group
chmod("test.txt",0740);
?>
Cont…
60

// check to see if the directory exists


if (!file_exists($newfolder)) {
echo "The $newfolder directory has been
removed<br /><br />";
} else {
echo "ERROR: Trouble removing $newfolder
directory";
}
?>
61

The myNewFolder directory has been created


The myNewFolder directory has been removed

You might also like