السبت، 25 يونيو 2011

Files2

File Append

So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.

File Open: Append

If we want to add on to a file we need to open it up in append mode. The code below does just that.

Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.

File Write: Appending Data

Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.

Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2

Append: Why Use It?

The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.
A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append! 

File Truncate

As we have mentioned before, when you open a file for writing with the paramater 'w' it completely wipes all data from that file. This action is also referred to as "truncating" a file. Truncate literally means to shorten.


File Open: Truncate

To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.

 Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);

Truncate: Why Use It?

Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These type of files are most often referred to as temporary files.
For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated and overwritten with new, up-to-date data every thirty seconds.
This might not be the most efficient program, but it is a nice usage of truncate.

File Upload



With PHP, it is possible to upload files to the server.

Create an Upload-File Form

To allow users to upload files from a form can be very useful.
Look at the following HTML form for uploading files:
<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>
Notice the following about the HTML form above:
  • The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded
  • The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.

Create The Upload Script

The "upload_file.php" file contains the code for uploading a file:
<?php
if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br />";
  echo "Type: " . $_FILES["file"]["type"] . "<br />";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
?>
By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:
  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload
This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

Restrictions on Upload

In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>
Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg.

Saving the Uploaded File

The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server.
The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>
The script above checks if the file already exists, if it does not, it copies the file to the specified folder.
Note: This example saves the file to a new folder called "upload"

Files1

Files

Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files. 

Be Careful

When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.


File Create]

In PHP, a file is created using a command that is also used to open files. It may seem a little confusing, but we'll try to clarify this conundrum.
In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this later). 

The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).
Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.

PHP Code:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle); 
The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.
  1. $ourFileName = "testFile.txt"; Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName.
  2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character "w".
    Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.
  3. fclose($ourFileHandle); We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.

PHP - Permissions

If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.

Different Ways to Open a File

For many different technical reasons, PHP requires you to specify your intentions when you open a file. Below are the three basic ways to open a file and the corresponding character that PHP uses.
  • Read: 'r'
Open a file for read only use. The file pointer begins at the front of the file.
  • Write: 'w'
Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file pointer begins at the start of the file.
  • Append: 'a'
Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file.
A file pointer is PHP's way of remembering its location in a file. When you open a file for reading, the file pointer begins at the start of the file. This makes sense because you will usually be reading data from the front of the file.
However, when you open a file for appending, the file pointer is at the end of the file, as you most likely will be appending data at the end of the file. When you use reading or writing functions they begin at the location specified by the file pointer.

Explanation of Different Types of fopen

These three basic ways to open a file have distinct purposes. If you want to get information out of a file, like search an e-book for the occurrences of "cheese", then you would open the file for read only.
If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the "w" option. This would wipe clean all existing data within the file.
If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to append the data on to the end. This would be the "a" option.

File Open: Advanced

There are additional ways to open a file. Above we stated the standard ways to open a file. However, you can open a file in such a way that reading and writing is allowable! This combination is done by placing a plus sign "+" after the file mode character.
  • Read/Write: 'r+'
Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.
  • Write/Read: 'w+'
This is exactly the same as r+, except that it deletes all information in the file when the file is opened.
  • Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of the file.

File Open: Cookie Cutter

Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above (i.e. r, w, a, etc).

Pseudo PHP Code:

$ourFileName = "testFile.txt";
$fh = fopen($ourFileName, 'X') or die("Can't open file");
fclose($fh);

File Close Description

In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it's a good programming practice and because we told you to!

File Close Function

In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.

PHP Code:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle); 
The function fclose requires the file handle that we want to close down. In our example we set our variable "$fileHandle" equal to the file handle returned by the fopen function.
After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function.

File Open: Write

Before we can write information to our test file we have to use the function fopen to open the file for writing.

Code

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');

File Write: fwrite Function

We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you're good to go!
Below we are writing a couple of names into our test file testFile.txt and separating them with a carriaged return.

 Code

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh); 
 
The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.
We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second contained Tracy Tanner. After we finished writing we closed the file using the fclose function.
If you were to open the testFile.txt file in NOTEPAD it would look like this:

Contents of the testFile.txt File:

Bobby Bopper
Tracy Tanner

File Write: Overwriting

Now that testFile.txt contains some data we can demonstrate what happens when you open an existing file for writing. All the data contained in the file is wiped clean and you start with an empty file. In this example we open our existing file testFile.txt and write some new data into it.

Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);
$stringData = "Pointy Pinto\n";
fwrite($fh, $stringData);
fclose($fh); 
If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present.

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto


