PHP Include File
Server Side Includes (SSI) are used to create functions, headers, footers, or elements that will be reused on multiple pages.
Server Side Includes
You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages.
This can save the developer a considerable amount of time. This means that you can create a standard header or menu file that you want all your web pages to include. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all web pages).
The include() Function
The include() function takes all the text in a specified file and copies it into the file that uses the include function.Example 1
Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this:<html> <body> <?php include("header.php"); ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> |
Example 2
Now, let's assume we have a standard menu file that should be used on all pages (include files usually have a ".php" extension). Look at the "menu.php" file below:<html> <body> <a href="http://www.w3schools.com/default.php">Home</a> | <a href="http://www.w3schools.com/about.php">About Us</a> | <a href="http://www.w3schools.com/contact.php">Contact Us</a> |
<?php include("menu.php"); ?> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> |
<html> <body> <a href="default.php">Home</a> | <a href="about.php">About Us</a> | <a href="contact.php">Contact Us</a> <h1>Welcome to my home page</h1> <p>Some text</p> </body> </html> |
The require() Function
The require() function is identical to include(), except that it handles errors differently.The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).
If you include a file with the include() function and an error occurs, you might get an error message like the one below.
PHP code:
<html> <body>
<?php include("wrongFile.php"); echo "Hello World!"; ?>
</body> </html> |
Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5 Hello World! |
PHP code:
<html> <body>
<?php require("wrongFile.php"); echo "Hello World!"; ?>
</body> </html> |
Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Fatal error: require() [function.require]: Failed opening required 'wrongFile.php' (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5 |
It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
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> |
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 |
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> |
- 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
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"]; } ?> |
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
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"; } ?> |
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"; } ?> |
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 1
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> ..... |
Example 2
You can also set the expiration time of the cookie in another way. It may be easier than using seconds.<?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> <html> ..... |
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:
<?php
// Print a cookie
echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?> |
<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> |
<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> |
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> |
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']); ?> |
<?php session_destroy(); ?> |
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 |
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
No comments:
Post a Comment