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.
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 Filesystem Reference
PHP
Filesystem Functions
PHP Filesystem Introduction
The filesystem functions allow you to access and manipulate the
filesystem.
Installation
The filesystem functions are part of the PHP core. There is no
installation needed to use these functions.
Runtime Configuration
The behavior of the filesystem functions is affected by settings
in php.ini.
Filesystem configuration options:
Name
|
Default
|
Description
|
Changeable
|
allow_url_fopen
|
"1"
|
Allows fopen()-type functions to work with URLs (available since
PHP 4.0.4)
|
PHP_INI_SYSTEM
|
user_agent
|
NULL
|
Defines the user agent for PHP to send (available since PHP 4.3)
|
PHP_INI_ALL
|
default_socket_timeout
|
"60"
|
Sets the default timeout, in seconds, for socket based streams
(available since PHP 4.3)
|
PHP_INI_ALL
|
from
|
""
|
Defines the anonymous FTP password (your email address)
|
PHP_INI_ALL
|
auto_detect_line_endings
|
"0"
|
When set to "1", PHP will examine the data read by
fgets() and file() to see if it is using Unix, MS-Dos or Mac line-ending
characters (available since PHP 4.3)
|
PHP_INI_ALL
|
Unix / Windows Compatibility
When specifying a path on Unix platforms, the forward slash (/) is
used as directory separator. However, on Windows platforms, both forward slash
(/) and backslash (\) can be used.
PHP Filesystem Functions
PHP:
indicates the earliest version of PHP that supports the function.
Function
|
Description
|
PHP
|
Returns the filename component of a path
|
3
|
|
Changes the file group
|
3
|
|
Changes the file mode
|
3
|
|
Changes the file owner
|
3
|
|
Clears the file status cache
|
3
|
|
Copies a file
|
3
|
|
delete()
|
See unlink() or unset()
|
|
Returns the directory name component of a path
|
3
|
|
Returns the free space of a directory
|
4
|
|
Returns the total size of a directory
|
4
|
|
Alias of disk_free_space()
|
3
|
|
Closes an open file
|
3
|
|
Tests for end-of-file on an open file
|
3
|
|
Flushes buffered output to an open file
|
4
|
|
Returns a character from an open file
|
3
|
|
Parses a line from an open file, checking for CSV fields
|
3
|
|
Returns a line from an open file
|
3
|
|
Returns a line, with HTML and PHP tags removed, from an open
file
|
3
|
|
Reads a file into an array
|
3
|
|
Checks whether or not a file or directory exists
|
3
|
|
Reads a file into a string
|
4
|
|
Writes a string to a file
|
5
|
|
Returns the last access time of a file
|
3
|
|
Returns the last change time of a file
|
3
|
|
Returns the group ID of a file
|
3
|
|
Returns the inode number of a file
|
3
|
|
Returns the last modification time of a file
|
3
|
|
Returns the user ID (owner) of a file
|
3
|
|
Returns the permissions of a file
|
3
|
|
Returns the file size
|
3
|
|
Returns the file type
|
3
|
|
Locks or releases a file
|
3
|
|
Matches a filename or string against a specified pattern
|
4
|
|
Opens a file or URL
|
3
|
|
Reads from an open file, until EOF, and writes the result to the
output buffer
|
3
|
|
Formats a line as CSV and writes it to an open file
|
5
|
|
Alias of fwrite()
|
3
|
|
Reads from an open file
|
3
|
|
Parses input from an open file according to a specified format
|
4
|
|
Seeks in an open file
|
3
|
|
Returns information about an open file
|
4
|
|
Returns the current position in an open file
|
3
|
|
Truncates an open file to a specified length
|
4
|
|
Writes to an open file
|
3
|
|
Returns an array of filenames / directories matching a specified
pattern
|
4
|
|
Checks whether a file is a directory
|
3
|
|
Checks whether a file is executable
|
3
|
|
Checks whether a file is a regular file
|
3
|
|
Checks whether a file is a link
|
3
|
|
Checks whether a file is readable
|
3
|
|
Checks whether a file was uploaded via HTTP POST
|
3
|
|
Checks whether a file is writeable
|
4
|
|
Alias of is_writable()
|
3
|
|
Creates a hard link
|
3
|
|
Returns information about a hard link
|
3
|
|
Returns information about a file or symbolic link
|
3
|
|
Creates a directory
|
3
|
|
Moves an uploaded file to a new location
|
4
|
|
Parses a configuration file
|
4
|
|
Returns information about a file path
|
4
|
|
Closes a pipe opened by popen()
|
3
|
|
Opens a pipe
|
3
|
|
Reads a file and writes it to the output buffer
|
3
|
|
Returns the target of a symbolic link
|
3
|
|
Returns the absolute pathname
|
4
|
|
Renames a file or directory
|
3
|
|
Rewinds a file pointer
|
3
|
|
Removes an empty directory
|
3
|
|
Sets the buffer size of an open file
|
3
|
|
Returns information about a file
|
3
|
|
Creates a symbolic link
|
3
|
|
Creates a unique temporary file
|
3
|
|
Creates a unique temporary file
|
3
|
|
Sets access and modification time of a file
|
3
|
|
Changes file permissions for files
|
3
|
|
Deletes a file
|
3
|
PHP Filesystem Constants
PHP:
indicates the earliest version of PHP that supports the constant.
Constant
|
Description
|
PHP
|
GLOB_BRACE
|
||
GLOB_ONLYDIR
|
||
GLOB_MARK
|
||
GLOB_NOSORT
|
||
GLOB_NOCHECK
|
||
GLOB_NOESCAPE
|
||
PATHINFO_DIRNAME
|
||
PATHINFO_BASENAME
|
||
PATHINFO_EXTENSION
|
||
FILE_USE_INCLUDE_PATH
|
||
FILE_APPEND
|
||
FILE_IGNORE_NEW_LINES
|
||
FILE_SKIP_EMPTY_LINES
|
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/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";
}
?>
|
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/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"
PHP Cookies
A cookie is often used to identify
a user.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small
file that the server embeds on the user's computer. Each time the same computer
requests a page with a browser, it will send the cookie too. With PHP, you can
both create and retrieve cookie values.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note:
The setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
|
Example
In the example below, we will create a cookie named
"user" and assign the value "Alex Porter" to it. We also
specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
<body>
</body>
</html>
|
Note: The
value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie()
instead).
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "user" and display it on a page:
In the example below, we retrieve the value of the cookie named "user" and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>
|
In the following example we use the isset() function to find out
if a cookie has been set:
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
|
How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date
is in the past.
Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
|
What if a Browser Does NOT Support Cookies?
If your application deals with browsers that do not support
cookies, you will have to use other methods to pass information from one page
to another in your application. One method is to pass the data through forms
(forms and user input are described earlier in this tutorial).
The form below passes the user input to "welcome.php"
when the user clicks on the "Submit" button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
|
Retrieve the values in the "welcome.php" file like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
|
PHP Sessions
A PHP session variable is used to
store information about, or change settings for a user session. Session
variables hold information about one single user, and are available to all
pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some
changes and then you close it. This is much like a Session. The computer knows
who you are. It knows when you start the application and when you end. But on
the internet there is one problem: the web server does not know who you are and
what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user
information on the server for later use (i.e. username, shopping items, etc).
However, session information is temporary and will be deleted after the user
has left the website. If you need a permanent storage you may want to store the
data in a database.
Sessions work by creating a unique id (UID) for each visitor and
store variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you
must first start up the session.
Note:
The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>
<html>
<body>
</body>
</html>
|
The code above will register the user's session with the server,
allow you to start saving user information, and assign a UID for that user's
session.
Storing a Session Variable
The correct way to store and retrieve session variables is to use
the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
|
Output:
Pageviews=1
|
In the example below, we create a simple page-views counter. The
isset() function checks if the "views" variable has already been set.
If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and
set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
|
Destroying a Session
If you wish to delete some session data, you can use the unset()
or the session_destroy() function.
The unset() function is used to free the specified session
variable:
<?php
unset($_SESSION['views']);
?>
|
You can also completely destroy the session by calling the
session_destroy() function:
<?php
session_destroy();
?>
|
Note:
session_destroy() will reset your session and you will lose all your stored
session data.
PHP Sending E-mails
PHP allows you to send e-mails
directly from a script.
The PHP mail() Function
The PHP mail() function is used to send emails from inside a
script.
Syntax
mail(to,subject,message,headers,parameters)
|
Parameter
|
Description
|
to
|
Required. Specifies the receiver / receivers of the email
|
subject
|
Required. Specifies the subject of the email. Note: 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
|
Note:
For the mail functions to be available, PHP requires an installed and working
email system. The program to be used is defined by the configuration settings
in the php.ini file. Read more in our PHP
Mail reference.
PHP Simple E-Mail
The simplest way to send an email with PHP is to send a text
email.
In the example below we first declare the variables ($to,
$subject, $message, $from, $headers), then we use the variables in the mail()
function to send an e-mail:
<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
|
PHP Mail Form
With PHP, you can create a feedback-form on your website. The
example below sends a text message to a specified e-mail address:
<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>
|
This is how the example above works:
- First, check if the email input field is filled out
- If it is not set (like when the page is first visited); output the HTML form
- If it is set (after the form is filled out); send the email from the form
- When submit is pressed after the form is filled out, the page reloads, sees that the email input is set, and sends the email
PHP Mail Reference
For more information about the PHP mail() function, visit our PHP
Mail Reference.
PHP Secure E-mails
There is a weakness in the PHP
e-mail script in the previous chapter.
PHP E-mail Injections
First, look at the PHP code from the previous chapter:
<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>
|
The problem with the code above is that unauthorized users can
insert data into the mail headers via the input form.
What happens if the user adds the following text to the email
input field in the form?
someone@example.com%0ACc:person2@example.com
%0ABcc:person3@example.com,person3@example.com,
anotherperson4@example.com,person5@example.com
%0ABTo:person6@example.com
|
The mail() function puts the text above into the mail headers as
usual, and now the header has an extra Cc:, Bcc:, and To: field. When the user
clicks the submit button, the e-mail will be sent to all of the addresses
above!
PHP Stopping E-mail Injections
The best way to stop e-mail injections is to validate the input.
The code below is the same as in the previous chapter, but now we
have added an input validator that checks the email field in the form:
<html>
<body>
<?php
function spamcheck($field)
{
//eregi() performs a case insensitive regular expression match
if(eregi("to:",$field) || eregi("cc:",$field))
{
return TRUE;
}
else
{
return FALSE;
}
}
//if "email" is filled out, send email
if (isset($_REQUEST['email']))
{
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==TRUE)
{
echo "Invalid input";
}
else
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>
|
NIcee
ReplyDelete