PHP: Open, Read and Create files

Open and Read content from a text file
Create and Write to a text file
Read and Write compressed files (.gz)
Example: Save IP address and referrer of our page

NOTE: To work with files, correct permissions are required. Change permissions to 777 to try the code bellow. Other way, you will get errors.

Open and Read content from a text file

Example 1: This one will be the basic code we need to open a text file. The file is defined in line 2, it is read in lines 3-5, and content of the file is outputted in line 7.
 

1
2
3
4
5
6
7
8
<?php
$filename="myfile.txt";
$tempvar = fopen($filename,"r");
$content=fread($tempvar, filesize ($filename));
fclose($tempvar);

print "<pre>$content";
?>

Line 2: a variable name $filename is defined. It contains the name of the file we will work with. In this case, the file is located in the same directory where the script is located. In case the file is located in a different location we may defined $filename as:

$filename="subdir/myfile.txt"; 
// the file is located in a directory named "subdir" within current directory
$filename="/var/www/html/mydir/myfile.txt"; // This is the absolute location within the hard disk
$filename=$_SERVER["DOCUMENT_ROOT"]."/mydir/myfile.txt"; // This is the location relative to document root (the folder containing the website files).

Line 3: a variable named $tempvar is created. This variable (this object) is used to open our file by using a command named fopen. Command fopen is used with two parameters: the name of our file (and the path to it when necessary, as shown above), and second parameter ("r") to indicate what we will do with the file. In this case, "r" means "read".

Line 4: in this line two new commands and a new variable ($content) are used. Command fread will be used to read our object ($tempvar), and command filesize is used to let know to fopen to what extent we want to read our file. In this case, the file will be read completely: filesize($filename) characters of file will be read.

Let's check some modifications of line 4:

$content=fread($tempvar, 100); 
// only the first 100 characters will be read
$content=fread($tempvar, 1000000); //  the first 1000000 characters will be read. In case the file is shorter, it will be read completely.
//  although a big number may be used in this procedure, it is not convenient.
//  a big number (1000000) means a lot of memory will be allocated for this task even though it s not necessary.

Line 5
: $tempvar is closed.

Line 7: $content (the variable containing the text in the file read in lines 3-5) is outputted. 


Example 2: This code is shorter than the one above, but the same results will be obtained (only for PHP version 4.3 or above). 

1
2
3
4
5
6
7
<?php
$filename="myfile.txt";

$content=file_get_contents ($filename);

print "<pre>$content";
?>

Line 4
: Command file_get_contents will read the entire file to variable $content.

Example 3: Let's suppose we have a file with different kind of information in each line (a name in the first line, the last name in the second one, and the age in the third one), and we want to use them separately. This one will be the script we may use:
 

1
2
3
4
5
6
7
8
9
10
11
<?php
$filename="myfile.txt";

$lines= file ($filename);

print "<pre>$content";
?>

Your first name is <? print $lines[0]; ?><BR>
Your last name is <? print $lines[1]; ?><BR>
Your are <? print $lines[2]; ?> years old<BR>

Line 2: A variable named $filename is defined. It contains the name of the file we will read.

Line 4: Command file is used to transfer the content of the file to an array named $lines. Each element within array $lines will content one line of the line.

Line 9-11: Content of array $lines is printed out.

$lines [0] is the content in first line of the file $filename.
$lines [1] is the content in second line of the file $filename.
$lines [2] is the content in third line of the file $filename.
etc.


Create and Write to a text file

Example 4: The basic code we need to create a file is very similar to that one we have used to open a file in example 1:
1
2
3
4
5
6
7
8
9
10
11
<?
$thetext="Write this text in the file";

$filename="myfile.txt";

$tempvar = fopen($filename,"w");
fwrite($tempvar, $thetext);
fclose($tempvar);

print "The text has been saved";
?>

Line 2: a variable name $thetext is defined, and it contains the text to be saved in the file.

Line 4:  $filename is the file (including path if necessary) where $thetext  will be saved.

Line 6-8:  Similar to example 1, but in this case $filename is opened  for writing ("w"), and in line 7, $thetext is written to the file.

In case the file already exists, it will be overwritten.
In case the file does not exist, it will be created.

Line 10:  the output. 


Example 5: very similar to example 4, but in line 6 the file is open for appending text to it ("a"). 

1
2
3
4
5
6
7
8
9
10
11
<?
$thetext="Write this text in the file";

$filename="myfile.txt";

$tempvar = fopen($filename,"a");
fwrite ($tempvar, $thetext);
fclose($tempvar);

print "The text has been saved";
?>


Example 6: This code is shorter than example 4, but the same results will be obtained (only for PHP version 5 or above).
 

