Type Validation Functions in PHP
is_array() – Test for Arrays
is_bool() – Test for Booleans (TRUE, FALSE)
is_float() – Test for Floating-point numbers
is_int() – Test for Integers
is_null() – Test for NULLs
is_numeric() – Test forNumeric values, even as a string (e.g., ‘ 20′ )
is_resource() – Test for Resources, like a database connection
is_scalar() – Test for Scalar (single-valued) variables
is_string() – Test for Strings
Urlencoding in PHP using urlencode
<?php $myurlparam = "hello this is a test message"; $site = "http://www.w3mentor.com"; $query = $site; $query .= "&message=".urlencode( $myurlparam ); echo $query; ?>
Traversing Arrays Using foreach in PHP
$users = array("Mani", "Nani", "Item", "Raja"); print "The users are:\n"; foreach ($users as $key => $value) { print "#$key = $value\n"; }
Output:
The players are:
#0 = Mani
#1 = Nani
#2 = Item
#3 = Raja
Accessing string offsets in PHP
$str = "M"; $str{2} = "n"; $str{1} = "a"; $str = $str . "i"; print $str;
The above code will output “Mani”. Individual characters in a string can be accessed using the $str{offset} notation. You can use it to both read and write string offsets.
Output large amount of text in PHP
ob_start(); echo 'Put your text here'; $body = ob_get_contents(); ob_end_clean(); echo $body;
Determine user’s IP Address with proxy in PHP
function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; }
Strip defined HTML tags from PHP input
function strip_html_tags( $text ) { $text = preg_replace( array( // Remove invisible content '@<head[^>]*?>.*?</head>@siu', '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu', '@<object[^>]*?.*?</object>@siu', '@<embed[^>]*?.*?</embed>@siu', '@<applet[^>]*?.*?</applet>@siu', '@<noframes[^>]*?.*?</noframes>@siu', '@<noscript[^>]*?.*?</noscript>@siu', '@<noembed[^>]*?.*?</noembed>@siu', // Add line breaks before and after blocks '@</?((address)|(blockquote)|(center)|(del))@iu', '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu', '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu', '@</?((table)|(th)|(td)|(caption))@iu', '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu', '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu', '@</?((frameset)|(frame)|(iframe))@iu', ), array( ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', " $0", " $0", " $0", " $0", " $0", " $0", " $0", " $0", ), $text ); }
Generate Random String of desired length in PHP
function getCode($length=12) { //Ascii Code for number, lowercase, uppercase and special characters $no = range(48,57); $lo = range(97,122); $up = range(65,90); //exclude character I, l, 1, 0, O $eno = array(48, 49); $elo = array(108); $eup = array(73,79); $no = array_diff($no,$eno); $lo = array_diff($lo,$elo); $up = array_diff($up,$eup); $chr = array_merge($no, $lo, $up); for ($i=1;$i<=$length;$i++) { $code.= chr($chr[rand(0,count($chr)-1)]); } return $code; }
PHP func_get_args function
The func_get_args function returns, as an array, the arguments that have been passed to the function containing the call. This allows you to simplify the previous code to use a foreach loop:
$arglist = func_get_args(); foreach ($arglist as $arg) { // process $arg }
Like the other argument processing functions, it will generate a warning when not called from inside a function.
PHP func_get_arg function
The func_get_arg, when passed an integer, will return the argument passed to the current function, indexed by that integer. To process a variable argument list, you could use code such as:
for ($index = 0; index < func_num_args(); index++) { $arg = func_get_arg(index); }
The limitation of this function is that it does not take into account the default arguments when a value has not been passed by the call to the function.
PHP func_num_args function
The func_num_args function returns the number of arguments that were passed to a function and must be called from within that function. For example:
function variable_argument_function () { $num_args = func_num_args(); echo ("I was passed $num_args arguments."); } variable_argument_function ("w3m", 1, 2,2);
The output from this code snippet will be:
I was passed 4 arguments.
PHP function_exists function
The function_exists function tests to see whether a specific named function has been defined and implemented in the current scope. It is useful for testing, given a possible collection of equivalent routines, which is available for use or for making sure that the function that is about to be defined does not use a name that is already taken.
PHP getdate function
The getdate function returns an array that contains several key/ value pairs, representing the current date/time at the server:
mday From 1 to 31 (day of the month)
wday From 0 to 6 (Sunday to Saturday)
mon Numeric month of year, 1 to 12
month Textual equivalent of mon, January to December
year The year, in four-digit format; that is, 2008
yday The day of the year, zero-based
hours The hour component of the current time, 0 to 23
minutes The minute component of the current time, 0 to 59
seconds The second component of the current time, 0 to 59
Each of these key/value pairs can be accessed through its key:
$today_date = getdate(); echo "The month is $today_date['month'].";
PHP die function
The die function is used to do two things:
* Print an error message
* Halt the script
When die is encountered, no more processing will take place, and the error message passed to the function (if any) will be displayed. An example is as follows:
if (not_logged_in($user)) { die ("Error : $user not logged in."); }
die is generally used to catch system errors such as the inability to connect to a database.
PHP eval function
The eval function takes a string and evaluates it is if it were PHP code:
eval("$my_var = "a site"); echo $my_var;
This code will output “a site”. The $my_var variable had not existed until the eval function was called. The return value from eval is always set to null unless the code in the evaluation part returns a value, in which case the return value is passed back as the eval return value.
Executing a system command like LS in PHP
<?php // exec.php $cmd = "dir"; // Windows // $cmd = "ls"; // Linux, Unix & Mac exec(escapeshellcmd($cmd), $output, $status); if ($status) echo "Exec command failed"; else { echo "<b>"; foreach($output as $line) echo "$linen"; } ?>
Using Custom Error Handler in PHP
<?php error_reporting(E_ALL); function ErrHandler($errorno, $errorstr, $errorfile, $errorline) { $display = true; $notify = false; $halt_script = false; $error_msg = "<br>The $errorno error is occurring at $errorline in $errorfile<br>"; switch($errorno) { case E_USER_NOTICE: case E_NOTICE: $halt_script = false; $notify = true; $label = "<B>Notice</B>"; break; case E_USER_WARNING: case E_WARNING: $halt_script = false; $notify = true; $label = "<b>Warning</b>"; break; case E_USER_ERROR: case E_ERROR: $label = "<b>Fatal Error</b>"; $notify=true; $halt_script = false; break; case E_PARSE: $label = "<b>Parse Error</b>"; $notify=true; $halt_script = true; break; default: $label = "<b>Unknown Error</b>"; break; } if($notify) { $msg = $label . $error_msg; echo $msg; } if($halt_script) exit -1; } $error_handler = set_error_handler("ErrHandler"); echo "<BR><H2>Using Custom Error Handler</h2><BR>"; trigger_error("<BR>Error caused by E_USER_NOTICE</BR>", E_USER_NOTICE); trigger_error("<BR>Error caused by E_USER_WARNING</BR>", E_USER_WARNING); trigger_error("<BR>Error caused by E_USER_ERROR</BR>", E_USER_ERROR); trigger_error("<BR>Error caused by E_PARSE</BR>", E_PARSE); ?>
Generating Errors Using the trigger_error() Function in PHP
The assert() function checks whether the divisor is zero or not.
The error_log() function sends the message, Cannot perform division by zero, to the log file specified by the second parameter when the divisor is zero.
<?php // set the error reporting level for this script error_reporting(E_USER_ERROR); if (assert($divisor == 0)) { error_log("Cannot perform division by zero", 3, "var/www/html/PHP_XML/error.log"); trigger_error("Cannot perform division by zero", E_USER_ERROR); } ?>
Using Nested Functions in PHP
<?php function msg() { echo("<center><h2>Displaying even numbers</h2></center><p><p>"); function displayeven() { $ctr=0; echo("<font size=4>"); for($i=2;$i<=100;$i+=2) { echo("$i "); $ctr++; if($ctr%10==0) { echo("<p>"); } } echo("</font>"); } } msg(); displayeven(); ?>
Example of User-Defined Function in PHP
<?php echo("<center><h2>Displaying even numbers</h2></center><p><p>"); function displayeven() { $ctr=0; echo("<font size=4>"); for($i=2;$i<=100;$i+=2) { echo("$i "); $ctr++; if($ctr%10==0) { echo("<p>"); } } echo("</font>"); } echo("<center><h2>Displaying even numbers</h2></center><p><p>"); displayeven(); ?>