File Read: fread Function

The fread function is the staple for getting data out of a file. The function requires a file handle, which we have, and an integer to tell the function how much data, in bytes, it is supposed to read.
One character is equal to one byte. If you wanted to read the first five characters then you would use five as the integer.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;

Display:

Flopp
The first five characters from the testFile.txt file are now stored inside $theData. You could echo this string, $theData, or write it to another file.
If you wanted to read all the data from the file, then you need to get the size of the file. The filesize function returns the length of a file, in bytes, which is just what we need! The filesize function requires the name of the file that is to be sized up.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

Display:

Floppy Jalopy Pointy Pinto
Note: It is all on one line because our "testFile.txt" file did not have a <br /> tag to create an HTML line break. Now the entire contents of the testFile.txt file is stored in the string variable $theData.

File Read: gets Function

PHP also lets you read a line of data at a time from a file with the gets function. This can or cannot be useful to you, the programmer. If you had separated your data with new lines then you could read in one segment of data at a time with the gets function.
Lucky for us our "testFile.txt" file is separated by new lines and we can utilize this function.

Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;

testFile.txt Contents:

Floppy Jalopy
The fgets function searches for the first occurrence of "\n" the newline character. If you did not write newline characters to your file as we have done in File Write, then this function might not work the way you expect it to.

The fopen() function is used to open files in PHP.

Opening a File

The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:
<html>
<body>

<?php
$file=fopen("welcome.txt","r");
?>

</body>
</html>
The file may be opened in one of the following modes:
Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Note: If the fopen() function is unable to open the specified file, it returns 0 (false).

Example

The following example generates a message if the fopen() function is unable to open the specified file:
<html>
<body>

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>

</body>
</html>


Closing a File

The fclose() function is used to close an open file:
<?php
$file = fopen("test.txt","r");

//some code to be executed

fclose($file);
?>


Check End-of-file

The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.
Note: You cannot read from files opened in w, a, and x mode!
if (feof($file)) echo "End of file";


Reading a File Line by Line

The fgets() function is used to read a single line from a file.
Note: After a call to this function the file pointer has moved to the next line.

Example

The example below reads a file line by line, until the end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>


Reading a File Character by Character

The fgetc() function is used to read a single character from a file.
Note: After a call to this function the file pointer moves to the next character.

Example

The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);
?>


File Delete

You know how to create a file. You know how to open a file in an assortment of different ways. You even know how to read and write data from a file!
Now it's time to learn how to destroy (delete) files. In PHP you delete files by calling the unlink function.

 

File Unlink

When you view the contents of a directory you can see all the files that exist in that directory because the operating system or application that you are using displays a list of filenames. You can think of these filenames as links that join the files to the directory you are currently viewing.
If you unlink a file, you are effectively causing the system to forget about it or delete it!
Before you can delete (unlink) a file, you must first be sure that it is not open in your program. Use the fclose function to close down an open file.

Unlink Function

Remember from the PHP File Create lesson that we created a file named testFile.txt.

Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the file to start working its destructive magic.

PHP Code:

$myFile = "testFile.txt";
unlink($myFile);
The testFile.txt should now be removed.

Unlink: Safety First!

With great power comes a slough of potential things you can mess up! When you are performing the unlink function be sure that you are deleting the right file!



Creating Secure Login

 This articles demonstrate and explains how to create a secure PHP login script that will allow safe authentication. Here, cookies are not used because of preventive measure against cross-side scripting. The back-end used is MySQL. So, you should have knowledge of MySQL and database as well.

Database Schema

For example lets make a table called login for this tutorial purpose only. For commercial purpose, please do add relevant attributes in the table. Use SQL below to create a table of login.
CREATE TABLE login (
user_name varchar(20) NOT NULL default '',
user_pass char(32) binary NOT NULL default '',
PRIMARY KEY (username)
);

Creating a HTML Form

<form method="post" action="login.php" name="login">
<input name="user_name" size="18" type="text" />
<input name="user_pass" size="18" type="text" />
<input name="submit" value="Login" type="submit" />
</form>

Handling Form


