RandomBase.com logo
Announcement:
World of Warcraft Bots, need some help in choosing the best bot?

News Archives

Statistics

  • There are 17 users online.
  • Most users ever online was 424 on 03/16/08.
  • Our poor server had to serve 36 pages in the last 15 minutes.
  • And yet he managed to generate this page in 0.039 seconds.

Affiliates & friends

RandomBase.com isn't just one website - it is more.
RandomBase.com -> Tutorials -> [PHP] Functions [PHP] - Functions - Easy

Functions are pieces of script that can be used more then 1 time or in multiple scripts. Let's say you want to check if someone has a valid session ID but don't want to place on every top of your page a code that checks it. Then you can use a function that will replace a 10 line code into a 1 line code that calls for the function !

The normal view of a function is :
Function function-name($Parameter1,$Parameter2,...) {
Some code
}
Example :

functions.inc.php

<?php
function sessioncheck($session
{
    
//Checks if the session exists, is not empty and contains = 'Safe'
    
if (isset($session) && $session != '' && $session == 'Safe'
    {
        
//Display a positive reaction, so the session is valid
        
echo 'logged in!';                                        
    } 
    else
    {
        
//Display a negative reaction, so the session is not valid            
        
echo 'Not logged in';                                    
    }
}
?>

So this function will check if a session is valid. If the session is valid he will print out logged in, else he will print out Not logged in.

index.php
<?php
session_start
();                     //Always start with this if your script contains sessions
include 'functions.inc.php';        //Include our function script
sessioncheck($_SESSION['logged']);    //Call the function
$_SESSION['logged'] = 'Safe';        //Give the session a valid input so he the function will give a true response
sessioncheck($_SESSION['logged']);    //Call the function again
?>

The output will look like :
Not logged in
logged in!

Why did he change the second line ? Because, as you can see, I have defined the $_SESSION['logged'] to the requested needs to get a true response.
The use of functions can decrease the total size of your pages so a faster load is possible ! Also functions are called Snippets because they aren't a full code. So when you are searching for functions, search for snippets.