Back


PHP Introduction Day 1 Day 2 Day 3 Day 4 Day 5

PHP – File Create

Before you can do anything with a file it has to exist! In this lesson you will learn how to create a file using PHP.

 

PHP – Creating Confusion

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).

 

PHP – How to Create a File

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.

 

PHP – File Open

In the previous lesson we used the function fopen to create a new file. In this lesson we will be going into the details of this important function and see what it has to offer.

 

PHP – 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.

 

PHP – 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.

 

PHP – 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.

PHP – 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);

 

PHP – File Open: Summary

You can open a file in many different ways. You can delete everything and begin writing on a clean slate, you can add to existing data, and you can simply read information from a file. In later lessons we will go into greater detail on how each of these different ways to open a file is used in the real world and give some helpful examples.

 

PHP – File Close

The next logical step after you have opened a file and finished your business with it is to close that file down. You don’t want an open file running around on your server taking up resources and causing mischief!

 

PHP – 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!

 

PHP – 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.

PHP – File Write

Now that you know how to open and close a file, lets get on to the most useful part of file manipulation, writing! There is really only one main function that is used to write and it’s logically called fwrite.
PHP – 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.

PHP Code:
$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘w’);

 

PHP – 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.

PHP 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

 

PHP – 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.

PHP 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

PHP – File Read

PHP – File Open: Read

Before we can read information from a file we have to use the function fopen to open the file for reading. Here’s the code to read-open the file we created in the PHP File Write lessons.
PHP Code:
$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘r’);

The file we created in the last lesson was named “testFile.txt”. Your PHP script that you are writing should reside in the same directory as “text.txt”. Here are the contents of our file from File Write.

testFile.txt Contents:
Floppy Jalopy
Pointy Pinto

Now that the file is open, with read permissions enabled, we can get started!

PHP – 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.

 

PHP – 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.

PHP 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.

 

PHP – 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.

 

PHP – 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.

PHP – Unlink Function

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

PHP 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.

 

PHP – 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.

PHP – 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.

PHP 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.

 

PHP – 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.

PHP 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

 

PHP – 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!

PHP – 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.

 

PHP – 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.
PHP Code:
$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘w’);
fclose($fh);

 

PHP – 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.

PHP – File Upload

A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.

PHP – File Upload: HTML Form

Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload. See our HTML Form lesson for a more in-depth look at forms.

HTML Code:
<form enctype=”multipart/form-data” action=”uploader.php” method=”POST”>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”100000″ />
Choose a file to upload: <input name=”uploadedfile” type=”file” /><br />
<input type=”submit” value=”Upload File” />
</form>
Here is a brief description of the important parts of the above code:

  • enctype=”multipart/form-data” – Necessary for our to-be-created PHP file to function properly.
  • action=”uploader.php” – The name of our PHP page that will be created, shortly.
  • method=”POST” – Informs the browser that we want to send information to the server using POST.
  • input type=”hidden” name=”MA… – Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example.
  • input name=”uploadedfile” – uploadedfile is how we will access the file in our PHP script.

Save that form code into a file and call it upload.html. If you view it in a browser it should look like this:

 

Display:

Choose a file to upload:

After the user clicks submit, the data will be posted to the server and the user will be redirected to uploader.php. This PHP file is going to process the form data and do all the work.

PHP – File Upload: What’s the PHP Going to Do?

Now that we have the right HTML form we can begin to code the PHP script that is going to handle our uploads. Typically, the PHP file should make a key decision with all uploads: keep the file or throw it away. A file might be thrown away from many reasons, including:

  • The file is too large and you do not want to have it on your server.
  • You wanted the person to upload a picture and they uploaded something else, like an executable file (.exe).
  • There were problems uploading the file and so you can’t keep it.

This example is very simple and omits the code that would add such functionality.

 

PHP – File Upload: uploader.php

When the uploader.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be destroyed! To save our precious file we are going to need to make use of the $_FILES associative array.