if(count($_POST) &gt; 0) {
 $user_name = htmlspecialchars($_POST["user_name"]);
 $user_pass = htmlspecialchars($_POST["user_pass"]);
 
 $sql = "SELECT user_name,user_pass FROM login
           WHERE user_name=\"$user_name\"
            AND    user_pass=\"$user_pass\"";
 
 $rs = mysql_query($sql);               //execute the query
 if(mysql_num_rows($rs) == 1)  {
  // username and passwords exists in database
       //other codes
 }
 else {
  //invalid username of password
  //redirect to login page
 
  header("Location: login.php");
 }
 
}
Above is fairly a simple login page. We can add many other functionalities.

How to Get IP Address of Visitor

This is a simple PHP tutorials and script for getting remote visitors with their IP Address. With this tracking your visitor is very easy and simple with PHP. PHP has a set of global variables. Among them, we use $_SERVER variable to get an IP address of a remote computer. REMOTE_ADDR is the constant that is used to get the IP Address of a remote computer.
Note that this script may not return IP Address if the client/user firewall is on or when client is using some proxy software.

< ?php
 $ipaddress=$_SERVER["REMOTE_ADDR"];
 echo "Your IP ADDRESS: ". $ipaddress;
?>
 
 
 
Another way of retrieving IP Address is using function getenv().
 
 
< ?php
 $userip = $_SERVER["HTTP_X_FORWARDED_FOR"];
 $proxy = $_SERVER["REMOTE_ADDR"];
 $host = @gethostbyaddr($_SERVER["HTTP_X_FORWARDED_FOR"]);
?>
 
 

OUTPUT

Server IP ADDRESS: [exec]echo $_SERVER["HTTP_X_FORWARDED_FOR"];[/exec]
User IP ADDRESS: [exec]echo $_SERVER["REMOTE_ADDR"];[/exec]
User HOST ADDRESS: [exec]echo @gethostbyaddr($_SERVER["HTTP_X_FORWARDED_FOR"]);[/exec]
 
 
 
  $userip is the IP address of the user thats been passed on by the 
server. $proxy is the IP address of the server itself and $host is the 
host address of the user. If your PHP version is less than 4.3 then use 
$HTTP_SERVER_VARS in place of $_SERVER
 
 //////////
<?php
 // A simple script to get ip address of visitor
         $userip = $_SERVER["HTTP_X_FORWARDED_FOR"];
         $proxy = $_SERVER["REMOTE_ADDR"];
         $host = @gethostbyaddr($_SERVER["HTTP_X_FORWARDED_FOR"]);
?> 
 ////////// 

Adding Text to an Image

 This small script describes how to add a custom text to an image loaded onto your page. One of my client wanted to add a copyright notice in her images related to her site. So, I came up with this small PHP script for her.

Adding Text to an Image


Using the PHP GD function called imagecreatefromjpeg, imagecreatefromgif and imagecreatefrompng. We can add a custom text to an already existing image file.
So you have imagecreatefromjpeg for jpeg file, imagecreatefrompng for png file and so on.

< ?php
header("Content-type: image/png");
$string = "copyright: some text";
$font = 4;
$width = imagefontwidth($font)* strlen($string) ;
$height = imagefontheight($font) ;


This will setup the structure of the data being sent to the image file as well as what location to place the text at. In this case we want to place it on the bottom right of the page.
Now, we use imagecreatefrompng to create image from a file, set the text color, get the images dimensions, and figure on where to place the text. 


$im = imagecreatefrompng("/path/to/yourimagefile");
$x = imagesx($im) - $width ;
$y = imagesy($im) - $height;
 
$backgroundColor = imagecolorallocate ($im, 255, 255, 255);   //white background
$textColor = imagecolorallocate ($im, 0, 0, 0);   //black text
imagestring ($im, $font, $x, $y,  $string, $textColor);
 
 
Finally we produce the new image that will display custom text in an image. 

imagepng ($im);
?>
 
 

Here is the complete code:

< ?php
header ("Content-type: image/png");
$string = "your text";
// try changing this as well
$font = 4;
$width = imagefontwidth($font) * strlen($string) ;
$height = imagefontheight($font) ;
$im = imagecreatefrompng("/path/to/yourimagefile");
$x = imagesx($im) - $width ;
$y = imagesy($im) - $height;
$backgroundColor = imagecolorallocate ($im, 255, 255, 255);
$textColor = imagecolorallocate ($im, 0, 0,0);
imagestring ($im, $font, $x, $y,  $string, $textColor);
imagepng($im);
?>