首页 >php教程 >php手册 >15非常有用的PHP代码片段

15非常有用的PHP代码片段

WBOY
WBOY原创
2016-06-13 10:51:591348浏览

以下是十五个最有用的PHP代码片段。您可能还想对任何代码或者你也可以分享你的代码片段在评论部分如果你认为它可能对其他人有用。
1。发送邮件使用邮件函数在PHP
 与站长百科     PHP教程同步首发
$to = "viralpatel.net@gmail.com";
$subject = "VIRALPATEL.net";
$body = "Body of your message here you can use HTML too. e.g.
Bold ";
$headers = "From: Peter\r\n";
$headers .= "Reply-To: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.com\r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$body,$headers);
?>
2。Base64编码和解码字符串在PHP
 
function base64url_encode($plainText) {
    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}
 
function base64url_decode($plainText) {
    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}
3。在PHP中获得远程IP地址
 
function getRemoteIPAddress() {
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
}
 
上面的代码将无法工作,以防您的客户端代理服务器后面。在这种情况下使用函数来获得真正的IP地址的客户。
 
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;
}
4。秒到字符串
 
这个函数将返回给定时间段期间在天、小时、分钟和秒。
例如secsToStr(1234567)将返回“14天6小时56分钟,7秒”
 
function secsToStr($secs) {
    if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days1){$r.='s';}if($secs>0){$r.=', ';}}
    if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours1){$r.='s';}if($secs>0){$r.=', ';}}
    if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes1){$r.='s';}if($secs>0){$r.=', ';}}
    $r.=$secs.' second';if($secs1){$r.='s';}
    return $r;
}
5。电子邮件验证代码片段在PHP
 
$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
    echo 'This is a valid email.';
} else{
    echo 'This is an invalid email.';
}
6。解析XML的简单的方法使用PHP
 
所需的扩展:SimpleXML
 
//this is a sample xml string
$xml_string="

   
        ben
        A
   

   
        h2o
        K
   

";
 
//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);
 
//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
   //attribute are accessted by
   echo $record['name'], '  ';
   //node are accessted by -> operator
   echo $record->symbol, '  ';
   echo $record->code, '
';
}
7。数据库连接在PHP
 
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost";        //Location Of Database usually its localhost
$dbUser = "xxxx";            //Database User Name
$dbPass = "xxxx";            //Database Password
$dbDatabase = "xxxx";       //Database Name
 
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
 
# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
function send_404()
{
    header('HTTP/1.x 404 Not Found');
    print ''."n".
    '

'."n".
    '404 Not Found'."n".
    ''."n".
    '

Not Found

'."n".
    '

The requested URL '.
    str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
    ' was not found on this server.

'."n".
    ''."n";
    exit;
}
 
# In any file you want to connect to the database,
# and in this case we will name this file db.php
# just add this line of php code (without the pound sign):
# include"db.php";
?>
8。创建和解析JSON数据在PHP
 
以下是PHP代码创建JSON数据格式,上面的示例使用的PHP数组。
 
$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
echo json_encode($json_data);
 
下面的代码将解析JSON数据到PHP数组。
 
$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
$obj=json_decode($json_string);
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google
9。MySQL在PHP过程时间戳
 
$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records))
{
    echo $row;
}
10。在PHP中生成一个身份验证代码
 
这个基本的代码片段将创建一个随机身份验证代码,或者仅仅是一个随机字符串。
 
# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i     $pos = rand(0,36);
    $str .= $string{$pos};
}
echo $str;
# If you have a database you can save the string in
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify
?>
11。在PHP的日期格式验证
 
验证一个日期在“yyyy mm dd”格式。
 
function checkDateFormat($date)
{
    //match the format of the date
    if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
    {
        //check weather the date is valid of not
        if(checkdate($parts[2],$parts[3],$parts[1]))
            return true;
        else
        return false;
    }
    else
        return false;
}
12。HTTP重定向在PHP
 
    header('Location: http://you_stuff/url.php'); // stick your url here
?>
13。目录清单在PHP
 
 
 
function list_files($dir)
{
    if(is_dir($dir))
    {
        if($handle = opendir($dir))
        {
            while(($file = readdir($handle)) !== false)
            {
                if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
                {
                    echo ''.$file.'
'."\n";
                }
            }
            closedir($handle);
        }
    }
}
 
/*
To use:
 
    list_files("images/");
?>
*/
?>
14。在PHP浏览器检测脚本
 
    $useragent = $_SERVER ['HTTP_USER_AGENT'];
    echo "Your User Agent is: " . $useragent;
?>
15。Zip文件解压缩一个
 
    function unzip($location,$newLocation){
        if(exec("unzip $location",$arr)){
            mkdir($newLocation);
            for($i = 1;$i                 $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
                copy($location.'/'.$file,$newLocation.'/'.$file);
                unlink($location.'/'.$file);
            }
            return TRUE;
        }else{
            return FALSE;
        }
    }
?>
//Use the code as following:
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
    echo 'Success!';
else
    echo 'Error';
?>
 
你怎么这样小的收集的PHP代码片段。你可能想要将您的代码片段在评论中与他人分享。
作者:ssoftware
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn