2009年3月15日星期日

PHP Snippet

1. When using REQUEST variables, there are always some COOKIE variables we don't want, beside POST, GET, SESSION. We can insert a piece of code below to filter all COOKies


if (count ( $_COOKIE )) {
foreach ( array_keys ( $_COOKIE ) as $value ) {
unset ( $_REQUEST [$value] );
}
}

Note: array_keys()函数返回一个数组中的所有键



2. PHP check the format of input Emails.

if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))

{

$_REQUEST ['email'] = trim ( $_REQUEST ['email'] );

if(substr_count($_REQUEST['email'],"@") != 1 stristr($_REQUEST['email']," "))
{
$errors [] = "Email address is invalid";
}else
{
$exploded_email = explode ( "@", $_REQUEST ['email'] );if(empty($exploded_email[0]) strlen($exploded_email[0]) > 64 empty($exploded_email[1]))
{
$errors [] = "Email address is invalid";
}else
{
if (substr_count ( $exploded_email [1], "." ) == 0) {
$errors [] = "Email address is invalid";
} else {
$exploded_domain = explode ( ".", $exploded_email [1] );
if (in_array ( "", $exploded_domain )) {
$errors [] = "Email address is invalid";
} else {
foreach ( $exploded_domain as $value ) {if(strlen($value) > 63 !preg_match('/^[a-z0-9-]+$/i',$value))
{
$errors [] = "Email address is invalid";
break;
}
}
}
}
}
}
}
?>


3. Check the referer is from the same website.

if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
?>


Note: stristr() 函数查找字符串在另一个字符串中第一次出现的位置。
如果成功,则返回字符串的其余部分(从匹配点)。如果没有找到该字符串,则返回 false。



4.Check for a blank form


function recursive_array_check_blank($element_value) {

global $set;

if (! is_array ( $element_value )) {
if (! empty ( $element_value )) {
$set = 1;
}
} else {

foreach ( $element_value as $value ) {
if ($set) {
break;
}
recursive_array_check_blank ( $value );
}

}

}

recursive_array_check_blank ( $_REQUEST );

if (! $set) {
$errors [] = "You cannot send a blank form";
}

unset ( $set );

?>



5. Using constant PHP_EOL as \n


if (! defined ( "PHP_EOL" )) {
define ( "PHP_EOL", strtoupper ( substr ( PHP_OS, 0, 3 ) == "WIN" ) ? "\r\n" : "\n" );
}
?>

没有评论: