The real power of PHP comes from its functions.
In PHP, there are more than 700 built-in functions.
For a complete reference and examples of the built-in functions
in this chapter we will show you how to create your own functions.
To keep the browser from executing a script when the page loads, you can put your script into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
A function will be executed by a call to the function.
function functionName()
{
code to be executed;
}
PHP function guidelines:
A simple function that writes my name when it is called:
| <html> <body> <?php echo “My name is “; </body> |
Output:
My name is Kai Jim Refsnes
PHP Functions – Return valuesTo let a function return a value, use the return statement. Example<html> <?php echo “1 + 16 = ” . add(1,16); </body> Output:
|
This PHP filters is used to validate and filter data coming from insecure sources, like user input.
The filter functions are part of the PHP core. There is no installation needed to use these functions.
PHP: indicates the earliest version of PHP that supports the function.
| Function | Description | PHP version |
|---|---|---|
| filter_has_var() | Checks if a variable of a specified input type exist | 5 |
| filter_id() | Returns the ID number of a specified filter | 5 |
| filter_input() | Get input from outside the script and filter it | 5 |
| filter_input_array() | Get multiple inputs from outside the script and filters them |
5 |
| filter_list() | Returns an array of all supported filters | 5 |
| filter_var_array() | Get multiple variables and filter them | 5 |
| filter_var() | Get a variable and filter it | 5 |
| ID Name | Description |
|---|---|
| FILTER_CALLBACK | Call a user-defined function to filter data |
| FILTER_SANITIZE_STRING | Strip tags, optionally strip or encode special characters |
| FILTER_SANITIZE_STRIPPED | Alias of “string” filter |
| FILTER_SANITIZE_ENCODED | URL-encode string, optionally strip or encode special characters |
| FILTER_SANITIZE_SPECIAL_CHARS | HTML-escape ‘”<>& and characters with ASCII value less than 32 |
| FILTER_SANITIZE_EMAIL | Remove all characters, except letters, digits and !#$%&’*+-/=?^_`{|}~@.[] |
| FILTER_SANITIZE_URL | Remove all characters, except letters, digits and $-_.+!*’(),{}|\\^~[]`<>#%”;/?:@&= |
| FILTER_SANITIZE_NUMBER_INT | Remove all characters, except digits and +- |
| FILTER_SANITIZE_NUMBER_FLOAT | Remove all characters, except digits, +- and optionally .,eE |
| FILTER_SANITIZE_MAGIC_QUOTES | Apply addslashes() |
| FILTER_UNSAFE_RAW | Do nothing, optionally strip or encode special characters |
| FILTER_VALIDATE_INT | Validate value as integer, optionally from the specified range |
| FILTER_VALIDATE_BOOLEAN | Return TRUE for “1″, “true”, “on” and “yes”, FALSE for “0″, “false”, “off”, “no”, and “”, NULL otherwise |
| FILTER_VALIDATE_FLOAT | Validate value as float |
| FILTER_VALIDATE_REGEXP | Validate value against regexp, a Perl-compatible regular expression |
| FILTER_VALIDATE_URL | Validate value as URL, optionally with required components |
| FILTER_VALIDATE_EMAIL | Validate value as e-mail |
| FILTER_VALIDATE_IP | Validate value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges |
Server Side Includes
You can insert the content of a file into a PHP file before the server carry out 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)
The require() function generates a fatal error (and the script execution will stop after the error).
This can save the developer a substantial amount of time. This means that you can develop 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
The include() Function
The include() function get all the text in a particular file and copies it into the file that uses the include function.
Example
suppose that you have a standard header file, called “welcome.php”. To include the header file in a page, use the include() function, like this:
<html>
<body>
<?php include(“welcome.php”); ?>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
Example
Now, let’s suppose we have a standard menu file that should be used on all pages (include files usually have a “.php” extension). Look at the “any.php” file below:
<html>
<body>
<a href=”http://www.any.com/xxx.php”>hi</a> |
<a href=”http://www.any.com/zzz.php”>your Us</a> |
<a href=”http://www.any.com/yyy.php”>name Us</a>
The three files, “xxx.php”, “zzz.php”, and “yyy.php” should all include the “any.php” file. Here is the code in “xxx.php”:
<?php include(“any.php”); ?>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
If you look at the source code of the “xxx.php” in a browser, it will look something like this:
<html>
<body>
<a href=”xxx.php”>hi</a> |
<a href=”zzz.php”>your Us</a> |
<a href=”yyy.php”>name</a>
<h1>Welcome</h1>
<p>any text</p>
</body>
</html>
And, of course, we would have to do the same thing for “zzz.php” and “yyy.php”. By using include files, you simply have to update the text in the “any.php” file if you decide to rename or change the order of the links or add another web page to the site.
The require() Function
The require() function is indistinguishable to include(), except for that it handles errors differently.
The include() function produce 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(“phpguru.php.php”);
echo “Welcome!”;
?>
</body>
</html>
Error message:
Warning: include(phpguru.php) [function.include]:
failed to open stream:
No such file or directory in on line 5
Warning: include() [function.include]:
Failed opening ‘phpguru.php’ for inclusion
(include_path=’.;C:\php\ar’)
on line 5
Welcome!
Now, let’s run the same example with the require() function.
PHP code:
<html>
<body>
<?php
require(“phpguru.php “);
echo “Welcome!”;
?>
</body>
</html>
It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
Like many others, I wish to use technical PHP as a template language. While PHP’s syntax makes it a practical choice for this, there is a problem with embedding dynamic content. Most PHP applications produce HTML output, so you end up writing <?php echo htmlspecialchars($foo);?> a lot, using this technique. Or you forget it, and make your application horizontal to all sorts of mean XSS attacks.
Apart from the bother of superfluous typing, there is a danger of getting lazy, seeing that <?php echo $foo;?> is remarkably shorter to type. In some situations, it won’t manifest itself as a problem either, since some content-types never contains HTML special characters (Numbers for example). This is particularly nasty, because errors in the view layer are notoriously hard to track down, and unlike SQL-injections — a analogous problem — the consequences tend to hurt the users of a site, rather than the site directly.
PHP Functions
In this lesson we will show you how to create your own functions.For a situation and examples of the built-in functions, please visit our PHP Reference.
Create a PHP Function
A function is a block of code that can be executed whenever we need it.
(1) All functions start with the word “function()”
(2) Name the function – It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)
(3) Add a “{” – The function code starts after the opening curly brace
(4) Insert the function code
(5) Add a “}” – The function is finished by a closing curly brace
Example
A simple function that writes my name when it is called:
<html><body>
<?php
function writeMyName()
{
echo “chintan”;
}
writeMyName();
?>
</body></html>
Use a PHP Function
Now we will use the function in a PHP script:
<html><body>
<?php
function writeMyName()
{
echo “chintan”;
}
echo “Hello world!<br />”;
echo “My name is “;
writeMyName();
echo “.<br />That’s right, “;
writeMyName();
echo ” is my name.”;
?>
</body>
</html>
The output of the code above will be:
Hello world!
My name is chintan.
That’s right, chintan is my name.
PHP Functions – Adding parameters
Our first function (writeMyName()) is a very simple function. It only writes a static string.
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses.
Example 1
The following example will write different first names, but the same last name:
<html><body>
<?php
function writeMyName($fname)
{
echo $fname . ” Refsnes.<br />”;
}
echo “My name is “;
writeMyName(“chintan”);
echo “My name is “;
writeMyName(“Den”);
echo “My name is “;
writeMyName(“James”);
?>
</body></html>
The output of the code above will be:
My name is chintan Refsnes.
My name is Den Refsnes.
My name is James Refsnes.
Example 2
The following function has two parameters:
<html><body>
<?php
function writeMyName($fname,$punctuation)
{
echo $fname . ” Refsnes” . $punctuation . “<br />”;
}
echo “My name is “;
writeMyName(“chintan”,”.”);
echo “My name is “;
writeMyName(“Den”,”!”);
echo “My name is “;
writeMyName(“James”,”…”);
?>
</body>
</html>
The output of the code above will be:
My name is chintan Refsnes.
My name is Den Refsnes!
My name is James Refsnes…
PHP Functions – Return values
Functions can also be used to return values.
Example
<html><body>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo “1 + 10 = ” . add(1,10);
?>
</body></html>
The output of the code above will be:
1 + 10= 11