|Language:||English, Spanish, Portuguese|
|ePub File Size:||22.73 MB|
|PDF File Size:||8.49 MB|
|Distribution:||Free* [*Regsitration Required]|
There are no restrictions on allowed values, and the browser will automatically detect the correct file extension and add it to the file .img,.pdf,.txt,.html, etc.). How to use the element to embed a Flash file: to embed multimedia ( like audio, video, Java applets, ActiveX, PDF, and Flash) in your web pages. One could probably use utilities like: Convert any URL or web page to PDF online Save as PDF.
The second form specifies both the column names and the values to be inserted: Example The following example demonstrates a loop that will print the values of the given array: 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: Unknown Validating filters: My name is Hege Refsnes. Example In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age".
After a call to this function the file pointer moves to the next character. The example below reads a file character by character, until the end of file is reached: 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: Notice the following about the HTML form above: 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. Like this: 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. 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: The script above checks if the file already exists, if it does not, it copies the file to the specified folder. This example saves the file to a new folder called "upload". 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. Syntax setcookie name, value, expire, path, domain ;. 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: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received to prevent URLencoding, use setrawcookie instead.
Example 2. You can also set the expiration time of the cookie in another way. It may be easier than using seconds. How 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 following example we use the isset function to find out if a cookie has been set: How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the past. Delete example: 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. Retrieve the values in the "welcome.
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: A PHP session solves this problem by allowing you to store user information on the server for later use i.
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. Before you can store user information in your PHP session, you must first start up the session. 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. 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: The unset function is used to free the specified session variable: Description Required.
Specifies the subject of the email. This parameter cannot contain any newline characters Required. Defines the message to be sent. Lines should not exceed 70 characters Optional. Specifies additional headers, like From, Cc, and Bcc. Specifies an additional parameter to the sendmail program. 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.
Read more in our PHP Mail reference. This is a simple email message. The example below sends a text message to a specified e-mail address: 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 Note: This is the simplest way to send e-mail, but it is not secure.
In the next chapter of this tutorial you can read more about vulnerabilities in e-mail scripts, and how to validate user input to make it more secure. Page 47 of 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? The mail function puts the text above into the mail headers as usual, and now the header has an extra Cc: When the user clicks the submit button, the e-mail will be sent to all of the addresses above!
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: In the code above we use PHP filters to validate input: An error message with filename, line number and a message describing the error is sent to the browser.
Page 50 of If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. This tutorial contains some of the most common error checking methods in PHP. We will show different error handling methods: Simple "die " statements Custom errors and error triggers Error reporting. Basic Error Handling: Using the die function The first example shows a simple script that opens a text file: If the file does not exist you might get an error like this: To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it: 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.
However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors.
Creating a Custom Error Handler Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.
This function must be able to handle a minimum of two parameters error level and error message but can accept up to five parameters optionally: Specifies the error report level for the user-defined error.
Must be a value number. See table below for possible error report levels. Specifies the filename in which the error occurred Optional. Specifies the line number in which the error occurred. Specifies an array containing every variable, and their values, in use when the error occurred. Error Report levels These error report levels are the different types of error the user-defined error handler can be used for: Page 52 of Description Non-fatal run-time errors. 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. Now that we have created an error handling function we need to decide when it should be triggered.
Page 53 of We are going to make the function above the default error handler for the duration of the script. It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways.
However, in this example we are going to use our custom error handler for all errors: Example Testing the error handler by trying to output variable that does not exist: The output of the code above should be something like this: Trigger an Error In a script where users can input data it is useful to trigger errors when an illegal input occurs. In this example an error occurs if the "test" variable is bigger than "1": Value must be 1 or below in C: An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.
Possible error types: Errors that can not be recovered from. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally. Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.
Sending errors messages to yourself by e-mail can be 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: And the mail received from the code above looks like this: This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system.
PHP Exception Handling Exceptions are used to change the normal flow of a script if a specified error occurs.
Exception handling is used to change the normal flow of the code execution if a specified error exceptional condition occurs. This condition is called an exception. This is what normally happens when an exception is triggered: 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 We will show different error handling methods: Basic use of Exceptions Creating a custom exception handler Multiple exceptions Page 57 of 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.
Basic Use of Exceptions When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. Lets try to throw an exception without catching it: The code above will get an error like this: Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C: Try, throw and catch To avoid the error from the example above, we need to create the proper code to handle an exception.
Page 58 of Proper exception code should include: Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown" 2.
Throw - This is how you trigger an exception. Each "throw" must have at least one "catch" 3. Catch - A "catch" block retrieves an exception and creates an object containing the exception information Lets try to trigger an exception with valid code: Example explained: The code above throws an exception and catches it: The checkNum function is created. It checks if a number is greater than 1.
If it is, an exception is thrown Page 59 of The checkNum function is called in a "try" block 3. The exception within the checkNum function is thrown 4. Creating a Custom Exception Class Creating a custom exception handler is quite simple. 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: 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: 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 2. The errorMessage function is created. This function returns an error message if an e-mail address is invalid 3.
The "try" block is executed and an exception is thrown since the email address is invalid 5. The "catch" block catches the exception and displays the error message. Multiple Exceptions It is possible for a script to use multiple exceptions to check for multiple conditions.
It is possible to use several if.. These exceptions can use different exception classes and return different error messages: The code above tests two conditions and throws an exception if any of the conditions are not met: The "try" block is executed and an exception is not thrown on the first condition 5. The second condition triggers an exception since the e-mail contains the string "example" Page 62 of 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.
Re-throwing Exceptions Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block.
A script should hide system errors from users. System errors may be important for the coder, but is of no interest to the user. To make things easier for the user you can re-throw the exception with a user friendly message: The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown: The "try" block contains another "try" block to make it possible to rethrow the exception 5.
The exception is triggered since the e-mail contains the string "example" 6. The "catch" block catches the exception and re-throws a "customException" 7. The "customException" is caught and displays an error message If the exception is not caught in its current "try" block, it will search for a catch block on "higher levels". Uncaught Exception occurred. In the code above there was no "catch" block. Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions.
Code may be surrounded in a try block, to help catch potential exceptions Each try block or "throw" 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 in a catch block within a try block. What is a PHP Filter? A PHP filter is used to validate and filter data coming from insecure sources. To test, validate and filter user input or custom data is an important part of any web application.
The PHP filter extension is designed to make data filtering easier and quicker. Why use a Filter? Almost all web applications depend on external input. Usually this comes from a user or another application like a web service. By using filters you can be sure your application gets the correct input type.
Page 65 of You should always filter all external data! Input filtering is one of the most important application security issues. What is external data? Input data from a form Cookies Web services data Server variables Database query results. Functions and Filters To filter a variable, use one of the following filter functions: Since the integer is valid, the output of the code above will be: If we try with a variable that is not an integer like "abc" , the output will be: Page 66 of Validating and Sanitizing There are two kinds of filters: Validating filters: Are used to allow or disallow specified characters in a string No data format rules Always return the string.
Options and Flags Options and flags are used to add additional filtering options to the specified filters. Different filters have different options and flags. Like the code above, options must be put in an associative array with the name "options". If a flag is used it does not need to be in an array. Since the integer is "" it is not in the specified range, and the output of the code above will be: Check each filter to see what options and flags are available.
Validate Input Let's try validating input from a form. The first thing we need to do is to confirm that the input data we are looking for exists. In the example below, the input variable "email" is sent to the PHP page: Check if an "email" input variable of the "GET" type exist 2. If the input variable exists, check if it is a valid e-mail address. Let's try cleaning up an URL sent from a form. First we confirm that the input data we are looking for exists.
In the example below, the input variable "url" is sent to the PHP page: Check if the "url" input of the "POST" type exists 2. Filter Multiple Inputs A form almost always consist of more than one input field. The received GET variables is a name, an age and an e-mail address: Example Explained The example above has three inputs name, age and email sent to it using the "GET" method: Set an array containing the name of input variables and the filters used on the specified input variables 2.
Page 70 of If the parameter is a single filter ID all values in the input array are filtered by the specified filter. If the parameter is an array it must follow these rules: Must be an associative array containing an input variable as an array key like the "age" input variable The array value must be a filter ID or an array specifying the filter, flags and options. This way, we have full control of the data filtering.
You can create your own user defined function or use an existing PHP function The function you wish to use to filter is specified the same way as an option is specified. What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collections of related data entries and it consists of columns and rows. Databases are useful when storing information categorically.
A company may have a database with the following tables: Database Tables A database most often contains one or more tables.
Each table is identified by a name e. Tables contain records rows with data. Below is an example of a table called "Persons": With MySQL, we can query a database for specific information and have a recordset returned. Look at the following query: The query above selects all the data in the "LastName" column from the "Persons" table, and will return a recordset like this: LastName Hansen Svendson Pettersen.
Perhaps it is because of this reputation that many people believe that MySQL can only handle small to medium-sized systems. The truth is that MySQL is the de-facto standard database for web sites that support huge volumes of both data and end users like Friendster, Yahoo, Google.
Look at http: Page 73 of Parameter Description servername Optional. Specifies the server to connect to. Default value is "localhost: Specifies the username to log in with.
Default value is the name of the user that owns the server process Optional. Specifies the password to log in with.
Default is "". There are more available parameters, but the ones listed above are the most important. The "die" part will be executed if the connection fails: Closing a Connection The connection will be closed automatically when the script ends. This function is used to send a query or command to a MySQL connection.
Page 75 of The following example creates a table named "Persons", with three columns.
Page 76 of A database must be selected before a table can be created. When you create a database field of type varchar, you must specify the maximum length of the field, e. The data type specifies what type of data the column can hold. A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique within the table. Furthermore, the primary key.
The following example sets the personID field as the primary key field. The first form doesn't specify the column names where the data will be inserted, only their values: The second form specifies both the column names and the values to be inserted: In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table: Here is the HTML form: When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.
The "insert. Here is the "insert. The while loop loops through all the records in the recordset. Page 81 of If you want to sort the records in a descending order, you can use the DESC keyword. The following example selects all the data stored in the "Persons" table, and sorts the result by the "Age" column: Order by Two Columns It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are equal: Earlier in the tutorial we created a table named "Persons".
Here is how it looks: The following example updates some data in the "Persons" table: After the update, the "Persons" table will look like this: Look at the following "Persons" table: After the deletion, the table will look like this: Open the Administrative Tools icon in your Control Panel.
Choose the System DSN tab.
Select the Microsoft Access Driver. Click Finish. In the next screen, click Select to locate the database. Click OK. Note that this configuration has to be done on the computer where your web site is located. If you are running Internet Information Server IIS on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to to set up a DSN for you to use.
The function takes four parameters: The following example creates a connection to a DSN called northwind, with no username and no password. It then creates an SQL and executes it: This function returns true if it is able to return rows, otherwise false. The function takes two parameters: This function takes two parameters: The code line below returns the value of the first field from the record: The code line below returns the value of a field called "CompanyName": What is XML?
XML is used to describe data and to focus on what data is. An XML file describes the structure of the data. In XML, no tags are predefined. You must define your own tags. What is Expat? There are two basic types of XML parsers:. Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements. Views an XML document as a series of events.
When a specific event occurs, it calls a function to handle it Page 91 of The Expat parser is an event-based parser. Event-based parsers focus on the content of the XML documents, not their structure. Because of this, event-based parsers can access data faster than tree-based parsers. Look at the following XML fraction: However, this makes no difference when using the Expat parser. Expat is a non-validating parser, and ignores any DTDs.
XML documents must be well-formed or Expat will generate an error. There is no installation needed to use these functions. Tove From: Jani Heading: Reminder Message: Don't forget me this weekend! How it works: Create functions to use with the different event handlers 3. Parse the file "test. What is DOM? It analyzes the whole document, and provides access to the tree elements Event-based parser: When a specific event occurs, it calls a function to handle it.
The DOM parser is an tree-based parser. Look at the following XML document fraction: Level 1: XML Document Level 2: Root element: Text element: Tove Jani Reminder Don't forget me this weekend! In the example above you see that there are empty text nodes between each element. When XML generates, it often contains white-spaces between the nodes. The XML DOM parser treats these as ordinary elements, and if you are not aware of them, they sometimes cause problems. Page 97 of What is SimpleXML? It is an easy way of getting an element's attributes and text, if you know the XML document's layout.
When there's more than one element on one level, they're placed inside an array Attributes - Are accessed using associative arrays, where an index corresponds to the attribute name Element Data - Text data from elements are converted to strings.
If an element has more than one text node, they will be arranged in the order they are found SimpleXML is fast and easy to use when performing basic tasks like: Installation As of PHP 5. We want to output the element names and data from the XML file above. Here's what to do: Load the XML file 2. Get the name of the first element 3. Create a loop that will trigger on each child node, using the children function 4. Reminder body: AJAX is not a new programming language, but simply a new technique for creating better, faster, and more interactive web applications.
The AJAX technique makes web pages more responsive by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change.
AJAX applications are browser and platform independent. Cross-Platform, Cross-Browser technology. Web applications have many benefits over desktop applications: AJAX is based on open standards. These standards have been used by most developers for several years.
After the web server has processed the data, it will return a completely new web page to the user. Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly.
AJAX is a technology that runs in your browser. It uses asynchronous data transfer HTTP requests between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. AJAX is a web browser technology independent of web server software. It has been available ever since Internet Explorer 5. Internet Explorer uses an ActiveXObject. Here is the simplest code you can use to overcome this problem: Example above explained: Set the value to null.
Then test if the object window. XMLHttpRequest is available. This object is available in newer versions of Firefox, Mozilla, Opera, and Safari. If it's available, use it to create a new object: If it's not available, test if an object window.
ActiveXObject is available. This object is available in Internet Explorer version 5. If it is available, use it to create a new object: A Better Example? The example below tries to load Microsoft's latest version "Msxml2. Try to create the object according to web standards Mozilla, Opera and Safari: Try to create the object the Microsoft way, available in Internet Explorer 6 and later: If this catches an error, try the older Internet Explorer 5.
This example consists of three pages: The form works like this: An event is triggered when the user presses, and releases a key in the input field 2. When the event is triggered, a function called showHint is executed.
This is used as a placeholder for the return data of the showHint function. This function executes every time a character is entered in the input field. If there is some input in the text field str. Defines the url filename to send to the server 2. Adds a parameter q to the url with the content of the input field 3.
Adds a random number to prevent the server from using a cached file 4. Sends an HTTP request to the server If the input field is empty, the function simply clears the content of the txtHint placeholder. When the state changes to 4 or to "complete" , the content of the txtHint placeholder is filled with the response text.
If more than one name is found, include all names in the response string 3. W3schools offline Version. Gassen BenHadj. Wish list. See System Requirements. Available on PC Mobile device Hub. Description W3Schools is optimized for learning, testing, and training. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content Show More.
People also like. Zip Opener Rated 4 out of 5 stars. Rar Zip Extractor Pro Rated 4 out of 5 stars. WinZip Universal Rated 3 out of 5 stars.
FortiClient Rated 3 out of 5 stars. Microsoft To-Do: QR Scanner Plus Rated 3 out of 5 stars. VLC Rated 4 out of 5 stars. What's new in this version offline version of W3Schools. Additional information Published by Gassen BenHadj. Published by Gassen BenHadj. Copyright W3Schools. Developed by Gassen BenHadj. Approximate size Age rating For ages 3 and up. This app can Access your Internet connection. Permissions info. Installation Get this app while signed in to your Microsoft account and install on up to ten Windows 10 devices.
Accessibility The product developer believes this product meets accessibility requirements, making it easier for everyone to use. Language supported English United States. Additional terms Terms of transaction. Seizure warnings Photosensitive seizure warning. Report this product Report this app to Microsoft Thanks for reporting your concern.
Our team will review it and, if necessary, take action.