In this part of our PHP Tutorial I will be showing you 3 different things that you need to learn when it comes to files. These 3 are:

  1. File Handling ~ In this part you will deal with the contents of the files like read a text file, edit it, write it and more…
  2. Uploading files
  3. File Management ~ This will deal with the file in general you can delete, copy, move, organize them and more…

OK lets start by File Handling:

In PHP you can:

  • Open a text file and closing it

In order to do anything with a file, first you need to open it you can do this using fopen() function here is the code for it:

$handle_variable=fopen(filename,opening mode);

and

$A_variable=fclose(file_handle);

for example:

< ?php

$handle=fopen(“test.txt”,’r’);//this will open a file called test.txt for reading only and start at the beggining.

$closed=fclose($handle);

?>

The most important modes that fopen() uses are:

Mode What it Does?
r It opens the file as read only and starts at the beginning of the file
r+ It opens the file to read and write and starts at the beginning of the file.
w It opens the file for writing and starts at the beginning of the file and will delete the content of the file first, if the file is not available it will create it
w+ This will open a file for reading and writing, set the file size to zero and starts at the beginning. If the file does not exist it will create it.
a It will opens the file to append it(add to it) and starts at the beginning of the file. If file is not available will create it.
a+ This will open a file to read and write and starts at the end of the file. If the file does not exist it will create it.

fopen() will return a value of false if the file is not readable(or if it is not available). So you can check to see if it was successful or not before going any further:

<?php

$handle=fopen(“test1.txt”,”r”);// and here we assume test1.txt doesn’t exist

if($handle){// this will check to see if the file was opened or not

echo “file is open”;// this part will be executed if the file handle is true meaning the file is open

}else{

echo “file couldnt be found!”;// this part will be executed if the file handle is false meaning file couldn’t be opened, there will be an error on screen from PHP as well.

}

$closed=fclose($handle);

?>

  • Read a text file line by line

OK, we opened the file now what? now we can read it using fgets() here is how:

string variable or function fgets(file handle, length to read);

file handle is the variable that you opened the file with using fopen.

length to read is the length of the file that it will return for you it basically will read until it reached the (length -1) or to the end of the line(when on the text file they pressed enter to move to the next line for example) or the end of the file

During reading the file you need to know if you have reached the end of the file or not you can do this using feof() here is the code:

boolean feof(file handle);

It will return true if it has reached the end of the file and false if it has not reached the end of the file.

so lets read a file:

<?php

/*I will be assumming there is a file with 3 lines here called test.txt in the same folder as this script

and will read and display the text on screen and add a “-” after every 10 charachter of each line*/

$handle=fopen(‘test.txt’,’r’);

if($handle){// check to see if the fiole is open or not

while(!feof($handle)){// this will check to see if it has reached the end of the file if not it will run the loop if it has it will get out of the loop

echo fgets($handle,10);// will read and display 10 charachter of each line of the file

echo “-“;// this will add the “-” also could be added to the above line then it would be: echo fgets($handle,10).”-“;         // I seperated them for clearaification

}

$closed=fclose($handle);

}else{

echo “couldn’t read the file”;// display an error in addition to the error that PHP will give you.

}

?>

  • Read a text file character by character

For reading characters from a file you need to use fgetc() function here is the code:

String fgetc(file handle);

This function will return the character that file pointer(the character that you are in the file) is on. So for example if we wanted to read a file and if the file is bigger than 300 characters only returning the first 300 characters here is the code for that:

<?php

$handle=fopen(‘test.txt’,’r’);

if ($handle){

$i=300;

while(!feof($handle) and $i>0){// as long as it is more than 300 characters and is not the end of the file do the following

echo fgetc($handle);// read one character from the file and display

$i–;

}//————end of while

$closed=fclose($handle);

}else{

echo “couldn’t open the file”;

}//————–end of if

?>

  • Edit the text file

for editing a file you need to read it, find what you want to change, make the changes and finally save them. You already know how to read a file now for finding you can use any of the string functions in PHP to find and replace text here in this example I will be opening a file read it into an array and the search for a “book” and then change it to “notepad” then display the result:

<?php

$handle=fopen(‘test.txt’,’r’);

if(!$handle){die;}// if the file is not open just end the script using die; statement

$main_array=array();

while(!feof($handle)){// this loop will read a file into an array

$temp_var=fgets($handle);// reads a line

$temp_array=explode(” “,$temp_var);// this will make the text that we just read(the line) into an array; it will find them using ” ” space

foreach($temp_array as $temp_item ){

$main_array[]=$temp_item;// adding each node(part) of the temp array to the main one

}// —————-end of foreach

$temp_array=array();//empty the array

}//————end of  while

//————————now we can search for the “book” and change it with “notepad”

for ($i=0; $i<count($main_array); $i++){// will go through all the elements in the main array( count(array name) will tell you how many elements or items do you have in that array )

if($main_array[$i]==”book”){$main_array[$i]=”notepad”;}// change book to notepad if the item is book

}// ——————end of for

$j=0;

foreach($main_array as $item){// just display the result here

echo $main_array[$j].” “;

$j++;

}//————-end of foreach

$closed=fclose($handle);

?>

Now if we wanted to store the changed details the code would be(please pay attention to the bold parts as they have been changed):

<?php

$handle=fopen(‘test.txt’,’r’);

