Difference between revisions of "PHP109"

From mi-linux
Jump to navigationJump to search
 
(12 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> File Handling  
 
[[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> File Handling  
 
== PHP File Handling ==
 
  
 
== Text Files ==
 
== Text Files ==
Line 9: Line 7:
  
 
== Opening Files - fopen ==
 
== Opening Files - fopen ==
 
More often that not, you will be opening and reading files as opposed to writing them. There are 3 main functions that we can use to open and read files in PHP.
 
  
 
'''fopen''' stands for "file open", and is used to create a pointer to the file which we want to open for read/write access. It accepts 2 required and 2 optional parameters. Its syntax is shown below:  
 
'''fopen''' stands for "file open", and is used to create a pointer to the file which we want to open for read/write access. It accepts 2 required and 2 optional parameters. Its syntax is shown below:  
Line 18: Line 14:
 
For example, let's say that we wanted to open a file called test.txt. We would use fopen like this:  
 
For example, let's say that we wanted to open a file called test.txt. We would use fopen like this:  
  
<nowiki><?  
+
<pre>
 +
<?php
 
   $fp = fopen("test.txt", "r");  
 
   $fp = fopen("test.txt", "r");  
?></nowiki>
+
?>
 +
</pre>
 
   
 
   
 
'''IF YOU ATTEMPT THIS, you will likely get one of two errors'''
 
'''IF YOU ATTEMPT THIS, you will likely get one of two errors'''
  
Error 1: the file does not exist - the example above is a read of an existing file, thus if the file does not exist, you'll get an error, so the obvious thing to do is create the file with some dummy content and run the script again, when you'll likely get...
+
*Error 1: the file does not exist - the example above is a read of an existing file, thus if the file does not exist, you'll get an error, so the obvious thing to do is create the file with some dummy content and run the script again, when you'll likely get...
  
Error 2: file permissions - see [[Troubleshooting PHP]] for information on file permission errors and how to solve them.
+
*Error 2: file permissions - see [[Troubleshooting PHP]] for information on file permission errors and how to solve them.
  
 
The $fp variable would now contain a pointer (or reference) to the test.txt file. The second parameter, "r", tells PHP that we want to open the file in read mode only -- we don't actually want to write to the file.  
 
The $fp variable would now contain a pointer (or reference) to the test.txt file. The second parameter, "r", tells PHP that we want to open the file in read mode only -- we don't actually want to write to the file.  
Line 58: Line 56:
 
== Read from File - fgets & fread ==
 
== Read from File - fgets & fread ==
  
In PHP there are 2 different functions that you can use to read in a file. They are called fgets and fread. Some code for each follows.
+
In PHP there are 2 different functions that you can use to read in a file:
 +
*fgets
 +
*fread  
  
 
The following two examples demonstrate the use of the fgets and the fread commands.
 
The following two examples demonstrate the use of the fgets and the fread commands.
  
The fundamental difference between these two approaches is Fgets grabs a line from the file, whereas fread grabs a certain amount of characters from the file.  
+
The fundamental difference between these two approaches is fgets grabs a line from the file, whereas fread grabs a certain amount of characters from the file.  
  
 
'''BEFORE''' you attempt the next couple of exercises, create a file called "test.txt" in the same directory as the exercises, change the permissions to make it world-readable (see [[Troubleshooting PHP]] for information on how to do this) and put some content in the file - doesn't matter what.
 
'''BEFORE''' you attempt the next couple of exercises, create a file called "test.txt" in the same directory as the exercises, change the permissions to make it world-readable (see [[Troubleshooting PHP]] for information on how to do this) and put some content in the file - doesn't matter what.
  
 
* fgets
 
* fgets
  <nowiki><?  
+
  <nowiki><?php
 
   $fp = fopen("test.txt", "r");  
 
   $fp = fopen("test.txt", "r");  
 
   $data = "";  
 
   $data = "";  
   while(!feof($fp))  
+
   while(!feof($fp)) {  
  {  
 
 
     $data .= fgets($fp, 4096);  
 
     $data .= fgets($fp, 4096);  
 
   }  
 
   }  
 
   echo $data;  
 
   echo $data;  
?></nowiki>  
+
?></nowiki>  
  
 
* fread
 
* fread
  <nowiki><?
+
  <nowiki><?php
   $filename="test.txt";
+
   $filename = "test.txt";
   $fp = fopen($filename,"r");
+
   $fp = fopen($filename, "r");
   $data=fread($fp,filesize($filename));
+
   $data = fread($fp, filesize($filename));
 
   echo $data;
 
   echo $data;
?></nowiki>
+
?></nowiki>
 
 
=== What's the Difference? ===
 
 
 
We start by setting a parameter called $filename with the name of the file we're using "test.txt"
 
 
 
Using the fopen function, we open the "test.txt" file for reading only. The file pointer to test.txt is stored in the variable called $fp.
 
 
 
$filename = "test.txt");
 
$fp = fopen($filename, "r");
 
 
 
Next, we grab the entire contents of our test.txt file by passing 2 parameters to the fread function:
 
 
 
$data = fread($fp, filesize($filename));
 
 
 
$fp is the file pointer to our test.txt file
 
 
 
filesize($filename) is a PHP function which accepts a filename and returns the length of that file in bytes.
 
 
 
After this line has executed, $data will contain the entire contents of our test.txt file -- whether it be text or binary. The signature of the fread function looks like this:
 
 
 
string fread ( int fp, int length)
 
 
 
As we've already discussed, we pass in a file pointer ($fp in our example) and also the number of bytes that we want to retrieve from the file. The filesize() function returns the length of our file by simply passing it the file name.
 
  
 
=== EXERCISE ===
 
=== EXERCISE ===
Line 126: Line 102:
 
Create a file called '''getperson.php''' and add the following code to it (make sure you save it in the same directory as person.data):  
 
Create a file called '''getperson.php''' and add the following code to it (make sure you save it in the same directory as person.data):  
  
  <nowiki><?
+
  <nowiki><?php
   $filename="person.data";
+
   $filename = "person.data";
 
   $fp = @fopen($filename, "rb") or die("Couldn't open file");  
 
   $fp = @fopen($filename, "rb") or die("Couldn't open file");  
 
   $data = fread($fp, filesize($filename));  
 
   $data = fread($fp, filesize($filename));  
   while(!feof($fp))  
+
   while(!feof($fp)) {  
  {  
 
 
     $data .= fgets($fp, 1024);  
 
     $data .= fgets($fp, 1024);  
 
   }  
 
   }  
Line 139: Line 114:
 
   // NOTE: if you create your data file on Windows you need to replace the line above with the one below
 
   // NOTE: if you create your data file on Windows you need to replace the line above with the one below
 
   // $values = explode("\r\n", $data);  
 
   // $values = explode("\r\n", $data);  
 
  
 
   echo "Name: " . $values[0] . " " . $values[1] . "<br>";  
 
   echo "Name: " . $values[0] . " " . $values[1] . "<br>";  
 
   echo "Age: " . $values[2] . "<br>";  
 
   echo "Age: " . $values[2] . "<br>";  
 
   echo "Sex: " . $values[3];  
 
   echo "Sex: " . $values[3];  
?></nowiki>
+
?></nowiki>
  
 
== Writing to Files ==
 
== Writing to Files ==
Line 152: Line 126:
 
So, how would we create a blank file using just the fopen command? Simple. Take a look:  
 
So, how would we create a blank file using just the fopen command? Simple. Take a look:  
  
  <nowiki><?  
+
  <nowiki><?php
 
   $fp = fopen("newfile.file", "w") or die("Couldn't create file");  
 
   $fp = fopen("newfile.file", "w") or die("Couldn't create file");  
?></nowiki>
+
?></nowiki>
  
 
That's really all there is to it. To actually output a value to the file, we need to use the fwrite function.
 
That's really all there is to it. To actually output a value to the file, we need to use the fwrite function.
Line 167: Line 141:
 
If we wanted to output a simple sentence to a file, then we could do it like this:  
 
If we wanted to output a simple sentence to a file, then we could do it like this:  
  
  <nowiki><?  
+
  <nowiki><?php
 
   $fp = fopen("newfile.file", "w") or die("Couldn't create file");  
 
   $fp = fopen("newfile.file", "w") or die("Couldn't create file");  
 
   $numBytes = fwrite($fp, "Hello, this is some text!");  
 
   $numBytes = fwrite($fp, "Hello, this is some text!");  
Line 173: Line 147:
  
 
   echo "Wrote $numBytes bytes to newfile.file!";  
 
   echo "Wrote $numBytes bytes to newfile.file!";  
?></nowiki>
+
?></nowiki>
  
 
'''If you get "Couldn't create file" errors''', make sure the folder the PHP file is in has world-writable permissions - if the webserver cannot write to the folder, you cannot create the file.
 
'''If you get "Couldn't create file" errors''', make sure the folder the PHP file is in has world-writable permissions - if the webserver cannot write to the folder, you cannot create the file.
Line 184: Line 158:
 
So, to append a sentence to the bottom of '''newfile.file''', we could use this code:  
 
So, to append a sentence to the bottom of '''newfile.file''', we could use this code:  
  
  <nowiki><?  
+
  <nowiki><?php
 
   $fp = fopen("newfile.file", "a") or die("Couldn't create new file");  
 
   $fp = fopen("newfile.file", "a") or die("Couldn't create new file");  
 
   $numBytes = fwrite($fp, "\r\nLook, it's a brand new line!");  
 
   $numBytes = fwrite($fp, "\r\nLook, it's a brand new line!");  
Line 190: Line 164:
  
 
   echo "Wrote $numBytes bytes to the end of newfile.file!";  
 
   echo "Wrote $numBytes bytes to the end of newfile.file!";  
?></nowiki>
+
?></nowiki>
  
The output from our PHP script shows how many bytes were written to newfile.file:
+
The output from our PHP script shows how many bytes were written to newfile.file
 
    
 
    
Simple, right! Now, remember that using the file mode "w" actually truncates the file before writing to it. What about if we just wanted to append some text to the bottom of the file? Which file mode would we use then? We have 2 choices:
 
 
== File Writing Data ==
 
Let's create an example that will grab the name, sex and age of someone from a HTML form and write them to a file. There will be 2 pages in our example: '''getdata.html''' and '''savedata.php'''.
 
 
Here's the code for '''getdata.html''':
 
<nowiki><html>
 
  <head>
 
    <title>Personal Organizer </title>
 
  </head>
 
  <body bgcolor="#ffffff">
 
      <form action="savedata.php" method="post">
 
        First Name: <input type="text" name="first_name" size="30"><br>
 
        Last Name: <input type="text" name="last_name" size="30"><br>
 
        Age: <input type="text" name="age" size="2"><br>
 
        Sex: <input type="radio" name="sex" value="M"> Male <input type="radio" name="sex" value="F"> Female<br><br>
 
        <input type="submit" value="Save Data">
 
      </form>
 
  </body>
 
</html></nowiki>
 
 
=== getdata.html Breakdown ===
 
* Form heading specifying '''savedata.php''' as the destination when the subject button is clicked
 
<form action="savedata.php" method="post">
 
 
* Gather Text such as Name and age in text boxes
 
First Name: <input type="text" name="first_name" size="30"><br>
 
Last Name: <input type="text" name="last_name" size="30"><br>
 
Age: <input type="text" name="age" size="2"><br>
 
 
* Use Radio Buttons for such details as gender
 
Sex: <input type="radio" name="sex" value="M"> Male <input type="radio" name="sex">
 
 
* Create a button on the form to save the data
 
<input type="submit" value="Save Data">
 
 
'''Note:''' - you will need to write a script to show the contents of the file created by the script 'savedata.php'
 
 
== Exercises ==
 
=== Exercise 1 ===
 
Implement the code in this chapter, to save typing it can be downloaded from my web site at http://www.scit.wlv.ac.uk/brendan/php/
 
 
=== Exercise 2 ===
 
'getdata.html' above, uses a PHP script called 'savedata.php' to add text to the text file 'organizer.data'.  Develop a page which reads this text file, ensuring that it presents the contents to screen in a neat format.
 
 
=== Exercise 3 ===
 
Experiment with the use of a table to present the data.
 
 
 
= Ready to move on? =
 
= Ready to move on? =
[[PHP110|PHP110 - Simple Databases Concepts & SQL]]
+
Let's tackle this week's [[PHPEX03|mini-task]]!

Latest revision as of 13:37, 29 June 2016

Main Page >> Web Application Development >> Workbook >> File Handling

Text Files

A simple text file may be considered to be a database. It will be simple (flat), sequential, not secure and contain just plain ASCII text. However, as we can read and write to it on the server we can treat it as a database. We will look at storing simple information such as peoples names, email addresses etc, and in this sense use our text file as our database

Some of these are from Internet & World Wide Web - How to Program, Deitel, Deitel & Nieto (2002)

Opening Files - fopen

fopen stands for "file open", and is used to create a pointer to the file which we want to open for read/write access. It accepts 2 required and 2 optional parameters. Its syntax is shown below:

int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

For example, let's say that we wanted to open a file called test.txt. We would use fopen like this:

<?php 
   $fp = fopen("test.txt", "r"); 
?>

IF YOU ATTEMPT THIS, you will likely get one of two errors

  • Error 1: the file does not exist - the example above is a read of an existing file, thus if the file does not exist, you'll get an error, so the obvious thing to do is create the file with some dummy content and run the script again, when you'll likely get...
  • Error 2: file permissions - see Troubleshooting PHP for information on file permission errors and how to solve them.

The $fp variable would now contain a pointer (or reference) to the test.txt file. The second parameter, "r", tells PHP that we want to open the file in read mode only -- we don't actually want to write to the file.

Open Modes

One-way file operations are quicker than 2 way operations (such as read+write access) because the location of the file pointer is uni-directional, i.e. it only has to travel down the file, and not jump from position to position.

There are 6 different file modes that we can use when working with files in PHP. They are shown below (courtesy of php.net):

  • 'r' - Open for reading only; place the file pointer at the beginning of the file.
  • 'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
  • 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

As you can see, PHP is very flexible when it comes to files. We can read a file, read and write to a file, append to the end of a file, move the file pointer to the bottom of the file automatically and more!

End of File - feof

Is the the function that we can use in PHP to determine whether or not we have reached the end of a file when we're reading it in. All file functions are prefixed with the character "f" in PHP, and EOF is an acronym for End-Of-File.

Feof is a simple function, and accepts just 1 parameter, as shown below:

int feof ( int fp) 

The parameter, fp, is a reference to a file pointer that contains the details of the file we're working with. Feof returns true if we're at the end of a file, and false if we're not.

Before we can see the feof function in action, we need to learn a bit about the fread function, which we will look at next.

Read from File - fgets & fread

In PHP there are 2 different functions that you can use to read in a file:

  • fgets
  • fread

The following two examples demonstrate the use of the fgets and the fread commands.

The fundamental difference between these two approaches is fgets grabs a line from the file, whereas fread grabs a certain amount of characters from the file.

BEFORE you attempt the next couple of exercises, create a file called "test.txt" in the same directory as the exercises, change the permissions to make it world-readable (see Troubleshooting PHP for information on how to do this) and put some content in the file - doesn't matter what.

  • fgets
<?php 
   $fp = fopen("test.txt", "r"); 
   $data = ""; 
   while(!feof($fp)) { 
     $data .= fgets($fp, 4096); 
   } 
   echo $data; 
?> 
  • fread
<?php
   $filename = "test.txt";
   $fp = fopen($filename, "r");
   $data = fread($fp, filesize($filename));
   echo $data;
?>

EXERCISE

OK, so now you know about the 4 functions that we need to open and then read-in the contents of a file:

  • fopen(),
  • foef(),
  • fread() and
  • filesize().


Create a text file called person.data and add the following lines to it:

Joe 
Bloggs 
22
M 

Create a file called getperson.php and add the following code to it (make sure you save it in the same directory as person.data):

<?php
   $filename = "person.data";
   $fp = @fopen($filename, "rb") or die("Couldn't open file"); 
   $data = fread($fp, filesize($filename)); 
   while(!feof($fp)) { 
     $data .= fgets($fp, 1024); 
   } 
   fclose($fp); 

   $values = explode("\n", $data); 
   // NOTE: if you create your data file on Windows you need to replace the line above with the one below
   // $values = explode("\r\n", $data); 

   echo "Name: " . $values[0] . " " . $values[1] . "<br>"; 
   echo "Age: " . $values[2] . "<br>"; 
   echo "Sex: " . $values[3]; 
?>

Writing to Files

By simply specifying "w" as the file mode, PHP will move the file pointer to the beginning of the file and truncate (cut-down) the file to zero length if that file already exists. If it doesn't exist, here's the good part - PHP will automatically create it for us!

So, how would we create a blank file using just the fopen command? Simple. Take a look:

<?php 
   $fp = fopen("newfile.file", "w") or die("Couldn't create file"); 
?>

That's really all there is to it. To actually output a value to the file, we need to use the fwrite function.

fwrite

fwrite simply writes the contents of a string to a file. The signature for the fwrite function looks like this:

int fwrite ( int fp, string string [, int length])

fwrite returns the number of bytes written on success, or false if an error occurs. The first parameter is the file pointer ($fp in all of our previous examples). The second parameter is the string that you want to write to the file, and the third optional parameter is the length of the string that will be output to the file.

If we wanted to output a simple sentence to a file, then we could do it like this:

<?php 
   $fp = fopen("newfile.file", "w") or die("Couldn't create file"); 
   $numBytes = fwrite($fp, "Hello, this is some text!"); 
   fclose($fp); 

   echo "Wrote $numBytes bytes to newfile.file!"; 
?>

If you get "Couldn't create file" errors, make sure the folder the PHP file is in has world-writable permissions - if the webserver cannot write to the folder, you cannot create the file.

Writing Options

  • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Because we are only performing write operations on the file, we will use "a" (remember that it's quicker to use a unidirectional access method instead of a bi-directional one, such as read/write).

So, to append a sentence to the bottom of newfile.file, we could use this code:

<?php 
   $fp = fopen("newfile.file", "a") or die("Couldn't create new file"); 
   $numBytes = fwrite($fp, "\r\nLook, it's a brand new line!"); 
   fclose($fp); 

   echo "Wrote $numBytes bytes to the end of newfile.file!"; 
?>

The output from our PHP script shows how many bytes were written to newfile.file

Ready to move on?

Let's tackle this week's mini-task!