Sie sind auf Seite 1von 12

Unit 3: Files and Directories in PHP

3.1. Reading files/ Directories


Files and directories have three levels of access: User, Group and Other. The three typical
permissions for files and directories are:
a. Read (r)
b. rite (!)
c. "#ecute (#)
$ stream is a channel used for accessin% a resource that you can read from and !rite to. The
input stream reads data from a resource (such as a file) !hile the output stream !rites data to a
resource. &n file operation, !e do have the follo!in% steps or procedures:'
(. Open the file stream !ith the fopen() function
)ynta#:- variable= open(text file!" mode!#$ !here mode mean r,
r*, !, !* etc as sho!n in the ne#t pa%e.
+. rite data to or read data from the file stream
, e use fread() function to read functions. e can also use fgets(#
function to read files or data. &t is !ritten !ith t!o parameters li-e
fgets(%&andle"%b'tes#
. Reads up to /bytes of data, stops at ne!line or end of file
("OF)
, 010 supports t!o basic functions for !ritin% data to te#t files:
. file(put(contents(# function !rites or appends a te#t strin% to
a file. &ts synta# for the file2put2contents() function is:
file2put2contents (filename, string3, options4
. f)rite(# function incrementally !rites data to a te#t file. &ts synta#
for the f!rite() function is: f!rite(/handle, data3, length4)5
6. 7lose the file stream !ith the fclose() function:' used !hen finished !or-in%
!ith a file stream to save space in memory
)ynta#:' fclose(file name t&at contains t&e opened files#$
/handle from the follo!in% e#ample.
"#ample:'
%&andle = fopen(*people+t,t*" *r*#$
)&ile (-feof(%&andle## .
ec&o fgets(%&andle" /012#$
ec&o *3br /4*$
5
fclose(%&andle#$
Files modes can be specified as one of the si# options in this table.
1
6ode Purpose
r Opens the file for readin% only. 0laces the file pointer at the be%innin% of the file.
r* Opens the file for readin% and !ritin%. 0laces the file pointer at the be%innin% of the file.
!
Opens the file for !ritin% only. 0laces the file pointer at the be%innin% of the file.
and truncates the file to 8ero len%th. &f files does not e#ist then it attempts to create a file.
!*
Opens the file for readin% and !ritin% only. 0laces the file pointer at the be%innin% of the file. and
truncates the file to 8ero len%th. &f files does not e#ist then it attempts to create a file.
a
Opens the file for !ritin% only. 0laces the file pointer at the end of the file. &f files does not e#ist
then it attempts to create a file.
a*
Opens the file for readin% and !ritin% only. 0laces the file pointer at the end of the file. &f files
does not e#ist then it attempts to create a file.
Once a file is opened usin% fopen(# function it can be read !ith a function called fread(#. This
function re9uires t!o ar%uments. These must be the file pointer and the len%th of the file
e#pressed in bytes.
The files:s len%th can be found usin% the filesi7e(# function !hich ta-es the file name as its
ar%ument and returns the si8e of the file e#pressed in bytes. )o here are the steps re9uired to read
a file !ith 010.
Open a file usin% fopen(# function.
Get the file:s len%th usin% filesi7e(# function.
Read the file:s content usin% fread(# function.
7lose the file !ith fclose(# function.
The follo!in% e#ample assi%ns the content of a te#t file to a variable then displays those contents
on the !eb pa%e.
;html<
;head<
;title<Readin% a file usin% 010;=title<
;=head<
;body<
;>php
/filename ? @=home=user=%uest=tmp.t#t@5
/file ? fopen( /filename, @r@ )5
if( /file ?? false )
A
echo ( @"rror in openin% file@ )5
e#it()5
B
/filesi8e ? filesi8e( /filename )5
/filete#t ? fread( /file, /filesi8e )5
2
fclose( /file )5
echo ( @File si8e : /filesi8e bytes@ )5
echo ( @;pre</filete#t;=pre<@ )5
><
;=body<
;=html<
8ote 9&at:- 9&ere are t)o :s&ortcut; functions t&at don;t re<uire a file to be opened:
, %lines = file(%filename#
. Reads entire file into an array !ith each line a separate entry in the array.
, %str = file(get(contents(%filename#
. Reads entire file into a sin%le strin%.
3+1+ =riting a file
$ ne! file can be !ritten or te#t can be appended to an e#istin% file usin% the 010 function as
discus in the previous discussions. These functions re9uire t!o ar%uments specifyin% a file
pointer and the strin% of data that is to be !ritten. Optionally a third inte%er ar%ument can be
included to specify the len%th of the data to !rite. &f the third ar%ument is included, !ritin%
!ould !ill stop after the specified len%th has been reached. The follo!in% is the synta# to !rite
files:'
f)rite(file )e )rite on it" string )&at )e )rite>"lengt& of string?#
The follo!in% e#ample creates a ne! te#t file then !rites a short te#t headin% inside it. $fter
closin% this file its e#istence is confirmed usin% file(e,ist(# function !hich ta-es file name as an
ar%ument. )ee the follo!in% e#ample ho! open file, !rite in file and close files
;>php
/filename ? @=home=user=%uest=ne!file.t#t@5
/file ? fopen( /filename, @!@ )5
if( /file ?? false )
A
echo ( @"rror in openin% ne! file@ )5
e#it()5
B
f!rite( /file, @This is a simple testCn@ )5
fclose( /file )5
><
;html<
;head<
;title<ritin% a file usin% 010;=title<
;=head<
;body<
;>php
if( file2e#ist( /filename ) )
A
3
/filesi8e ? filesi8e( /filename )5
/ms% ? @File created !ith name /filename @5
/ms% .? @containin% /filesi8e bytes@5
echo (/ms% )5
B
else
A
echo (@File /filename does not e#it@ )5
B
><
;=body<;=html<
&f an attempt to open a file fails then fopen returns a value of false other!ise it returns a file
pointer !hich is used for further readin% or !ritin% to that file.
$fter ma-in% a chan%es to the opened file it is important to close it !ith the fclose(# function.
The fclose(# function re9uires a file pointer as its ar%ument and then returns true !hen the
closure succeeds or false if it fails.
8ote t&at:-
The file(put(contents(# function can also !rites or appends a te#t strin% to a file, doesnDt
need to use fopen or fclose. &f no data !as !ritten to the file, the function returns a value
of E !hich can determine if data !as successfully !ritten to the file. The F&F"2$00"GH
constant appends data to any e#istin% contents in the specified filename instead of
over!ritin% it
@,ample:- 9&is e,ample s&o)s costs&aring pa'ment s'stem
;html<
;body<
;h(<7oast sharin% payment system;=h(<
;>php
if (isset(/2G"T3:first2name:4) II isset(/2G"T3:last2name:4)) A
/First ? /2G"T3:first2name:45
/Fast ? /2G"T3:last2name:45
/Ge!? /Fast . @, @ . @/First@ . @Cn@5
/# ? @bo!lers.t#t@5
if (file2put2contents(/#, /Ge!, F&F"2$00"GH) < E)
echo @;p<A/2G"T3:first2name:4B A/2G"T3:last2name:4B has
been re%istered for the paymentJ;=p<@5
else
echo @;p<Re%istration errorJ;=p<@5
B
elseA
echo @;p<To si%n up for the cost sharin% system, enter your first
and last name and clic- the Re%ister button.;=p<@5
if(Jempty(/2G"T3:first2name:4))
echo /2G"T3:first2name:45
if(J/2G"T3:last2name:4)
echo /2G"T3:last2name:45B
4
><
;form action?@;>php /20102)"FF ><@ method?@%et@ enctype?@application=#'!!!'
form'urlencoded@<
;p<First Game: ;input type?@te#t@ name?@first2name@ si8e?@6E@ =<;=p<
;p<Fast Game: ;input type?@te#t@ name?@last2name@ si8e?@6E@ =<;=p<
;p<;input type?@submit@ value?@Re%ister@ =<;=p<
;=form<
;=body<
;=html <
&n %eneral5
To !rite files incrementally, use the f!rite() function
fclose() closes a file+
f%etc() reads a single c&aracter
feof() determines if t&e end is true+
f%ets() reads a line of data
file() reads entire file into an arra'
Aee t&e follo)ing e,amples
"#ample (:'
;>php
/myFile ? @!elcome.t#t@5
if (J(/fh?fopen(/myFile,:r:)))
e#it(@Unable to open file.@)5
!hile (Jfeof(/fh))
A
/#?f%etc(/fh)5
echo /#5
B
fclose(/fh)5
><
"#ample +
;>php
/myFile ? @!elcome.t#t@5
/fh ? fopen(/myFile, :r:)5
/theHata ? fgets(/fh)5
fclose(/fh)5
echo /theHata5><
"#ample 6:
;>php
/lines ? file(:!elcome.t#t:)5
foreach (/lines as /l2num ?< /line)
A
5
echo @Fine KA/l2numB:L ./line.M;br=<M5
B
><
"#ample N:'
;>php
/myFile ? @testFile.t#t@5
/fh ? fopen(/myFile, :a:) or die(@can:t open file@)5
/strin%Hata ? @Ge! )tuff (Cn@5
f)rite(/fh, /strin%Hata)5
/strin%Hata ? @Ge! )tuff +Cn@5
f!rite(/fh, /strin%Hata)5
fclose(/fh)5 ><
BocCing Files
, To prevent multiple users from modifyin% a file simultaneously use the floc-() function
, The synta# for the floc-() function is:
flocC(%handle" operation# !here operations could be FO7O2"P, FO7O2GQ, etc. The
follo!in%s are possible file loc- functions and their descriptions.
Reading an @ntire File
6
Dop'ing Files
, Use the copy() function to copy a file !ith 010
, The function returns a value of true if it is successful or false if it is not
, The synta# for the copy() function is: cop'(source" destination#
, For the source and destination ar%uments:
. &nclude Rust the name of a file to ma-e a copy in the current directory, or
. )pecify the entire path for each ar%ument
"#ample:'
if (file2e#ists(La.t#tM)) A
if(is2dir(LhistoryM)) A
if (copy(La.t#tM,LhistoryCCb.t#tM))
echo L;p<File copied successfully.;=p<M5
else
echo L;p<Unable to copy the fileJ;=p<M5
B
else
echo (L;p<The directory does not e#istJ;=p<M)5
B
else
echo (L;p<The file does not e#istJ;=p<M)5
3+3+ Dreate Directories
Qasic functions=methods that are used to open directories, read directories and close
directories are5'
To iterate throu%h the entries in a directory, open a handle to the directory !ith the
opendir() function
Use the readdir() function to return the file and directory names from the open directory
Use the closedir() function to close a directory handle
7
There are also different functions !hich have different purposes. )ome of them are listed belo!:'
"#ample (:' This is used to demonstrate ho! %are directory contents of files are displayed.
;>php
/Hir ? @7:CC%are@5
/HirOpen ? opendir(/Hir)5
!hile (/7urFile ? readdir(/HirOpen)) A
echo /7urFile . @;br =<@5
B
closedir(/HirOpen)5
><
"#ample +:' The follo!in% e#ample sho!s ho! the content of the current directory opened
/handle ? opendir(:.=:)5
!hile(false J?? (/file?readdir(/handle)))
A
echo @/file;br =<@5
B
closedir(/handle)5
9o create directories:-
, Use the m-dir() function to create a ne! directory. To create a ne! directory pass Rust the
name of the directory !e !ant to create to the m-dir() function.
, "#ample
m-dir(Lbo!lersM)5
m-dir(L..CCtournamentM)5
8
m-dir(L7:CC010CCutilitiesM)5
, arnin% !ill appear if directory already e#ists
"#ample:'
;>php
/Hir ? @7:CCamp@5
if(is2dir(/Hir)) A
echo @;table border?:(S !idth?:(EET:<@5
echo @;tr<;th<Filename;=th<;th<File )i8e;=th<
;th<File Type;=th<;=tr<@5
/Hir"ntries ? scandir(/Hir)5
foreach (/Hir"ntries as /"ntry) A
echo @;tr<;td</"ntry;=td<;td<@ + filesi7e(/Hir . @CC@
. /"ntry) . @;=td<;td<@ . filet'pe(/Hir . @CC@
. /"ntry) . @;=td<;=tr<@5
B
echo @;=table<@5
B
else echo @;p<The directory does not e#ist.;=p<@5
><
3+2+ Upload Files
eb applications allo! visitors to upload files to and from their local computer. The files
that are uploaded and do!nloaded may be simple te#t files or more comple# file types, such
as ima%es, documents, or spreadsheets
Files are uploaded throu%h an 1TUF form usin% the LpostM method and enct'pe attribute
!ith value of Lmultipart/form-data,M !hich instructs the bro!ser to post multiple sections .
one for re%ular form data and one for the file contents.
The file input field creates a bro!ser button for the user to navi%ate to the appropriate file to
upload
;form method?MpostM action?M M enctype? multipart/form-data <
;input type?@file@ name?@picture2file@ =<
;=form<
The U$P2F&F"2)&V" (uppercase) attribute of a hidden form field specifies the ma#imum
number of bytes allo!ed in the uploaded file and it must appear before the file input field.
hen the form is posted, information for the uploaded file is stored in the /2F&F") auto
%lobal array. The /2F&F")34 array contains five elements:
a. // Dontains t&e error code associated )it& t&e file /2F&F")3:picture2file:4
3:error:4
b+ // Dontains t&e temporar' location of t&e file
/2F&F")3:picture2file:43:tmp2name:4 contents
c. // Dontains t&e name of t&e original file
/2F&F")3:picture2file:43:name:4
d+ // Dontains t&e si7e of t&e uploaded file in b'tes
9
/2F&F")3:picture2file:43:si8e:4
e+ // Dontains t&e t'pe of t&e file
/2F&F")3:picture2file:43:type:4
"#ample:'The follo!in% 1TU code belo! creates an uploaded form. This form is havin%
method attribute set to post and enct'pe attribute is set to multipart/form-data
;html<
;body<
;h6<File Upload:;=h6<
)elect a file to upload: ;br =<
;form action?@;>php /20102)"FF ><@ method?@post@
enctype?@multipart=form'data@<
;input type?@file@ name?@file@ si8e?@WE@ =<
;br =<
;input type?@submit@ value?@Upload File@ =<
;=form<
;>php
if( /2F&F")3:file:43:name:4 J? @@ )
A
copy( /2F&F")3:file:43:name:4, @7:C!ampC!!!CFetureCTest.php@ ) or die( @7ould
not copy fileJ@)5
B
else
A
die(@Go file specifiedJ@)5
B
><
;html<
;head<
;title<Uploadin% 7omplete;=title<
;=head<
;body<
;h+<Uploaded File &nfo:;=h+<
;ul<
;li<)ent file: ;>php echo /2F&F")3:file:43:name:45 ><
;li<File si8e: ;>php echo /2F&F")3:file:43:si8e:45 >< bytes
;li<File type: ;>php echo /2F&F")3:file:43:type:45 ><
;=ul<
;=body<
;=html<
;=body<;=html<
3+E+ Rename and Delete Files and Directories
Use the rename(# function to rename a file or directory !ith 010
o This function returns a value of true if it is successful or false if it is not
10
o The synta# is: rename(old_name" new_name#
Use the unlin-() function to delete files and the rmdir(# function to delete directories
0ass the name of a file to the unlin-() function and the name of a directory to the rmdir()
function. Qoth functions return a value of true if successful or false if not
o Use the file(e,ists(# function to determine !hether a file or directory name e#ists
before !e attempt to delete it
3.6. File Fnclusions
&n 010 , !e can include the content of a 010 file into another 010 file before the server
e#ecutes it. This is done by functions such as include() and re9uire() function statements:'
The include(# Function:' include !ill only produce a !arnin% ("2$RG&GG) and the
script !ill continue
The re<uire(# Function:' re9uire !ill produce a fatal error ("27OU0&F"2"RROR) and
stop the script
There are also the include(once(# and re<uire(once(# functions+ These functions !ill not re'
include the file if it has already been called.
This is a stron% point of 010 !hich helps in creatin% functions, headers, footers, or elements that
can be reused on multiple pa%es. This !ill help developers to ma-e it easy to chan%e the layout
of complete !ebsite !ith minimal effort. &f there is any chan%e re9uired then instead of chan%in%
thousand of files Rust chan%e included file is easier.
)ynta#:'
include :filename:5
or
re9uire :filename:5
"#ample:'
;>php
include2once(:header.php:)5
include2once(/2G"T3:action:4 . :.php:)5
include2once(:footer.php:)5 ><
The include() function ta-es all the te#t in a specified file and copies it into the file that uses the
include function. &f there is any problem in loadin% a file then include(# function %enerates a
!arnin% but the script !ill continue e#ecution.
"#ample:' let !e create a file menu.php !ith the follo!in% content.
;a href?@http:==!!!.tutorialspoint.com=inde#.htm@<1ome;=a< '
;a href?@http:==!!!.tutorialspoint.com=eb#ml@<ebPUF;=a< '
;a href?@http:==!!!.tutorialspoint.com=aRa#@<$X$P;=a< '
;a href?@http:==!!!.tutorialspoint.com=perl@<0"RF;=a< ;br =<
Go! create as many pa%es as !e li-e and include this file to create header. For e#ample no!
test.php file can have follo!in% content.
;html<
11
;body<
;>php include(Gmenu+p&pG#$ ><
;p<This is an e#ample to sho! ho! to include 010 fileJ;=p<
;=body<
;=html<
This !ill produce follo!in% result:' 1ome ' ebPUF ' $X$P ' 0"RF
The re9uire() function on the other hand, ta-es all the te#t in a specified file and copies it into
the file that uses the include function. &f there is any problem in loadin% a file then the re<uire(#
function %enerates a fatal error and halt the e#ecution of the script.
Gote that:' There is no difference in re9uire() and include() functions e#cept handlin% error
conditions. &t is recommended to use the re9uire() function instead of include(), because scripts
should not continue e#ecutin% if files are missin% or misnamed.
12

Das könnte Ihnen auch gefallen