0% found this document useful (0 votes)
6 views

Files in PHP

The document discusses PHP functions for file handling including opening, reading, writing, and closing files. It explains how to use functions like fopen(), fread(), fwrite(), fclose() providing examples of opening files in different modes, reading content line by line or character by character, writing data to files, and deleting files.

Uploaded by

Firomsa Dine
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Files in PHP

The document discusses PHP functions for file handling including opening, reading, writing, and closing files. It explains how to use functions like fopen(), fread(), fwrite(), fclose() providing examples of opening files in different modes, reading content line by line or character by character, writing data to files, and deleting files.

Uploaded by

Firomsa Dine
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Web Design and Programming

Files in PHP

1 Department of Software Engineering 05/08/2024


PHP File Handling
Manipulating files is a basic for serious programmers
and PHP gives you a great deal of tools for creating,
uploading, and editing files.
 Before you can do anything with a file it has to be exist!
 In PHP, a file is created using a command that is also used to
open files.
 In PHP the fopen function is used to open files.
 However, it can also create a file if it does not find the file
specified in the function call.
 So if you use fopen on a file that does not exist, it will create
it, given that you open the file for writing or appending.
2 Department of Software Engineering 05/08/2024
Opining a File
The fopen function needs two important parameter.
The first parameter of this function contains the name of
the file to be opened and the second parameter specifies
in which mode the file should be opened(what we plan to
do with that file read, write… )
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>

3 Department of Software Engineering 05/08/2024


Modes of a file
 The three basic ways to open a file and the corresponding character that
PHP uses.
Read: 'r'
 Open a file for read only use. The file pointer begins at the front of the
file.
Write: 'w'
 Open a file for write only. In addition, the data in the file is erased and
you will begin writing data at the beginning of the file. This is also
called truncating a file.
 The file pointer begins at the start of the file.

Append: 'a'
 Open a file for write only. However, the data in the file is preserved and
you begin writing data at the end of the file.
 The file pointer begins at the end of the file.
 ‘x’ - Write only. Creates a new file. Returns FALSE and an error if file
already exists
4 Department of Software Engineering 05/08/2024
Opening a File-Example
 If the fopen() function is unable to open the specified file, it
returns 0 (false).
Example
 The following example generates a message if the fopen()
function is unable to open the specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
5 Department of Software Engineering 05/08/2024
Closing a File
 The fclose() function is used to close an open file:
 The function fclose requires the file handle that we want to close down.
 After a file has been closed down with fclose it is impossible to read, write or
append to that file unless it is once more opened up with the fopen function.

<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
Check End-of-file
 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.
 Note: You cannot read from files opened in w, a, and x mode!
if (feof($file)) echo "End of file";
6 Department of Software Engineering 05/08/2024
Reading a File
 The fread function is used to get data out of a file.
 The function requires a file handle, which we have, and an
integer to tell the function how much data, in bytes, it is
supposed to read.
 One character is equal to one byte. If you wanted to read the
first five characters then you would use five as the integer.
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
?>

7 Department of Software Engineering 05/08/2024


Reading a File…
 If you wanted to read all the data from the file, then you
need to get the size of the file.
 The filesize function returns the length of a file, in bytes,
which is just what we need!
 The filesize function requires the name of the file that is to
be sized up.
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
?>
8 Department of Software Engineering 05/08/2024
Reading a File Line by Line
 The fgets() function is used to read a single line from a file.
 The fgets function searches for the first occurrence of "\n" the newline
character.
Example
 The example below reads a file line by line, until the end of file is
reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
9 Department of Software Engineering 05/08/2024
Reading a File Character by Character
 The fgetc() function is used to read a single character from a file.
 Note: After a call to this function the file pointer moves to the next
character.
Example
 The example below reads a file character by character, until the end
of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
10 Department of Software Engineering 05/08/2024
Exercise
1. Write a program that count the number
of words in the given text.
2. Write a program that display a word
with maximum character from a given
text.

11 Department of Software Engineering 05/08/2024


Writing in to a file
 The fwrite function allows data to be written to any type of file.
 It takes two parameters:- first parameter is the file handler and its
