SlideShare a Scribd company logo
Files in PHP
Web Design and Programming
5/8/2024
1 Department of Software Engineering
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.
5/8/2024
2 Department of Software Engineering
Opining a File
5/8/2024
Department of Software Engineering
3
 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>
Modes of a file
5/8/2024
Department of Software Engineering
4
 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
Opening a File-Example
5/8/2024
Department of Software Engineering
5
 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>
Closing a File
5/8/2024
Department of Software Engineering
6
 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";
Reading a File
5/8/2024
Department of Software Engineering
7
 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;
?>
Reading a File…
5/8/2024
Department of Software Engineering
8
 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;
?>
Reading a File Line by Line
5/8/2024
Department of Software Engineering
9
 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);
?>
Reading a File Character by Character
5/8/2024
Department of Software Engineering
10
 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);
?>
Exercise
5/8/2024
Department of Software Engineering
11
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.
Writing in to a file
5/8/2024
Department of Software Engineering
12
 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 Derejen";
fwrite($file, $stringData);
$stringData = “Debela Hailen";
fwrite($file, $stringData);
fclose($fh);
?>
Deleting a File
5/8/2024
Department of Software Engineering
13
 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.
PHP Filesystem Functions
5/8/2024
Department of Software Engineering
14
 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
PHP Filesystem Functions…
5/8/2024
Department of Software Engineering
15
 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
PHP Filesystem Functions…
5/8/2024
Department of Software Engineering
16
 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
PHP Filesystem Functions…
5/8/2024
Department of Software Engineering
17
 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
PHP Filesystem Functions…
5/8/2024
Department of Software Engineering
18
 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
PHP File Upload
5/8/2024
Department of Software Engineering
19
 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>
PHP File Upload…
5/8/2024
Department of Software Engineering
20
 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.
Create The Upload Script
5/8/2024
Department of Software Engineering
21
 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"];
}
?>
Create The Upload Script…
5/8/2024
Department of Software Engineering
22
 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.
Restrictions on Upload
5/8/2024
Department of Software Engineering
23
In this script we add some restrictions to
the
file upload. The user may only upload .gif
or
.jpeg files and the file size must be under
20 kb.
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
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"];
}
}
else
{
echo "Invalid file";
}
?>
Saving the Uploaded File
5/8/2024
Department of Software Engineering
24
 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"
5/8/2024
Department of Software Engineering
25
<?php
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/pjpeg")
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " .
$_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 "Temp file: " .
$_FILES["file"]["tmp_name"] . "<br />";
$_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"];
}
}
}
else
{
echo "Invalid file";
}
?>
Server Side Includes
5/8/2024
Department of Software Engineering
26
 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.
The include() Function
5/8/2024
Department of Software Engineering
27
 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>
The require() Function
5/8/2024
Department of Software Engineering
28
 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>
The require() Function…
5/8/2024
Department of Software Engineering
29
 Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:homewebsitetest.php on line 5
Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:php5pear')
in C:homewebsitetest.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.
The require() Function…
5/8/2024
Department of Software Engineering
30
 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:homewebsitetest.php on line 5
Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:php5pear')
in C:homewebsitetest.php on line 5
 The echo statement was not executed because the
script execution stopped after the fatal error.
The End
Questions
5/8/2024
Compiled By: Melkamu D.
31

More Related Content

Similar to Files in PHP.pptx g

FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operationsmussawir20
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
File management
File managementFile management
File management
lalithambiga kamaraj
 
lecture 10.pptx
lecture 10.pptxlecture 10.pptx
lecture 10.pptx
ITNet
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
Files in C
Files in CFiles in C
Files in C
Prabu U
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
DHARUNESHBOOPATHY
 
Files in php
Files in phpFiles in php
Files in php
sana mateen
 
File management
File managementFile management
File management
sumathiv9
 
File handling C program
File handling C programFile handling C program
File handling C program
Thesis Scientist Private Limited
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
Amarjith C K
 

Similar to Files in PHP.pptx g (20)

FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
File management
File managementFile management
File management
 
lecture 10.pptx
lecture 10.pptxlecture 10.pptx
lecture 10.pptx
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Files in C
Files in CFiles in C
Files in C
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Files in php
Files in phpFiles in php
Files in php
 
File management
File managementFile management
File management
 
Unit 8
Unit 8Unit 8
Unit 8
 
Unit v
Unit vUnit v
Unit v
 
File handling C program
File handling C programFile handling C program
File handling C program
 
File in C language
File in C languageFile in C language
File in C language
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 

More from FiromsaDine

Chapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptxChapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptx
FiromsaDine
 
Chapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptxChapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptx
FiromsaDine
 
Chapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptxChapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptx
FiromsaDine
 
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptxchapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
FiromsaDine
 
Chapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptxChapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptx
FiromsaDine
 
chapter_2_Source_code_generation_from_UML_model_edited_version.pptx
chapter_2_Source_code_generation_from_UML_model_edited_version.pptxchapter_2_Source_code_generation_from_UML_model_edited_version.pptx
chapter_2_Source_code_generation_from_UML_model_edited_version.pptx
FiromsaDine
 

More from FiromsaDine (6)

Chapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptxChapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptx
 
Chapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptxChapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptx
 
Chapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptxChapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptx
 
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptxchapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
chapter_one_Introduction_to_Object_Oriented_Programming_OOP.pptx
 
Chapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptxChapter 1-software-engineering-tools-and-practices.pptx
Chapter 1-software-engineering-tools-and-practices.pptx
 
chapter_2_Source_code_generation_from_UML_model_edited_version.pptx
chapter_2_Source_code_generation_from_UML_model_edited_version.pptxchapter_2_Source_code_generation_from_UML_model_edited_version.pptx
chapter_2_Source_code_generation_from_UML_model_edited_version.pptx
 

Recently uploaded

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 

Recently uploaded (20)

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 

Files in PHP.pptx g

  • 1. Files in PHP Web Design and Programming 5/8/2024 1 Department of Software Engineering
  • 2. 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. 5/8/2024 2 Department of Software Engineering
  • 3. Opining a File 5/8/2024 Department of Software Engineering 3  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>
  • 4. Modes of a file 5/8/2024 Department of Software Engineering 4  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
  • 5. Opening a File-Example 5/8/2024 Department of Software Engineering 5  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>
  • 6. Closing a File 5/8/2024 Department of Software Engineering 6  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";
  • 7. Reading a File 5/8/2024 Department of Software Engineering 7  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; ?>
  • 8. Reading a File… 5/8/2024 Department of Software Engineering 8  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; ?>
  • 9. Reading a File Line by Line 5/8/2024 Department of Software Engineering 9  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); ?>
  • 10. Reading a File Character by Character 5/8/2024 Department of Software Engineering 10  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); ?>
  • 11. Exercise 5/8/2024 Department of Software Engineering 11 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.
  • 12. Writing in to a file 5/8/2024 Department of Software Engineering 12  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 Derejen"; fwrite($file, $stringData); $stringData = “Debela Hailen"; fwrite($file, $stringData); fclose($fh); ?>
  • 13. Deleting a File 5/8/2024 Department of Software Engineering 13  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.
  • 14. PHP Filesystem Functions 5/8/2024 Department of Software Engineering 14  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
  • 15. PHP Filesystem Functions… 5/8/2024 Department of Software Engineering 15  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
  • 16. PHP Filesystem Functions… 5/8/2024 Department of Software Engineering 16  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
  • 17. PHP Filesystem Functions… 5/8/2024 Department of Software Engineering 17  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
  • 18. PHP Filesystem Functions… 5/8/2024 Department of Software Engineering 18  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
  • 19. PHP File Upload 5/8/2024 Department of Software Engineering 19  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>
  • 20. PHP File Upload… 5/8/2024 Department of Software Engineering 20  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.
  • 21. Create The Upload Script 5/8/2024 Department of Software Engineering 21  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"]; } ?>
  • 22. Create The Upload Script… 5/8/2024 Department of Software Engineering 22  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.
  • 23. Restrictions on Upload 5/8/2024 Department of Software Engineering 23 In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb. <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 20000)) { 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"]; } } else { echo "Invalid file"; } ?>
  • 24. Saving the Uploaded File 5/8/2024 Department of Software Engineering 24  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"
  • 25. 5/8/2024 Department of Software Engineering 25 <?php if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/pjpeg") && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_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 "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; $_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"]; } } } else { echo "Invalid file"; } ?>
  • 26. Server Side Includes 5/8/2024 Department of Software Engineering 26  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.
  • 27. The include() Function 5/8/2024 Department of Software Engineering 27  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>
  • 28. The require() Function 5/8/2024 Department of Software Engineering 28  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>
  • 29. The require() Function… 5/8/2024 Department of Software Engineering 29  Error message: Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:homewebsitetest.php on line 5 Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:php5pear') in C:homewebsitetest.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.
  • 30. The require() Function… 5/8/2024 Department of Software Engineering 30  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:homewebsitetest.php on line 5 Fatal error: require() [function.require]: Failed opening required 'wrongFile.php' (include_path='.;C:php5pear') in C:homewebsitetest.php on line 5  The echo statement was not executed because the script execution stopped after the fatal error.