The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example.

  • uploadedfile – uploadedfile is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with.
  • $_FILES[‘uploadedfile’][‘name’] – name contains the original path of the user uploaded file.
  • $_FILES[‘uploadedfile’][‘tmp_name’] – tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.

Now we can finally start to write a basic PHP upload manager script! Here is how we would get the temporary file name, choose a permanent name, and choose a place to store the file.

PHP Code:
// Where the file is going to be placed
$target_path = “uploads/”;

/* Add the original filename to our target path.
Result is “uploads/filename.extension” */
$target_path = $target_path . basename( $_FILES[‘uploadedfile’][‘name’]);

NOTE: You will need to create a new directory in the directory where uploader.php resides, called “uploads”, as we are going to be saving files there.

We now have all we need to successfully save our file to the server. $target_path contains the path where we want to save our file to.

 

PHP – File Upload: move_uploaded_file Function

Now all we have to do is call the move_uploaded_file function and let PHP do its magic. The move_uploaded_file function needs to know 1) The path of the temporary file (check!) 2) The path where it is to be moved to (check!).

PHP Code:
$target_path = “uploads/”;

$target_path = $target_path . basename( $_FILES[‘uploadedfile’][‘name’]);

if(move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $target_path)) {
echo “The file “.  basename( $_FILES[‘uploadedfile’][‘name’]).
” has been uploaded”;
} else{
echo “There was an error uploading the file, please try again!”;
}

If the upload is successful, then you will see the text “The file filename has been uploaded”. This is because move_uploaded_file returns true if the file was moved, and false if it had a problem.

If there was a problem then the error message “There was an error uploading the file, please try again!” would be displayed.

FILE SYSTEMS

  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

 

Opening and Closing Files

The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Mode     Purpose
r     Opens the file for reading only.
Places the file pointer at the beginning of the file.
r+     Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
w     Opens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
w+     Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
a     Opens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
a+     Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.

If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.

 

Reading a file
Once a file is opend using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.

The files’s length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.

So here are the steps required to read a file with PHP.

  • Open a file using fopen() function.
  • Get the file’s length using filesize() function.
  • Read the file’s content using fread() function.
  • Close the file with fclose() function.

The following example assigns the content of a text file to a variable then displays those contents on the web page.

<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>

<?php
$filename = “/home/user/guest/tmp.txt”;
$file = fopen( $filename, “r” );
if( $file == false )
{
echo ( “Error in opening file” );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );

fclose( $file );

echo ( “File size : $filesize bytes” );
echo ( “<pre>$text</pre>” );
?>

</body>
</html>

Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third intger argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.

The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument

<?php
$filename = “/home/user/guest/newfile.txt”;
$file = fopen( $filename, “w” );
if( $file == false )
{
echo ( “Error in opening new file” );
exit();
}
fwrite( $file, “This is  a simple test\n” );
fclose( $file );
?>

<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>

<?php
if( file_exist( $filename ) )
{
$filesize = filesize( $filename );
$msg = “File  created with name $filename “;
$msg .= “containing $filesize bytes”;
echo ($msg );
}
else
{
echo (“File $filename does not exit” );
}
?>
</body>
</html>

 

PHP File Uploading

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.

Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini

The process of uploading a file follows these steps

  • The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.
  • The user clicks the browse button and selects a file to upload from the local PC.
  • The full path to the selected file appears in the text filed then the user clicks the submit button.
  • The selected file is sent to the temporary directory on the server.
  • The PHP script that was specified as the form handler in the form’s action attribute checks that the file has arrived and then copies the file into an intended directory.
  • The PHP script confirms the success to the user.

As usual when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. If either is set to be read-only then process will fail.

An uploaded file could be a text file or image file or any document.

 

Creating an upload form:

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action=”/php/file_uploader.php” method=”post”
enctype=”multipart/form-data”>
<input type=”file” name=”file” size=”50″ />
<br />
<input type=”submit” value=”Upload File” />
</form>
</body>
</html>

 

This will display following result:

File Upload:
Select a file to upload:

NOTE: This is just dummy form and would not work.

 

Creating an upload script:

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input’s name attribute in uploading form was file, then PHP would create following five variables:

  • $_FILES[‘file’][‘tmp_name’]– the uploaded file in the temporary directory on the web server.
  • $_FILES[‘file’][‘name’] – the actual name of the uploaded file.
  • $_FILES[‘file’][‘size’] – the size in bytes of the uploaded file.
  • $_FILES[‘file’][‘type’] – the MIME type of the uploaded file.
  • $_FILES[‘file’][‘error’] – the error code associated with this file upload.

The following example below attempts to copy a file uploaded by the HTML Form listed in previous section page to /var/www/html directory which is document root of your PHP server and it will display all the file’s detail upon completion. Please note that if you are going to display uploaded file then don’t try with binary files like images or word document.

Here is the code of uploader.php script which will take care of uploading a file.

<?php
if( $_FILES[‘file’][‘name’] != “” )
{
copy( $_FILES[‘file’][‘name’], “/var/www/html” ) or
die( “Could not copy file!”);
}
else
{
die(“No file specified!”);
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES[‘file’][‘name’];  ?>
<li>File size: <?php echo $_FILES[‘file’][‘size’];  ?> bytes
<li>File type: <?php echo $_FILES[‘file’][‘type’];  ?>
</ul>
</body>
</html>

 

When you will upload a file using upload form and upload script, it will display following result:

Uploaded File Info:

  • Sent file: uploadedfile.txt
  • File size: 2003 bytes
  • File type: image/jpg

You try out above example yourself on your webserver.

PHP – Sending Emails

PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].

Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.

The configuration for Windows should look something like this:

[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only
sendmail_from = webmaster@test.com

Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.

The configuration for Linux should look something like this:

[mail function]
; For Win32 only.
SMTP =

; For win32 only
sendmail_from =

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i

Now you are ready to go:

Sending plain text email:

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient’s email address, the subject of the the message and the actual message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );

Here is the description for each parameters.

Parameter    Description
to    Required. Specifies the receiver / receivers of the email
subject    Required. Specifies the subject of the email. This parameter cannot contain any newline characters
message    Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers    Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters    Optional. Specifies an additional parameter to the sendmail program

As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.

Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

Example:

Following example will send an HTML email message to xyz@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.
<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
$to = “xyz@somedomain.com”;
$subject = “This is subject”;
$message = “This is simple text message.”;
$header = “From:abc@somedomain.com \r\n”;
$retval = mail ($to,$subject,$message,$header);
if( $retval == true )
{
echo “Message sent successfully…”;
}
else
{
echo “Message could not be sent…”;
}
?>
</body>
</html>

 

Sending HTML email:
When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.

While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example:

Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should recieve all content from the user and then it should send an email.

<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = “xyz@somedomain.com”;
$subject = “This is subject”;
$message = “<b>This is HTML message.</b>”;
$message .= “<h1>This is headline.</h1>”;
$header = “From:abc@somedomain.com \r\n”;
$header = “Cc:afgh@somedomain.com \r\n”;
$header .= “MIME-Version: 1.0\r\n”;
$header .= “Content-type: text/html\r\n”;
$retval = mail ($to,$subject,$message,$header);
if( $retval == true )
{
echo “Message sent successfully…”;
}
else
{
echo “Message could not be sent…”;
}
?>
</body>
</html>

 

Sending attachments with email:

To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.

A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email’s final section must also end with two hyphens.

Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.

Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.

<html>
<head>
<title>Sending attachment using PHP</title>
</head>
<body>
<?php
$to = “xyz@somedomain.com”;
$subject = “This is subject”;
$message = “This is test message.”;
# Open a file
$file = fopen( “/tmp/test.txt”, “r” );
if( $file == false )
{
echo “Error in opening file”;
exit();
}
# Read the file into a variable
$size = filesize(“/tmp/test.txt”);
$content = fread( $file, $size);

# encode the data for safe transit
# and insert \r\n after every 76 chars.
$encoded_content = chunk_split( base64_encode($content));

# Get a random 32 bit number using time() as seed.
$num = md5( time() );

# Define the main headers.
$header = “From:xyz@somedomain.com\r\n”;
$header .= “MIME-Version: 1.0\r\n”;
$header .= “Content-Type: multipart/mixed; “;
$header .= “boundary=$num\r\n”;
$header .= “–$num\r\n”;

# Define the message section
$header .= “Content-Type: text/plain\r\n”;
$header .= “Content-Transfer-Encoding:8bit\r\n\n”;
$header .= “$message\r\n”;
$header .= “–$num\r\n”;

# Define the attachment section
$header .= “Content-Type:  multipart/mixed; “;
$header .= “name=\”test.txt\”\r\n”;
$header .= “Content-Transfer-Encoding:base64\r\n”;
$header .= “Content-Disposition:attachment; “;
$header .= “filename=\”test.txt\”\r\n\n”;
$header .= “$encoded_content\r\n”;
$header .= “–$num–“;

# Send email now
$retval = mail ( $to, $subject, “”, $header );
if( $retval == true )
{
echo “Message sent successfully…”;
}
else
{
echo “Message could not be sent…”;
}
?>
</body>
</html>

 

 

PHP File Handling

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);
?>

PHP 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 fileto the specified folder.

Note: This example saves the file to a new folder called “upload”

PHP: Working with Directories

As is necessary for any language, PHP has a complete set of directory support functions. PHP gives you a variety of functions to read and manipulate directories and directory entries. Like other file-related parts of PHP, the functions are similar to the C functions that accomplish the same tasks, with some simplifications. This tutorial describes how PHP handles directories. You will look at how to create, remove, and read them.

  • Reading the Contents of a Directory
  • Deleting the Directory and Its Contents
  • Creating New Directories

Reading the Contents of a Directory

Let’s start with simple listing the contents of a directory. We need three functions to perform this task: opendir(), readdir() and closedir(). The opendir() function takes one parameter, which is the directory we want to read, and returns a directory handle to be used in subsequent readdir() and closedir() calls. opendir() returns False if the directory could not be opened.

The readdir() function takes one parameter, which is the handle that opendir() returned and each time we call readdir() it returns the filename of the next file in the directory. readdir() returns False if the end of the directory has been reached. Note that readdir() returns only the names of its items, rather than full paths.

The example below creates a select box that lists all the files in a directory. Copy and paste this code and save it as index.php in a directory you wish do display all files for. It automatically excludes itself from the list, and is easy to modify to make it ignore other files as well:

<?php
// open the current directory
$dhandle = opendir(‘.’);
// define an array to hold the files
$files = array();

if ($dhandle) {
// loop through all of the files
while (false !== ($fname = readdir($dhandle))) {
// if the file is not this file, and does not start with a ‘.’ or ‘..’,
// then store it for later display
if (($fname != ‘.’) && ($fname != ‘..’) &&
($fname != basename($_SERVER[‘PHP_SELF’]))) {
// store the filename
$files[] = (is_dir( “./$fname” )) ? “(Dir) {$fname}” : $fname;
}
}
// close the directory
closedir($dhandle);
}

echo “<select name=\”file\”>\n”;
// Now loop through the files, echoing out a new select option for each one
foreach( $files as $fname )
{
echo “<option>{$fname}</option>\n”;
}
echo “</select>\n”;
?>

First, we open the directory for reading with the opendir() function and use a while statement to loop through each of its entries. We call readdir() as part of the while statement’s test expression, assigning its result to the $fname variable. We are explicitly testing whether the return value is equal to and of the same type as False since otherwise, any directory entry whose name evaluates to False will stop the loop prematurely. Within the body of the while statement, we check if the file is not this file, and does not start with a . (current directory) or .. (parent directory) and then store the file name into the $files array. We also do one more check. If a full file path leads to a directory then we add to the file name “(Dir)”.

There is another way to iterate over all files in a directory. PHP 5 has a set of objects called iterators. Iterators help eliminate problems in your code. For instance, PHP 5 provides a DirectoryIterator:

<?php
echo “<select name=\”file\”>\n”;
foreach (new DirectoryIterator(‘.’) as $file) {
// if the file is not this file, and does not start with a ‘.’ or ‘..’,
// then store it for later display
if ( (!$file->isDot()) && ($file->getFilename() != basename($_SERVER[‘PHP_SELF’])) ) {
echo “<option>”;
// if the element is a directory add to the file name “(Dir)”
echo ($file->isDir()) ? “(Dir) “.$file->getFilename() : $file->getFilename();
echo “</option>\n”;
}
}
echo “</select>\n”;
?>

This example produces the same results as the earlier code that uses the directory functions, but this code is shorter and safer because you cannot forget the !== = comparison.

Deleting the Directory and Its Contents

PHP has the rmdir( ) function that takes a directory name as its only parameter and will remove the specified directory from the file system, if the process running your script has the right to do so. However, the rmdir() function works only on empty directories. The example below deletes empty directory named “temporary”:

<?php
rmdir( “temporary” );
?>

If you want to delete non-empty directory, you should use the recursion. In the following example we create recursive function named deleteDir() that takes a directory name as a parameter and will go through each subdirectory, deleting files as they go. When the directory is empty, we use rmdir() to remove it.

<?php
function deleteDir($dir) {
// open the directory
$dhandle = opendir($dir);

if ($dhandle) {
// loop through it
while (false !== ($fname = readdir($dhandle))) {
// if the element is a directory, and
// does not start with a ‘.’ or ‘..’
// we call deleteDir function recursively
// passing this element as a parameter
if (is_dir( “{$dir}/{$fname}” )) {
if (($fname != ‘.’) && ($fname != ‘..’)) {
echo “<u>Deleting Files in the Directory</u>: {$dir}/{$fname} <br />”;
deleteDir(“$dir/$fname”);
}
// the element is a file, so we delete it
} else {
echo “Deleting File: {$dir}/{$fname} <br />”;
unlink(“{$dir}/{$fname}”);
}
}
closedir($dhandle);
}
// now directory is empty, so we can use
// the rmdir() function to delete it
echo “<u>Deleting Directory</u>: {$dir} <br />”;
rmdir($dir);
}

// call deleteDir function and pass to it
// as a parameter a directory name
deleteDir(“temporary”);
?>
Another way to delete non-empty directory is to use RecursiveDirectoryIterator and RecursiveIteratorIterator. The RecursiveIteratorIterator must be told to provide children (files and subdirectories) before parents with its CHILD_FIRST constant. Have a look at the code:

<?php
function deleteDir($dir) {
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file)
{
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
}

deleteDir(“temporary”);
?>

Note: The CHILD_FIRST constant was added with PHP 5.1

 

Creating New Directories

Creating new directories in PHP is accomplished using the mkdir() function, which takes two parameters. These parameters are, in order, a directory name you want to create and a permission mode for a new directory, which must be an octal number. The mode parameter is optional and has an effect only on Unix systems. Have a look at the example:

<?php
// if /path/to/my exists, this should return true
// if PHP has the right permissions
mkdir(“/path/to/directory”, 0777);
?>

By default, the mkdir() function only creates a directory if its parent exists. In PHP 5 the recursive parameter was added which should be true or false, depending on whether you want to create parent directories or not. In the following example, we pass true as a third parameter to mkdir(), so this makes the function act recursively to create any missing parent directories.

<?php
// will create /path/to/directory and
// also create /path and /path/to if needed and allowed
mkdir(“/path/to/directory”, 0777, true);
?> 

PHP Introduction Day 1 Day 2 Day 3 Day 4 Day 5

 

 

Share this: