Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008
0
You can use multiple exceptions to check for multiple conditions in your script.
You can use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = ‘Error on line ‘.$this->getLine().’ in ‘.$this->getFile()
.’: <b>’.$this->getMessage().’</b> is not a valid E-Mail address’;
return $errorMsg;
}
}
$email = “someone@example.com”;
try
{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
//check for “example” in mail address
if(strpos($email, “example”) !== FALSE)
{
throw new Exception(”$email is an example e-mail”);
}
}
catch (customException $e)
{
echo $e->errorMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
The code above tests two conditions and throws an exception if any of the conditions are not met. It works as:
- The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
- The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
- The $email variable is set to a string that is a valid e-mail address, but contains the string “example”
- The “try” block is executed and an exception is not thrown on the first condition
- The second condition triggers an exception since the e-mail contains the string “example”
- The “catch” block catches the exception and displays the correct error message
If there was no customException catch, only the base exception catch, the exception would be handled there
Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008
0
You can also create a custom exception handler of your own which will handle the exceptions your way. We simply create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class.
The custom exception class inherits the properties from PHP’s exception class and you can add custom functions to it.
Lets create an exception class:
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = ‘Error on line ‘.$this->getLine().’ in ‘.$this->getFile()
.’: <b>’.$this->getMessage().’</b> is not a valid E-Mail address’;
return $errorMsg;
}
}
$email = “someone@example…com”;
try
{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{ //throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e)
{ //display custom message
echo $e->errorMessage();
}
?>
The new class is a copy of the old exception class with an addition of the errorMessage() function. Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine() and getFile() and getMessage().
The code above throws an exception and catches it with a custom exception class. It works as:
- The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
- The errorMessage() function is created. This function returns an error message if an e-mail address is invalid.
- The $email variable is set to a string that is not a valid e-mail address
- The “try” block is executed and an exception is thrown since the e-mail address is invalid
- The “catch” block catches the exception and displays the error message
Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008
0
Exceptions can occur in your program and you need to handle them to have your code going on. But how would you know which code is going to produce an error.
PHP exception handling provides some easy steps to deal with the exceptions:
- track where an error is produced
- throw the error to some handler
- catch the appropriate error and continue with the execution
A proper exception code includes:
- Try – It encloses the block of code or the function which is doubted to produce an exception. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is thrown automatically.
- Throw – Throw lets you trigger an error manually.
- Catch – It contains the code to handle the exceptions. A “catch” block retrieves an exception and creates an object containing the exception information.
A simple try-catch example:
<?php
//create function with an exception
function checkNum($number)
{
if($number<1)
{
throw new Exception(”Number must be greater than 0″);
}
return true;
}
//trigger exception in a “try” block
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo ‘The number is greater than 0′;
}
//catch exception
catch(Exception $e)
{
echo ‘Message: ‘ .$e->getMessage();
}
?>
The code above throws an exception and catches it.It works as follows:
- The checkNum() function is created. It checks if a number is less than 1. If it is, an exception is thrown
- The checkNum() function is called in a “try” block
- The exception within the checkNum() function is thrown
- The “catch” block retrives the exception and creates an object ($e) containing the exception information
- The error message from the exception is echoed by calling $e->getMessage() from the exception object
Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008
0
Exceptions are special conditions which occur during execution and change the normal flow of a code.
These exceptions need to be handled to let the program going on.
PHP 5 provides an object oriented way of dealing with errors.
During the execution of a program some condition may appear when the program flow is need to be changed to protect the code from crashing or producing wrong results or stopping in the middle of execution. This is called Exception handling. And exceptions are the condtions which may cause any of the above situations.
When an exception occurs the following steps are executed:
- The current code state is saved
- The code execution will switch to a predefined (custom) exception handler function
- Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code
Basic Idea for an Exception to handle is:
- decide whether the Error produced needs to be handled and how
- which exception to handle at which level and which point of tim
- your code should keep running even if a severe (non-fatal) error occurs
- make sure all errors of all the different types are handled uniformly.
Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.
When an exception is thrown, the execution of the following code block is stopped, and PHP will try to find the code for catching the exception.
If an exception is not caught, a fatal error will be issued with an “Uncaught Exception” message.
PHP 5 handles exceptions in a similar way to that of other programming languages.
Exception handling introduces some new keywords as:
- Try - It encloses the block of code or the function which is doubted to produce an exception. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is thrown automatically.
- Throw – Throw lets you trigger an error manually.
- Catch – It contains the code to handle the exceptions. A “catch” block retrieves an exception and creates an object containing the exception information.
When an exception is thrown, the program execution will be paused to handle the error. PHP will then attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception”
- Each try must have at least one corresponding catch block.
- Multiple catch blocks can be used to catch different classes of exceptions.
- Exceptions can be thrown (or re-thrown) within a catch block also.
Lets try to throw an exception without catching it:
<?php //create function with an exception
function checkNum($number)
{
if($number==0)
{
throw new Exception(”Value must not be 0″);
}
return true;
}
//trigger exception
checkNum(0);
?>
Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008
0
PHP sends an error log to the servers logging system or a file, depending on the error_log configuration in the php.ini file. But this can be changed using the error_log() function, ie you caqn send error logs to a file or a remote destination, specified by you.
You can also send error messages to yourself by e-mail. This is a good way of getting notified of specific errors.
Send an Error Message by E-Mail
In the example below we will send an e-mail with an error message and end the script, if a specific error occurs:
<?php //error handler function
function customError($errorNo, $errorStr)
{
echo “<b>Error:</b> [$errorNo] $errorStr<br />”;
echo “Webmaster has been notified”;
error_log(”Error: [$errorNo] $errstr”,1,
“user1@example.com”,”From: tutor@goweb99.com”);
}
//set error handler
set_error_handler(”customError”,E_USER_WARNING);
//trigger error
$test=2;
if ($test>1)
{
trigger_error(”Value must be 1 or below”,E_USER_WARNING);
}
?>
And the mail received from the code above looks like this:
Error: [512] Value must be 1 or below
Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008
0
Creating a Custom Error Handler
A Custom Error Handler is a special function which is called when an error occurs in PHP.
This function should accept at least two parameters, ie error level and error message and at the max it may accept up to five parameters ie file, line-number, and the error context:
Syntax
error_function(error_level,error_message,error_file,error_line,error_context)
|
Parameter |
Description |
|
error_level |
Required. Specifies the error report level for the user-defined error. Must be a value number. |
|
error_message |
Required. Specifies the error message for the user-defined error |
|
error_file |
Optional. Specifies the filename in which the error occurred |
|
error_line |
Optional. Specifies the line number in which the error occurred |
|
error_context |
Optional. Specifies an array containing every variable, and their values, in use when the error occurred |
These error report levels are the different types of error the user-defined error handler can be used for:
Error Report levels
|
Value |
Constant |
Description |
|
2 |
E_WARNING |
Non-fatal run-time errors. Execution of the script is not halted |
|
8 |
E_NOTICE |
Run-time notices. The script found something that might be an error, but could also happen when running a script normally |
|
256 |
E_USER_ERROR |
Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() |
|
512 |
E_USER_WARNING |
Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() |
|
1024 |
E_USER_NOTICE |
User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() |
|
4096 |
E_RECOVERABLE_ERROR |
Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) |
|
8191 |
E_ALL |
All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0) |
Now lets create a function to handle errors:
function customError($errno, $errstr)
{
echo “<b>Error:</b> [$errno] $errstr<br />”;
echo “Ending Script”;
die();
}
The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.
Here we have created an error handling function, so mow we we need to decide when it should be triggered.
Set Error Handler
PHP provides a built in default error handler error handler.
You can also change the error handler to apply for only some errors, so this way you can make more handlers for different type of errors, which will handle the errors in specific ways.
set_error_handler(”customError”);
Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.
Testing the error handler by trying to output variable that does not exist:
For eg:
<?php //error handler function
function customError($errno, $errstr)
{
echo “<b>Error:</b> [$errno] $errstr”;
}
//set error handler
set_error_handler(”customError”);
//trigger error
echo($test);
?>
Trigger an Error
In the above example we triggered the error without any reason. We need some valid trigger for the error handler to be triggered. When a user inputs data, some wrong input may be provided so we need to trigger the handler whenever a user inputs a invalid data. In PHP, this is done by the trigger_error() function.
In this example an error occurs if the “test” variable is bigger than “1″:
By this method you can trigger an error anywhere you wish in a script. By adding a second parameter, you can specify what error level is triggered.
Possible error types:
- E_USER_ERROR – Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
- E_USER_WARNING – Non-fatal user-generated run-time warning. Execution of the script is not halted
- E_USER_NOTICE – Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally
In this example an E_USER_WARNING occurs if the “test” variable is bigger than “1″. If an E_USER_WARNING occurs we will use our custom error handler and end the script:
For eg:
<?php //error handler function
function customError($errno, $errstr)
{
echo “<b>Error:</b> [$errno] $errstr<br />”;
echo “Ending Script”;
die();
}
//set error handler
set_error_handler(”customError”,E_USER_WARNING);
//trigger error
$test=2;
if ($test>1)
{
trigger_error(”Value must be 1 or below”,E_USER_WARNING);
}
?>
Posted by tutor | Posted in PHP Tutorial | Posted on 16-12-2009-05-2008
0
PHP provides a default error handling, which is very simple. An error message is sent to the browser, with filename, line number and a message describing the error.
Error handling is a vital part while working with scripts and creating web applications.
Error checking and handling helps you handle the errors your way, ie you can do what you want to do in case an error occurs. It makes your code look more professional and also provides security.
This tutorial contains some of the most common error checking methods in PHP.
Some of the most common error checking methods of PHP are:
- Simple “die()” statements
- Custom errors and error triggers
- Error reporting
Using the die() function
The first example shows a simple script that opens a text file:
<?php
$file=fopen(”welcome.txt”,”r”);
?>
You can avoid this situation by simple methods. First look for the file if it exists, then open it and if not then you can use the die() function.
<?php
if(!file_exists(”welcome.txt”))
{
die(”File not found”);
}
else
{
$file=fopen(”welcome.txt”,”r”);
}
?>
The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
Posted by tutor | Posted in PHP Tutorial | Posted on 16-12-2009-05-2008
0
First, look at the PHP code from the previous chapter:
<html>
<body>
<?php
if (isset($_REQUEST['email'])) //if “email” is filled out, 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.
Now suppose a if a 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 such e-mail injections is to validate the input.
In the code below we have added an input validator that checks the email field in the form:
<html>
<body>
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email'])) //if “email” is filled out, proceed
{
$mailcheck = spamcheck($_REQUEST['email']); //check if the email address is invalid
if ($mailcheck==FALSE)
{
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>
These are the PHP filters that we used in the above code to validate input:
The FILTER_SANITIZE_EMAIL- removes all illegal e-mail characters from a string
The FILTER_VALIDATE_EMAIL- validates value as an e-mail address
Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008
0
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 |
But before you will be able to use mail functions, you should have a working email system. The program to be used is defined by the configuration settings in the php.ini file.
PHP Simple E-Mail
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:
$to = "user1@example.com";
$subject = "Sample mail";
$message = "This is a test email message.";
$from = "user2@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008
0
PHP isset() Function
When we create a variable and store it in a session, it is with the intention to use it in the future. But to use a session variable it should first be created and set. So you must first check for its existence.
Here we use PHP’s isset function. isset is a function that takes any variable you want to use and checks to see whether it has been assigned some value or not.
Destroying a Session
If you wish to delete some session data, you can use the following two functions:
- unset() function
- session_destroy() function
The unset() function is used to free the specified session variable:
You can also completely destroy the session by calling the session_destroy() function:
session_destroy() will reset your session and you will lose all your stored session data.
Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008
0
Whenever a user logs in to a system some variables are set to identify this same user throughout his working duration and when the user logs out of the system the variables are reset. This duration from log=in to log-out is called a session and the variables used are session variables to identify a session.
Starting a PHP Session
Before storing the user information in a session, it should be first started. The code to start a session must be at the very beginning of your code, before any HTML or text is sent.
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
When you want to store user data in a session use the built-in PHP associative array $_SESSION. This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.
<?php
session_start();
// store session data
$_SESSION['username']=”Tutor”;
?>
<html>
<body>
<?php
//retrieve session data
echo “Username=”. $_SESSION['username'];
?>
</body>
</html>
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'];
?>
Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008
0
A PHP session allows you to store user information like username, shopping cart items, etc or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
However, this session information is temporary and is deleted very quickly after the user has left the website that uses sessions.
It is important to think and verify if the sessions’ temporary storage is applicable to your website. If you require a more permanent storage you will have to use a database.
Sessions too have some major loop holes which need some advanced techniques to fill into those gaps. So if you are not experienced with session programming it is not recommended that you use sessions on a website that requires high-security.
PHP Session Variables
Session is the duration for which you browse a website or you visit some page. That means, when you are working with an application, you open it, do some changes and then you close it. This is a Session. The time you login to an application or start it the computer recognizes you.
It knows when you start the application and when you end. This is the case with applications running on your system, but on the internet there is one problem: HTTP address doesn’t maintain state, so a web server cannot know who you are and what you do.
A PHP session is used to solve this problem. It allows you to store user information on the server for later use. However, session information is temporary and is 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.
Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008
0
Retrieving Cookie
The built-in PHP variable $_COOKIE is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named “username” and display it on a page:
We can also use the isset() function to find out if a cookie has been set:
<html>
<body>
<?php
if (isset($_COOKIE["username"]))
echo “Welcome ” . $_COOKIE["username"] . “!<br />”;
else
echo “Welcome Tutor!<br />”;
?>
</body>
</html>
Deleting Cookie
When deleting a cookie, its should have been expired ie you should assure that the expiration date is in the past.
Browsers not supporting Cookies
If a browser do not support cookies, you will have to use other methods to pass information from one page to another in your application. You may use the form method to pass the information in such a case.
The form below passes the user input to “main.php” when the user clicks on the “Submit” button:
Retrieve the values in the “main.php” file like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You live at <?php echo $_POST["address"]; ?>.
</body>
</html>
Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008
0
A cookie is a small file that the server sends to the client browser, whenever a request is sent. A cookie is often used to identify a user.
The server embeds this cookie on the user’s computer to store some information about the user. Whenever the same computer requests a page, the server sends the cookie too.
Cookies were thought of as a bad thing at the starting, but now nearly all the sites, even the most trusted ones also use cookies. Moreover, today there are more things to worry about.
Creating Cookie
Cookie can be created using the setcookie() function. But remember, the setcookie() function must appear BEFORE the <html> tag.
Syntax
setcookie(name, value, expiration);
Setcookie() function takes three arguments as:
- name: The name of your cookie, which will be later on used to retrieve your cookie and the information contained in it.
- value: The value that is stored in your cookie, generally username(string) and last visit(date).
- expiration: The date when the cookie will expire and will be deleted. If this parameter is not set, then it will be treated as a session cookie and will be removed when the browser is restarted.
In the example below, we are creating a cookie named “username” and assign the value “Tutor” to it. We also specify that the cookie should expire after one hour:
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received. But to remove this encoding you can use setrawcookie() instead.
You can also set the expiration time of the cookie in another way. It may be easier than using seconds.
In the example above the expiration time is set to a month i.e. 60 sec * 60 min * 24 hours * 30 days.
Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008
0
Providing the facility to upload files is a very important and useful part of web. But every user is not much aware of the pitfalls of it and the consequences of what will happen if a file of large size is uploaded or a file of undesired format is uploaded. So the programmers need to keep a check on what type of file can be uploaded and what size.
We can imply restrictions on users through code like this. 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 format or size”;
}
?>
Note: IE recognizes jpg files as pjpeg, and FireFox recognizes it by jpeg.
Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008
0
While uploading files by above codes, a temporary copy of the uploaded files is created in the PHP temp folder on the server.
These temporarily copied files disappear, once the uploading is done or when the script ends. To store the uploaded file we need to copy it to some secure and defined location:
<?php
if ((($_FILES["file"]["type"] == “image/gif”)
&& ($_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 format or size”;
}
?>
The above script first checks for the availability of the file, if it does not exist, it copies the file to the specified folder.
Note: This script is for learnig purposes only.
Posted by tutor | Posted in PHP Tutorial | Posted on 14-12-2009-05-2008
0
PHP provides the facility to upload files to a server.
Create an Upload-File Form
To allow a user to upload files from a form can be very useful. For eg there are various sites where we can upload images and keep theem there, or sites where we can upload our resumes.
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 while submitting the form. The value “multipart/form-data” is used when a form requires binary data to be uploaded, like the contents of a file.
- 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
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 basic way of uploading files, which is very less secure. For security reasons, you should add restrictions on what the user is allowed to upload.
Posted by tutor | Posted in PHP Tutorial | Posted on 14-12-2009-05-2008
0
If there could be a need to create file then definitely you would also require to delete the files.
Now, when we delete a file we actually don’t wash out the space acquired by that file,
rather we make the system forget about the file.
In PHP you can delete files by calling the unlink function.
PHP – File Unlink
Operating System treats a filename as a link which joins a file to a directory.
When you try to see 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.
When you unlink a file, you cause the system to forget about it or delete it!
Before deleting a file you must close it by fclose() function.
Unlink() function takes only one argument, which is the name of the file to be deleted.
The sample.txt should now be removed. You must make sure that the file exists in the same
directory as the file which is used to delete it.
Although you need to delete files at times but you must take care while deleting files,
as you may delete some other important file also.
Posted by tutor | Posted in PHP Tutorial | Posted on 14-12-2009-05-2008
0
fread() Function
The fread function is used for getting data out of a file.
This function takes two parameters, again. The first parameter is a handle to the file you want to read and the second parameter is an integer to tell the function how much data, in bytes, it is supposed to read.
One character is of one byte. So, if you wanted to read the first five characters then you use five as the second argument.
For eg:
$sampleFile = "sample.txt";
$samplefile_handle = fopen($sampleFile, 'r');
$data = fread($samplefile_handle, 6);
fclose($samplefile_handle);
echo $data;
If you want to read the whole content from the file, then you will need the size of the file, which will give the idea how much content it has. To get the size of the file you can use the filesize function. This function returns the length of a file, in bytes. The filesize function takes only one argument ie the name of the file whose size we want to find.
The output is in one line because we did not entered a line break while writing the data into the file
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. For eg if we are searching for some string in the file.
You can read from a file only when it is opened in read 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.
The file pointer moves to the next line in the file after each call to this function. The fgets function searches for the first occurrence of “\n” the newline character. If you did not write newline characters to your file, then this function might not work the way you expect it to.
The example below reads a file line by line, until the end of file is reached:
For eg:
$file = fopen("sample.txt", "r") or exit("File opening failed!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "
“;
}
fclose($file);
?>
Reading a File Character by Character
The fgetc() function is used to read a single character from a file.
The file pointer moves to the next character in the file after each call to this function.
The example below reads a file character by character, until the end of file is reached:
For eg:
$file=fopen("sample.txt","r") or exit("File opening failed!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>