second parameter is the string of data that is to be written.
 Below we are writing a couple of names into our test file
testFile.txt and separating them with a carriaged return.
<?php
$myFile = "testFile.txt";
$file = fopen($myFile, 'w') or die("can't open file");
$stringData = “Abebe Dereje\n";
fwrite($file, $stringData);
$stringData = “Debela Haile\n";
fwrite($file, $stringData);
fclose($fh);
?>

12 Department of Software Engineering 05/08/2024


Deleting a File
If you unlink a file, you are effectively causing the
system to forget about it or delete it!
Before you can delete (unlink) a file, you must first be
sure that it is not open in your program.
Example
$myFile = "testFile.txt";
unlink($myFile);
The testFile.txt should now be removed.

13 Department of Software Engineering 05/08/2024


PHP Filesystem Functions
chmod() Changes the file mode
chown() Changes the file owner
copy() Copies a file
delete() Deletes a file like that of unlink() or unset()
dirname() Returns the directory name component of a
path
disk_free_space() Returns the free space of a directory
disk_total_space() Returns the total size of a directory
fclose() Closes an open file
feof() Tests for end-of-file on an open file

14 Department of Software Engineering 05/08/2024


PHP Filesystem Functions…
 fgetc() Returns a character from an open file
 fgets() Returns a line from an open file
 fgetss() Returns a line, with HTML and PHP tags removed,
from an open file
 file() Reads a file into an array
 file_exists() Checks whether or not a file or directory exists
 file_get_contents() Reads a file into a string
 file_put_contents() Writes a string to a file
 fileatime() Returns the last access time of a file
 filectime() Returns the last change time of a file
 filemtime() Returns the last modification time of a file

15 Department of Software Engineering 05/08/2024


PHP Filesystem Functions…
 fileowner() Returns the user ID (owner) of a file
 fileperms() Returns the permissions of a file
 filesize() Returns the file size
 filetype() Returns the file type
 flock() Locks or releases a file
 fnmatch() Matches a filename or string against a specified
pattern
 fopen() Opens a file or URL
 fpassthru() Reads from an open file, until EOF, and writes
the result to the output buffer
 fread() Reads from an open file

16 Department of Software Engineering 05/08/2024


PHP Filesystem Functions…
 fwrite() Writes to an open file
 is_dir() Checks whether a file is a directory
 is_executable() Checks whether a file is executable
 is_file() Checks whether a file is a regular file
 is_link() Checks whether a file is a link
 is_readable() Checks whether a file is readable
 is_uploaded_file() Checks whether a file was uploaded via
HTTP POST
 is_writable() Checks whether a file is writeable
 mkdir() Creates a directory
 move_uploaded_file() Moves an uploaded file to a new location

17 Department of Software Engineering 05/08/2024


PHP Filesystem Functions…
readfile() Reads a file and writes it to the output buffer
realpath() Returns the absolute pathname
rename() Renames a file or directory
rmdir() Removes an empty directory
set_file_buffer() Sets the buffer size of an open file
stat() Returns information about a file
umask() Changes file permissions for files
unlink() Deletes a file

18 Department of Software Engineering 05/08/2024


PHP File Upload
 With PHP it is possible to upload files to the server.
Create an Upload-File Form
 To allow users to upload files from a form can be very useful.
 Look at the following HTML form for uploading files:
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
19 Department of Software Engineering 05/08/2024
PHP File Upload…
Notice the following about the HTML form above:
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 type="file" attribute of the <input> tag specifies
that the input should be processed as a file.
For example, when viewed in a browser, there will be
a browse-button next to the input field.
Note: Allowing users to upload files is a big security
risk. Only permit trusted users to perform file uploads.
20 Department of Software Engineering 05/08/2024
Create The Upload Script
 The "upload_file.php" file contains the code for uploading a file:
<?php
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"];
}
?>
21 Department of Software Engineering 05/08/2024
Create The Upload Script…
 By using the global PHP $_FILES array you can upload files from
a client computer to the remote server.
 The first parameter is the form's input name and the second index