1
2
3
4
5
6
7
8
9
<?php
$thetext="Write this text in the file";

$filename="myfile.txt";

file_put_contents ($filename, $thetext);

print "<pre>$content";
?>

Line 6: Command  file_put_contents will write the entire $thetext to file $filename. In case the file does not exist, it will be created, and in case the file already exists, it will be overwrited.


Read and Write compressed files (.gz)

In case we are using files to store information for internal use of our website, it may be interesting to work with compressed files.
The following factors may be considered when using compressed files:
The basic structure of the code used to open and write a compressed file is similar to that one used for text files above. In the table bellow is shown this basic structure.

 
open_gz_file.php
<?php
$filename="myfile.gz;
$tempvar = gzopen($filename,"r");
$content=gzread($tempvar, filesize ($filename));
gzclose($tempvar);

print "<pre>$content";
?>
write_gz_file.php
<?
$thetext="Write this text in the file";

$filename="myfile.gz";

$tempvar = gzopen($filename,"w");
gzwrite($tempvar, $thetext);
gzclose($tempvar);

print "The text has been saved";
?>
append_gz_file.php
<?
$thetext="Write this text in the file";

$filename="myfile.gz";

$tempvar = gzopen($filename,"a");
gzwrite($tempvar, $thetext);
gzclose($tempvar);

print "The text has been saved";
?>


Save IP address and referrer of our page

Let's suppose we want to record the IP address and Referrer of all visitors to our page. The script bellow may be placed within the code of our page and it will create two files to store both data: "ips_file.txt" to store IP addresses and "ref_file.txt" to store referrers. Additionally, this script may be use to track number of times users from a specific IP address visits our page.

To use this code written permission must be available in the directory containing the file with this code (in order to create the files).
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?
// save ip
$ip=$_SERVER["REMOTE_ADDR"];
if ($ip!=""){
        $ipfile= "ips_file.txt";
        $allips =  file_get_contents ($ipfile);
         if (strpos($allips," $ip ")>0){
                  $allips = preg_replace ("/ $ip /"," $ip x",$allips);
                  $tempvar= fopen($ipfile, "w");
                  fwrite ($tempvar, $allips);
                  fclose($tempvar);
       }else{
                  $tempvar = fopen($ipfile, "a");
                  fwrite ($tempvar, " $ip x\n");
                  fclose($tempvar);
        }
}

// save referrer
$ref=$_SERVER["HTTP_REFERER"];
if (strpos($ref,"mydomain.com")==0 and $ref!=""){
        $refffile= "ref_file.txt";
        $tempvar = fopen($refffile, "a");
        fwrite ($tempvar, $ref."\n");
        fclose($tempvar);
}
?>

Lines 2-13: saves the IP addresses to the file "ips_file.txt". Check the typical content of this file below.

Line 3: Get the IP address of visitors and stores the value in variable $ip.
Line 4: If $ip has been obtained, lines 5-16 are processed.
Line 5: Defines the name of the file containing the IP addresses.
Line 6: Reads the content of the file to variable
$allips.
Line 7: Checks whether the IP of visitor has been already save in the file. If so, lines 8-11 are processed. If not, lines 13-15 are processed.
Lines 8-11:  In line 8, a replacement in the variable containing the content of the file "ips_file.txt" is performed (variable $allips). This replacement will place a “x” after the IP address already recorded in the variable. In lines 13-15 the file "ips_file.txt" is overwritten with the content in the variable.

The typical content of file "ips_file.txt" will be the one bellow, where the number of "x" after each IP indicates number of visits from that specific IP to our file.

ips_file.txt
 150.150.150.150 x
 150.150.150.151 xxxxxxx
 150.150.150.152 xxx
 150.150.150.153 x
 150.150.150.154 xxxxxxxxx

Lines 19-26: saves the referrer to the file "ref_file.txt". Check the typical content of this file below.

Line 20: Get the referrer of visitor and stores the value in variable $ref.
Line 21: The following are checked: 
Check whether the referrer site is our own site (whether "mydomain.com" is within the variable $ref); if so, next three lines are not processed.
Check whether the value of $ref is different to "" (so whether a value exists); if  no value is contained in the variable $ref, next three lines are not processed.
Line 22-25: the value at $ref is appended to file ref_file.txt.

The typical content of file "ref_file.txt" will be the one bellow:

ref_file.txt
http://search.yahoo.com/search?p=myquery
http://www.myreferrer.com/main.html
http://search.yahoo.com/search?p=myquery2
http://www.google.com/search?q=a+diferent+query
http://www.myreferrer2.com/dir/file33.html



 PHPTutorial.info.