if(!$handle){die;}// if the file is not open just end the script using die; statement

$main_array=array();

while(!feof($handle)){// this loop will read a file into an array

$temp_var=fgets($handle);// reads a line

$temp_array=explode(” “,$temp_var);// this will make the text that we just read(the line) into an array; it will find them using ” ” space

foreach($temp_array as $temp_item ){

$main_array[]=$temp_item;// adding each node(part) of the temp array to the main one

}// —————-end of foreach

$temp_array=array();//empty the array

}//————end of  while

//————————now we can search for the “book” and change it with “notepad”

for ($i=0; $i<count($main_array); $i++){// will go through all the elements in the main array( count(array name) will tell you how many elements or items do you have in that array )

if($main_array[$i]==”book”){$main_array[$i]=”notepad”;}// change book to notepad if the item is book

}// ——————end of for

$j=0;

foreach($main_array as $item){// just display the result here

echo $main_array[$j].” “;

$j++;

}//————-end of foreach

// we close the file first and then we can open it to write it using fclose() function

$closed=fclose($handle);

$handle=fopen(“test.txt”,”w”);// this will set the file size to zero and deleting the content of the file

// for the above statement if you are only adding to the file like a log file you need to use “a” to just add to the file

if(!handle){die;}

foreach($main_array as $item){

$fw=fwrite($handle,$item.” “);// this will write it to the file

}

$closed=fclose($handle);// closeing the file

?>

  • Close the Text File

As Oracle said “Everything that has a beginning has an end!” that is true in file handling always close the file as you have seen it in all of the examples above

Now lets Upload a file

In PHP uploading a file involve a few steps:

  1. get the file details and do some checking before submission
  2. upload the file into the temporary folder
  3. check the file
  4. move it to the right place
  5. done.

Lets start:

for getting the file details you can setup a form using this code as a sample:

<form action=”upload.php” method=”post”  enctype=”multipart/form-data”>
<p>

<label for=”file”>Filename:</label>
<input type=”file” name=”file” id=”file” />

</p>
<input type=”submit” name=”submit” value=”Submit” />
</form>

You can put the above code anywhere in the body of your HTML code it will give you one input with the type of file which allows you to brows in your computer, choose a file and select it to upload it.

By submitting the form file is being uploaded to the temporary folder in the server and you can now check it using these two array items:

$_FILES[“file”][“type”] – indicates the type of the uploaded file like image, zip, text,etc.
$_FILES[“file”][“size”] – indicates the size of the file in bytes.

“file” is the name of the field that we setup in the form so if your form field’s name is file123 then the size of the uploaded file can be found in $_FILES[“file123”][“size”]

After you made any check that you like to put in place like the file type and/or size of the uploaded file we can move to the next part now for the PHP part:

<?php

if($_FILES[“file”][“error”]>0){// then there is a problem with the upload

echo “there was an error”;

die;

}//————-end of if

if($_FILES[“file”][“size”]<2048) {// if the file size is less than 2 KB then do this

move_uploaded_file($_FILES[“file”][“tmp_name”], “upload/” . $_FILES[“file”][“name”]);/* this will move the file from the temporary folder to upload folder and change the name from the temporary name that PHP gave it to the origial name of the file.

This is the part of the code that you could use to automatically rename the file to any name you want

*/

}//—————-end of if

?>

For the above code if you need the location of the stored file and its name and if I would set a variable to hold it the statement would be:

$uploaded_file=”upload/”.$_FILES[“file”][“name”];

And one last thing, there are no limitation on how many file you can upload in a form but remembering the name well for that you need sessions or cookies and that lesson will be coming soon.

And File Management

In our PHP Training course here we will look at:

  • Get a list of files in a directory(folder)

you can get the list of files and directories inside a path using the following command:

array scandir(directory name)

so to get all file in directory “examples” that is in the current folder, here would be the command for it:

$array=scandir(“example”);

  • Change to that directory

To change to a directory you can use this command:

bool chdir(“directory name”);

example for it would be like:

chdir(“example”);// moves into example folder

  • Change permission for a file or directory

You can change the permission for a file or directory using chmod() function here is how:

chmod(file,mode);

for example:

chmod(“test.txt”,0755); //will change the permission so owner will have everything and others will be able to read and execute the file but they cant write on it

  • delete a file

To delete a file you can use :

unlink(file name);

for example:

unlink(“test.txt”);// deletes the test.txt from the current location

To delete a directory however you need to use rmdir() function  here is the code:

rmdir(directory name);

for example:

rmdir(“example”);//this will remove example assuming example is an empty directory and you have permission.

  • rename a file

You can rename any file as long as you have permission to do it using this function:

rename(old name , new name);

for example:

rename(“test.txt”,”new_text.txt”);

  • copy a file

You can copy a file using:

copy(source , destination);

for example:

copy(“example/1.txt”,”upload/1.txt”);

  • move a file

You can do this by copy and then deleting the file like:

copy(“test.txt”,”upload/test.txt”);

unlink(“test.txt”);

  • make a directory

To make a directory use this:

mkdir(directory name , permission);

in the above code permission is optional here are two examples:

mkdir(“example2”,0755);// set the permissions to everything for owner and read and execute for everyone else.

mkdir(“example3”);// default permissions

  • rename a directory

You can use the rename function to rename the directory just the same as for files.

%d bloggers like this: