File Upload File and Directories

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

PHP 

File System
In this tutorial you will learn how to create, access (or read) and manipulate files dynamically using
the PHP's file system functions.

Working with Files in PHP


Since PHP is a server side programming language, it allows you to work with files and directories
stored on the web server. In this tutorial you will learn how to create, access, and manipulate files on
your web server using the PHP file system functions.

Opening a File with PHP fopen() Function


To work with a file you first need to open the file. The PHP fopen() function is used to open a file.
The basic syntax of this function can be given with:
Fopen(filename, mode)
The file may be opened in one of the following modes:

Modes What it does

r Open the file for reading only.


r+ Open the file for reading and writing.
w Open the file for writing only and clears the contents of file. If the file does not exist, PHP will
attempt to create it.
w+ Open the file for reading and writing and clears the contents of file. If the file does not exist, PHP
will attempt to create it.
a Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If
the file does not exist, PHP will attempt to create it.
a+ Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end
of the file. If the file does not exist, PHP will attempt to create it.
x Open the file for writing only. Return FALSE and generates an error if the file already exists. If
the file does not exist, PHP will attempt to create it.
x+ Open the file for reading and writing; otherwise it has the same behavior as 'x'.

If you try to open a file that doesn't exist, PHP will generate a warning message. So, to avoid these
error messages you should always implement a simple check whether a file or directory exists or not
before trying to access it, with the PHP file_exists() function.
Example
<?php
$file = "data.txt";
if(file_exists($file))
{ $handle = fopen($file, "r"); }
Else
{ echo "ERROR: File does not exist."; }
?>

Closing a File with PHP fclose() Function


Once you've finished working with a file, it needs to be closed. The fclose() function is used to close
the file, as shown in the following example:
<?php
$file = "data.txt";
if(file_exists($file))
{
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
/* Some code to be executed */
fclose($handle);
}
else
{ echo "ERROR: File does not exist.";
}
?>

Reading from Files with PHP fread() Function


Now that you have understood how to open and close files. In the following section you will
learn how to read data from a file. PHP has several functions for reading data from a file.
You can read from just one character to the entire file with a single operation.

Reading Fixed Number of Characters


The fread() function can be used to read a specified number of characters from a file. The
basic syntax of this function can be given with.
fread(file handle, length in bytes)
This function takes two parameter — A file handle and the number of bytes to read. The
following example reads 20 bytes from the "data.txt" file including spaces. Let's suppose the
file "data.txt" contains a paragraph of text "The quick brown fox jumps over the lazy dog."
<?php
$file = "data.txt";
if(file_exists($file))
{ $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
$content = fread($handle, "20"); // Read fixed number of bytes from the file
fclose($handle);
echo $content; // Display the file content
}
Else
{ echo "ERROR: File does not exist."; }
?>

Reading the Entire Contents of a File


The fread() function can be used in conjugation with the filesize() function to read the entire file at
once. The filesize() function returns the size of the file in bytes.
<?php
$file = "data.txt";
if(file_exists($file))
{ $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
$content = fread($handle, filesize($file));
fclose($handle);
echo $content; }
else
{ echo "ERROR: File does not exist."; }
?>
The easiest way to read the entire contents of a file in PHP is with the readfile() function. This
function allows you to read the contents of a file without needing to open it. The following example
will generate the same output as above example:
<?php
$file = "data.txt";
if(file_exists($file))
{ readfile($file) or die("ERROR: Cannot open the file.");
}
else
{ echo "ERROR: File does not exist."; }
?>
Another way to read the whole contents of a file without needing to open it is with
the file_get_contents() function. This function accepts the name and path to a file, and reads the
entire file into a string variable. Here's an example:

<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file))
{ // Reading the entire file into a string
$content = file_get_contents($file) or die("ERROR: Cannot open the file.");
echo $content;
}
else
{ echo "ERROR: File does not exist."; }
?>
One more method of reading the whole data from a file is the PHP's file() function. It does a similar
job to file_get_contents() function, but it returns the file contents as an array of lines, rather than a
single string. Each element of the returned array corresponds to a line in the file.
To process the file data, you need to iterate over the array using a foreach loop. Here's an example,
which reads a file into an array and then displays it using the loop:
<?php
$file = "data.txt";
// Check the existence of file
if(file_exists($file))
{ // Reading the entire file into an array
$arr = file($file) or die("ERROR: Cannot open the file.");
foreach($arr as $line)
{ echo $line; }
}
else
{ echo "ERROR: File does not exist."; } ?>

Writing the Files Using PHP fwrite() Function


Similarly, you can write data to a file or append to an existing file using the PHP fwrite() function.
The basic syntax of this function can be given with:
fwrite(file handle, string)
The fwrite() function takes two parameter — A file handle and the string of data that is to be written,
as demonstrated in the following example:
<?php
$file = "note.txt";
$data = "The quick brown fox jumps over the lazy dog.";
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");
fwrite($handle, $data) or die ("ERROR: Cannot write the file.");
fclose($handle);
echo "Data written to the file successfully.";
?>
In the above example, if the "note.txt" file doesn't exist PHP will automatically create it and write
the data. But, if the "note.txt" file already exist, PHP will erase the contents of this file, if it has any,
before writing the new data, however if you just want to append the file and preserve existing
contents just use the mode a instead of w in the above example.

An alternative way is using the file_put_contents() function. It is counterpart


of file_get_contents() function and provides an easy method of writing the data to a file without
needing to open it. This function accepts the name and path to a file together with the data to be
written to the file. Here's an example:

<?php
$file = "note.txt";
$data = "The quick brown fox jumps over the lazy dog.";
file_put_contents($file, $data) or die("ERROR: Cannot write the file.");
echo "Data written to the file successfully.";
?>

If the file specified in the file_put_contents() function already exists, PHP will overwrite it by


default. If you would like to preserve the file's contents you can pass the special FILE_APPEND flag
as a third parameter to the file_put_contents() function. It will simply append the new data to the file
instead of overwitting it. Here's an example:

<?php
$file = "note.txt";
$data = "The quick brown fox jumps over the lazy dog.";
file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the file.");
echo "Data written to the file successfully.";
?>

PHP Filesystem Functions


The following table provides the overview of some other useful PHP filesystem functions that can be
used for reading and writing the files dynamically.

Function Description

fgetc() Reads a single character at a time.


fgets() Reads a single line at a time.
fgetcsv() Reads a line of comma-separated values.
filetype() Returns the type of the file.
feof() Checks whether the end of the file has been reached.
Function Description

is_file() Checks whether the file is a regular file.


is_dir() Checks whether the file is a directory.
is_executable() Checks whether the file is executable.
realpath() Returns canonicalized absolute pathname.
rmdir() Removes an empty directory.

Working with Directories in PHP

Creating Directories in PHP


A new directory can be created in PHP using the mkdir() function. This function takes a path to the
directory to be created. To create a directory in the same directory as your PHP script simply provide
the directory name. To create a new directory in a different directory specify the full path when
calling mkdir().
A second, optional argument allows the specification of permissions on the directory (controlling
such issues as whether the directory is writable):
<?php
$result=mkdir(“/path/to/directory”,”0777”);
?>

Deleting a Directory
Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, the
name of the directory to be deleted. The deletion will only be successful if the directory is empty. If
the directory contains files or other sub-directories the deletion cannot be performed until those files
and sub-directories are also deleted.

Finding and Changing the Current Working Directory


It is unlikely that a web application will be able to perform all of its file related tasks in a single
directory. For this reason, it is vital to be able to both find out the current working directory, and
change to another directory from within a PHP script.
The current working directory can be identified using the getCwd() function:

<?php
$current_dir = getCwd();
echo "Current directory is $current_dir";
?>

The current working directory can be changed using the chdir() function. chdir() takes as the only
argument the path of the new directory:

<?php
$current_dir = getCwd();
echo "Current directory is $current_dir <br>";
chdir ("/tmp");
$current_dir = getCwd();
echo "Current directory is now $current_dir <br>";
?>

Listing Files in a Directory


