PHP Files
PHP Files
PHP Files
You often
need to open and process a file for different tasks.
The PHP code to read the file and write it to the output buffer is as
follows (the readfile() function returns the number of bytes read on
success):
Example
<?php
echo readfile("webdictionary.txt");
?>
The next chapters will teach you more about file handling.
PHP Open File - fopen()
A better method to open files is with the fopen() function. This function
gives you more options than the readfile() function.
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
Modes Description
w Open a file for write only. Erases the contents of the file
or creates a new file if it doesn't exist. File pointer starts at
the beginning of the 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 following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
It's a good programming practice to close all files after you have
finished with them. You don't want an open file running around on your
server taking up resources!
The fclose() requires the name of the file (or a variable that holds the
filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to
the next line.
The example below reads the "webdictionary.txt" file line by line, until
end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP Read Single Character - fgetc()
The fgetc() function is used to read a single character from a file.
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Note: After a call to the fgetc() function, the file pointer moves to the
next character.
If you use fopen() on a file that does not exist, it will create it, given
that the file is opened for writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will
be created in the same directory where the PHP code resides:
Example
$myfile = fopen("testfile.txt", "w")
The first parameter of fwrite() contains the name of the file to write to
and the second parameter is the string to be written.
The example below writes a couple of names into a new file called
"newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open
file!");
$txt = "Souhail Laghchim\n";
fwrite($myfile, $txt);
$txt = "Souhail Laghchim\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote
to the file we sent the string $txt that first contained "John Doe" and
second contained "Jane Doe". After we finished writing, we closed the
file using the fclose() function.
Souhail Laghchim
Souhail Laghchim
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens
when we open an existing file for writing. All the existing data will be
ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write
some new data into it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open
file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have
vanished, and only the data we just wrote is present:
Mickey Mouse
Minnie Mouse
In your "php.ini" file, search for the file_uploads directive, and set it to
On:
file_uploads = On
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>
</body>
</html>
Without the requirements above, the file upload will not work.
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.
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
= strtolower(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;
}
}
?>
Note: You will need to create a new directory called "uploads" in the
directory where "upload.php" file resides. The uploaded files will be
saved there.
Check if File Already Exists
Now we can add some restrictions.
First, we will check if the file already exists in the "uploads" folder. If it
does, an error message is displayed, and $uploadOk is set to 0:
Now, we want to check the size of the file. If the file is larger than
500KB, an error message is displayed, and $uploadOk is set to 0:
<?php
$target_dir = "uploads/";
$target_file = $target_dir .
basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
Email : Souhail.developer@gmail.com
Souhail Developer