can be either "name", "type", "size", "tmp_name" or "error". Like
this:
$_FILES["file"]["name"] - the name of the uploaded file
$_FILES["file"]["type"] - the type of the uploaded file
$_FILES["file"]["size"] - the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the
file stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload
 For security reasons, you should add restrictions on what the user
is allowed to upload.

22 Department of Software Engineering 05/08/2024


Restrictions on Upload
In this script we add some restrictions to the {
file upload. The user may only upload .gif or echo "Upload: " . $_FILES["file"]["name"] . "<br
.jpeg files and the file size must be under />";
20 kb. echo "Type: " . $_FILES["file"]["type"] . "<br />";
<?php echo "Size: " . ($_FILES["file"]["size"] / 1024) . "
Kb<br />";
if ((($_FILES["file"]["type"] == "image/gif")
echo "Stored in: " . $_FILES["file"]["tmp_name"];
|| ($_FILES["file"]["type"] == "image/jpeg"))
}
&& ($_FILES["file"]["size"] < 20000))
}
{
else
if ($_FILES["file"]["error"] > 0)
{
{
echo "Invalid file";
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
}
?>
else

23 Department of Software Engineering 05/08/2024


Saving the Uploaded File
The examples above create a temporary copy of the
uploaded files in the PHP temp folder on the server.
The temporary copied files disappears when the script
ends.
To store the uploaded file we need to copy it to a
different location:
The script below checks if the file already exists, if it
does not, it copies the file to the specified folder.
Note: This example saves the file to a new folder
called "upload"

24 Department of Software Engineering 05/08/2024


<?php ["name"]))
if (($_FILES["file"]["type"] == "image/gif") {
|| ($_FILES["file"]["type"] == "image/pjpeg") echo $_FILES["file"]["name"] . " already
&& ($_FILES["file"]["size"] < 20000)) exists. ";
{ }
if ($_FILES["file"]["error"] > 0) else
{ {
echo "Return Code: " . $_FILES["file"] move_uploaded_file($_FILES["file"]
["error"] . "<br />"; ["tmp_name"],
} "upload/" . $_FILES["file"]["name"]);
else echo "Stored in: " . "upload/" . $_FILES["file"]
["name"];
{
}
echo "Upload: " . $_FILES["file"]["name"] .
"<br />"; }
echo "Type: " . $_FILES["file"]["type"] . }
"<br />"; else
echo "Size: " . ($_FILES["file"]["size"] / 1024) {
. " Kb<br />"; echo "Invalid file";
echo "Temp file: " . $_FILES["file"] }
25 Department of Software
["tmp_name"] Engineering
. "<br />"; 05/08/2024
?>
if (file_exists("upload/" . $_FILES["file"]
Server Side Includes
You can insert the content of a file into a PHP file before the
server executes it, with the include() or require() function.
The two functions are identical in every way, except how
they handle errors.
The include() function generates a warning (but the script
will continue execution) while
The require() function generates a fatal error (and the script
execution will stop after the error).
These two functions are used to create functions, headers,
footers, or elements that can be reused on multiple pages.
This can save the developer a considerable amount of time.

26 Department of Software Engineering 05/08/2024


The include() Function
 The include() function takes all the text in a specified file and
copies it into the file that uses the include function.
Example
 Assume that you have a standard header file, called
"header.php". To include the header file in a page, use the
include() function, like this:
<html>
<body>
<?php include("header.php"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
27 Department of Software Engineering 05/08/2024
The require() Function
 The require() function is identical to include(), they only handle
errors differently.
 If you include a file with the include() function and an error
occurs, you might get an error message like the one below.
 Example
<html>
<body>
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
28 Department of Software Engineering 05/08/2024
The require() Function…
Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
Hello World!
Notice that the echo statement is still executed! This is
because a Warning does not stop the script execution.

29 Department of Software Engineering 05/08/2024


The require() Function…
 Now, let's run the same example with the require() function.
<?php
require("wrongFile.php");
echo "Hello World!";
?>
 Error message:
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
 The echo statement was not executed because the script
execution stopped after the fatal error.
Department of Software Engineering
30 05/08/2024
The End
Questions

! !!
OU
Y
N K
A
TH

31 Compiled By: Melkamu D. 05/08/2024

You might also like