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

CH 4

Uploaded by

awelwafi89
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)
8 views

CH 4

Uploaded by

awelwafi89
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/ 24

Chapter 4

FILES AND DIRECTORIES


Writing to a File
2

The PHP's file system functions are used to create,


access and manipulate files.
You can store data in two basic ways: in flat files or in a
database.
A flat file can have many formats, but in general, when
we refer to a flat file, we mean a simple text file.
File handling is an important part of any web
application. You often need to open and process a file for
different tasks.
The processes of writing to and reading from files is very
similar to many programming languages.

08/10/2024
….coun’t
3

Writing data to a file requires three steps:


 Open the file. If the file does not already exist, you need to create it.
 Write the data to the file.
 Close the file.
 To open a file in PHP, you use the fopen() function.
 The fclose() function is used to close an open file.
 It requires the name of the file (or a variable that holds the filename) we want to
close.
 When you open the file, you need to specify how you intend to use it. This is
known as the file mode.
 The operating system on the server needs to know what you want to do with a
file that you are opening.
 It needs to know whether the file can be opened by another script while you have
it open and whether you (or the script owner) have permission to use it in that
way.
08/10/2024
example
4

<?php
$a=fopen('ka.txt', 'w');
fwrite($a,'hello information technology' );
?>
<?php
readfile('ka.txt');
?>

08/10/2024
…coun’t
5

Essentially, file modes give the operating system a mechanism


to determine how to handle access requests from other people
or scripts and a method to check that you have access and
permission to a particular file.
You need to make three choices when opening a file:
 You might want to open a file for reading only, for writing only, or for
both reading and writing.
 If writing to a file, you might want to overwrite any existing contents of a
file or append new data to the end of the file. You also might like to
terminate your program gracefully instead of overwriting a file if the file
already exists.
 If you are trying to write to a file on a system that differentiates between
binary and text files, you might need to specify this fact.
 The fopen() function supports combinations of these three options.

08/10/2024
File Modes
6

08/10/2024
..coun’t
7

Writing to a file in PHP is relatively simple. You can use either


of the functions fwrite() (file write) or fputs() (file put
string); fputs() is an alias to fwrite().
You call fwrite() in the following way:
 fwrite($fp, $outputstring);
This function call tells PHP to write the string stored in
$outputstring to the file pointed to by $fp.
Example:
 <?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = “Welcome\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

08/10/2024
…count
8

<?php
file_put_contents('kassa.txt', ‘Easy Programming ');
echo file_get_contents('kassa.txt');
?>// Easy Programming
File_put_contents function used to write php file like
that of fwrite.
File_get_contents also used to read file from the
dirctory.

08/10/2024
Reading from a File
9

 Similarly, reading data from a file takes three steps:


 Open the file. If you cannot open the file (for example, if it doesn’t exist), you need to
recognize this and exit gracefully.
 Read data from the file.
 Close the file.
 When you want to read data from a file, you have many choices about
how much of the file to read at a time.
 Again, you open the file by using fopen(). In this case, you open the file
for reading only, so you use the file mode r.
 The fread() function reads from an open file.
 The first parameter of fread() contains the name of the file to read from
and the second parameter specifies the maximum number of bytes to
read.
 The readfile() function is useful if all you want to do is open up a file and
read its contents.
08/10/2024
….coun’t
10

The readfile() function also reads a file and writes it to the


output buffer.
fgets() and fgetc() are functions used to read single line at
a time and single character at a time respectively.
feof() function is used along with these functions to check if
the "end-of-file" (EOF) has been reached. The feof() function
is also useful for looping through data of unknown length.
Example:
 <?php
$myfile = fopen("web.txt", "r") or die("Unable to open
file!");
echo fread($myfile,filesize("web.txt"));
fclose($myfile);
?>

08/10/2024
….coun’t
11

 <?php
echo readfile("web.txt");
?>
 <?php
$myfile = fopen("web.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
 //read single line from the file
fclose($myfile);
?>
 <?php
$myfile = fopen("web.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgets($myfile);
 //can read whole file using while loop and feof
}
 ?>

08/10/2024
..count
12

<?php
$myfile = fopen("web.txt", "r") or die("Unable to
open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
// After a call to the fgetc() function, the file pointer
moves to the next character.
08/10/2024
Creating and Removing a Directory
13

The mkdir() and rmdir() functions are used to create a


new directory and remove the created directory respectively.
 mkdir(“directory name”)
 Rmdir(“directory name”)
The is_dir() function is used to check if the directory exists
before creating or removing it.
Example:
 <?php
if(!is_dir("NewDirectory")){
mkdir("NewDirectory");
echo "the new directory is created!!";
}
?>

08/10/2024
Renaming and Deleting Files
14

 The rename() function is used to give a new name for your file.
 rename (“old name”, “new name”).
 <?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>
 If you want to delete the order file after the orders have been processed, you can do so
by using unlink(). (here
is no function called delete)
 unlink($fp)

 <?php
 $fh=fopen('test.txt','a');
 fwrite($fh,'Hello world!');
 fclose($fh);

unlink('test.txt');
?>

08/10/2024
…coun’t
15

<?php
if(is_dir("NewDirectory")){
rmdir("NewDirectory");
echo "the new directory is removed!!";
}
?>
Like in files the rename () function is used to
rename the name of directories.

08/10/2024
Overview of PHP file system function
16

08/10/2024
Upload files
17

With PHP, it is easy to upload files to the server


However, with ease comes danger, so always be
careful when allowing file uploads!
Configure The "php.ini" File
First, ensure that PHP is configured to allow file
uploads.
In your "php.ini" file, search for the file_uploads
directive, and set it to On:

08/10/2024
File uploading
18

 Create The HTML Form


 Next, create an HTML form that allow users to choose the image file they
want to upload:
 <!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-


data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>
08/10/2024
Tips …
19

Some rules to follow for the HTML form above:


Make sure that the form uses method="post"
The form also needs the following attribute:
enctype="multipart/form-data". It specifies which content-type
to use when submitting the form
Without the requirements above, the file upload will not work.
Other things to notice:
The type="file" attribute of the <input> tag shows the input
field as a file-select control, with a "Browse" button next to the
input control
The form above sends data to a file called "upload.php", which
we will create next.

08/10/2024
Php script to upload
20
 Create The Upload File PHP Script
 The "upload.php" file contains the code for uploading a file:
 <?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>

08/10/2024
tips
21

PHP script explained:


$target_dir = "uploads/" - specifies the directory
where the file is going to be placed
$target_file specifies the path of the file to be
uploaded
$imageFileType holds the file extension of the file
Next, check if the image file is an actual image or a
fake image

08/10/2024
Problems with Using Flat Files
22

 When a file grows large, working with it can be very slow.


 Searching for a particular record or group of records in a flat file is
difficult.
 Dealing with concurrent access can become problematic. With enough
traffic on a site, a large group of users may be waiting for the file to be
unlocked before they can place their order. If the wait is too long, people
will go elsewhere.
 The file processing deals with a file using sequential processing; that is,
you start from the beginning of the file and read through to the end.
Random access can be difficult because you end up reading the whole file
into memory, making the changes, and writing the whole file out again.
With a large data file, having to go through all these steps becomes a
significant overhead.
 Beyond the limits offered by file permissions, there is no easy way of
enforcing different levels of access to data.
08/10/2024
How Solve These Problems
23

Relational database management systems address all


these issues:
RDBMSs can provide much faster access to data than flat
files. And MySQL, the database system we use in this course,
has some of the fastest benchmarks of any RDBMS.
RDBMSs can be easily queried to extract sets of data that fit
certain criteria.
RDBMSs have built-in mechanisms for dealing with
concurrent access.
RDBMSs provide random access to your data.
RDBMSs have built-in privilege systems. MySQL has
particular strengths in this area.
08/10/2024
24

End of the Chapter

08/10/2024

You might also like