The files in a directory can be read using the PHP scandir() function. scandir() takes two
arguments. The first argument is the path the directory to be scanned. The second optional argument
specifies how the directory listing is to be sorted. If the argument is 1 the listing is sorted reverse-
alphabetically. If the argument is omitted or set to 0 the list is sorted alphabetically:

<?php
chdir ("/tmp");
$current_dir = getCwd();
echo "Current directory is now $current_dir";
$array = scandir(".", 1);

print_r($array); ?>

PHP File Upload


PHP allows you to upload single and multiple files through few lines of code only.
PHP file upload features allows you to upload binary and text files both. Moreover, you can have the full control over the file to be u
authentication and file operation functions.

PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file siz
associated with file.
Here, we are assuming that file name is filename.
$_FILES['filename']['name']
returns file name.
$_FILES['filename']['type']
returns MIME type of the file.
$_FILES['filename']['size']
returns size of the file (in bytes).
$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
returns error code associated with this file.
The move_uploaded_file() function moves the uploaded file to a new location. The move_uploaded_file() function
checks internally if the file is uploaded thorough the POST request. It moves the file if it is uploaded through the
POST request.
Syntax
1. bool move_uploaded_file ( string $filename , string $destination )  

PHP File Upload Example


File: uploadform.html

<form action="uploader.php" method="post" enctype="multipart/form-data">  
    Select File:  
    <input type="file" name="fileToUpload"/>  
    <input type="submit" value="Upload Image" name="submit"/>  
</form>  
File: uploader.php
<?php  
$target_path = "e:/";  
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);   
  
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {  
    echo "File uploaded successfully!";  
} else{  
    echo "Sorry, file not uploaded, please try again!";  
}  
?>  
1. Display image in PHP
<?php
$result = $_GET['image'];
echo '<img src="images/gallery/'.$result.'.jpg">';
?>
OR
<?php $result = $_GET['image']; ?>
<img src="images/gallery/<?php echo $result; ?>.jpg">

PHP code for image upload and display


<html>
<head>
<title>PHP File Upload example</title>
</head>
<body>
<form action="fileupload.php" method="post">
Select image :
<input type="file" name="file"><br/>
<input type="submit" value="Upload" name="Submit1"> <br/>

</form>
<?php
if(isset($_POST['Submit1']))
{
$filepath = "images/" . $_FILES["file"]["name"];

if(move_uploaded_file($_FILES["file"]["tmp_name"], $filepath))
{
echo "<img src=".$filepath." height=200 width=300 />";
}
else
{
echo "Error !!";
}
}
?>
</body>
</html>

What is PHP mail?

PHP mail is the built in PHP function that is used to send emails from PHP scripts.

The mail function accepts the following parameters;


 Email address
 Subject
 Message
 CC or BC email addresses
o It’s a cost effective way of notifying users on important events.
o Let users contact you via email by providing a contact us form on the website that
emails the provided content.
o Developers can use it to receive system errors by email
o You can use it to email your newsletter subscribers.
o You can use it to send password reset links to users who forget their passwords
o You can use it to email activation/confirmation links. This is useful when registering
users and verifying their email addresses

Sending mail using PHP

The PHP mail function has the following basic syntax

<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>

  HERE,

 “$to_email_address” is the email address of the mail recipient


 “$subject” is the email subject
 “$message” is the message to be sent.
 “[$headers]” is optional, it can be used to include information such as CC, BCC
o CC is the acronym for carbon copy. It’s used when you want to send a copy to an
interested person i.e. a complaint email sent to a company can also be sent as CC to
the complaints board.
o BCC is the acronym for blind carbon copy. It is similar to CC. The email addresses
included in the BCC section will not be shown to the other recipients.

Simple Mail Transmission Protocol (SMTP)

PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail.

On a hosted server, the SMTP settings would have already been set.

The SMTP mail settings can be configured from “php.ini” file in the PHP installation folder.
Configuring SMTP settings on your localhost Assuming you are using xampp on windows, locate
the “php.ini” in the directory “C:\xampp\php”.

Let’s now look at an example that sends a simple mail.

<?php    
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>

You might also like