tonwei139 发表于 2017-3-4 07:50:34

PHP编程常用的PHP函数

  1.PHP获取客户端真实 IP 地址
  该函数将获取用户的真实 IP 地址,即便他使用代理服务器。
  function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
       $ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif
  (!emptyempty($_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;
}
  2.PHP寻找两个字符串的相似性
  PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。
  similar_text($string1, $string2, $percent);
3.PHP生成一个随机字符串
  如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。
  function generate_rand($l)
  {
        $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;
        srand((double)microtime()*1000000);
        for($i=0; $i<$l; $i++) {
              $rand.= $c;
       }
        return $rand;
}
  
  1. PHP可阅读随机字符串
  此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。
  function readable_random_string($length = 6)
  {
         $conso=array(“b”,”c”,”d”,”f”,”g”,”h”,”j”,”k”,”l”,
         “m”,”n”,”p”,”r”,”s”,”t”,”v”,”w”,”x”,”y”,”z”);
         $vocal=array(“a”,”e”,”i”,”o”,”u”);
         $password=”";
         srand ((double)microtime()*1000000);
         $max = $length/2;
         for($i=1; $i<=$max; $i++)
        {
                  $password.=$conso;
                  $password.=$vocal;
        }
         return $password;
}
  2. PHP生成一个随机字符串
  如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。
  function generate_rand($l)
  {
        $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;
        srand((double)microtime()*1000000);
        for($i=0; $i<$l; $i++)
  {
               $rand.= $c;
         }
        return $rand;
}
  3. PHP列出目录内容
  function list_files($dir)
{
      if(is_dir($dir))
     {
            if($handle = opendir($dir))
           {
                   while(($file = readdir($handle)) !== false)
                   {
                           if($file != “.” && $file != “..” && $file != “Thumbs.db”)
                          {
                                 echo ‘’.$file.’;
                           }
                   }
                  closedir($handle);
          }
     }
}
  4.PHP解析 JSON 数据
  与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。
  $json_string=’{“id”:1,”name”:”foo”,”email”:”foo@foobar.com”,”interest”:["wordpress","php"]} ‘;
$obj=json_decode($json_string);
echo $obj->name;
  echo $obj->interest;
  5.PHP解析 XML 数据
  $xml_string="
  Foo
foo@bar.com
  ";
  $xml = simplexml_load_string($xml_string);
  foreach ($xml->user as $user)
{
       echo $user['id'], ‘  ‘;
       echo $user->name, ‘  ‘;
       echo $user->email, ‘
’;
}
页: [1]
查看完整版本: PHP编程常用的PHP函数