> php教程 > PHP源码 > 본문

一些很有用的 PHP 代码片段

PHP中文网
풀어 주다: 2016-05-25 16:58:08
원래의
1293명이 탐색했습니다.

一些很有用的 PHP 代码片段

1. [代码]连接 MySQL 数据库    

<?php

 $host="localhost";
 $uname="database username";
 $pass="database password";
 $database = "database name";
 $connection=mysql_connect($host,$uname,$pass) 
 or die("Database Connection Failed");
 
 $result=mysql_select_db($database)
 or die("database cannot be selected");
 
?>
로그인 후 복사

2. [代码]PHP function to display limited words from a string.

function words_limit( $str, $num, $append_str=&#39;&#39; ){
$words = preg_split( &#39;/[\s]+/&#39;, $str, -1, PREG_SPLIT_OFFSET_CAPTURE );
 if( isset($words[$num][1]) ){
   $str = substr( $str, 0, $words[$num][1] ).$append_str;
 }
unset( $words, $num );
return trim( $str );>
}

echo words_limit($yourString, 50,&#39;...&#39;); 

or

echo words_limit($yourString, 50);
로그인 후 복사

3. [代码]显示 Youtube 或 Vimeo 视频缩略图

function video_image($url){
   $image_url = parse_url($url);
     if($image_url[&#39;host&#39;] == &#39;www.youtube.com&#39; || 
        $image_url[&#39;host&#39;] == &#39;youtube.com&#39;){
         $array = explode("&", $image_url[&#39;query&#39;]);
         return "http://img.youtube.com/vi/".substr($array[0], 2)."/0.jpg";
     }else if($image_url[&#39;host&#39;] == &#39;www.youtu.be&#39; || 
              $image_url[&#39;host&#39;] == &#39;youtu.be&#39;){
         $array = explode("/", $image_url[&#39;path&#39;]);
         return "http://img.youtube.com/vi/".$array[1]."/0.jpg";
     }else if($image_url[&#39;host&#39;] == &#39;www.vimeo.com&#39; || 
         $image_url[&#39;host&#39;] == &#39;vimeo.com&#39;){
         $hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/".
         substr($image_url[&#39;path&#39;], 1).".php"));
         return $hash[0]["thumbnail_medium"];
     }
}

<img src="<?php echo video_image(&#39;youtube URL&#39;); ?>" />
로그인 후 복사

4. [代码]根据生日计算年龄

function age_from_dob($dob){
$dob = strtotime($dob);
$y = date(&#39;Y&#39;, $dob);
 if (($m = (date(&#39;m&#39;) - date(&#39;m&#39;, $dob))) < 0) {
  $y++;
 } elseif ($m == 0 && date(&#39;d&#39;) - date(&#39;d&#39;, $dob) < 0) {
  $y++;
 }
return date(&#39;Y&#39;) - $y;
}

echo age_from_dob(&#39;2005/04/19&#39;); date in yyyy/mm/dd format.
로그인 후 복사

5. [代码]Cookie 操作

//设置 Cookie
setcookie("name", &#39;value&#39;, time()+3600*60*30);

//显示 Cookie
if ($_COOKIE["name"]!=""){
$_SESSION[&#39;name&#39;] = $_COOKIE["name"];
}
로그인 후 복사

6. [代码]生成随机密码

//方法1
echo substr(md5(uniqid()), 0, 8); 

//方法2
function rand_password($length){
  $chars =  &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&#39;;
  $chars .= &#39;0123456789&#39; ;
  $chars .= &#39;!@#%^&*()_,./<>?;:[]{}\|=+&#39;;

  $str = &#39;&#39;;
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[rand(0, $max)];

  return $str;
}

echo rand_password(16);
로그인 후 복사

7. [代码]计算日期差异

date_default_timezone_set("Asia/Calcutta");

function dt_differ($start, $end){
  $start = date("G:i:s:m:d:Y", strtotime($start));
  $date1=explode(":", $start);

  $end  = date("G:i:s:m:d:Y", strtotime($end));
  $date2=explode(":", $end);
	
  $starttime = mktime(date($date1[0]),date($date1[1]),date($date1[2]),
  date($date1[3]),date($date1[4]),date($date1[5]));
  $endtime   = mktime(date($date2[0]),date($date2[1]),date($date2[2]),
  date($date2[3]),date($date2[4]),date($date2[5]));

  $seconds_dif = $starttime-$endtime;

  return $seconds_dif;
}
로그인 후 복사

8. [代码]转换秒到日期、时或者分

function seconds2days($mysec) {
    $mysec = (int)$mysec;
    if ( $mysec === 0 ) {
        return &#39;0 second&#39;;
    }

    $mins  = 0;
    $hours = 0;
    $days  = 0;


    if ( $mysec >= 60 ) {
        $mins = (int)($mysec / 60);
        $mysec = $mysec % 60;
    }
    if ( $mins >= 60 ) {
        $hours = (int)($mins / 60);
        $mins = $mins % 60;
    }
    if ( $hours >= 24 ) {
        $days = (int)($hours / 24);
        $hours = $hours % 60;
    }

    $output = &#39;&#39;;

    if ($days){
        $output .= $days." days ";
    }
    if ($hours) {
        $output .= $hours." hours ";
    }
    if ( $mins ) {
        $output .= $mins." minutes ";
    }
    if ( $mysec ) {
        $output .= $mysec." seconds ";
    }
    $output = rtrim($output);
    return $output;
}
로그인 후 복사

9. [代码]文件解压

<?php
$zip = zip_open("moooredale.zip");
  if ($zip) {
   while ($zip_entry = zip_read($zip)) {
   $fp = fopen(zip_entry_name($zip_entry), "w");
   if (zip_entry_open($zip, $zip_entry, "r")) {
   $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
   fwrite($fp,"$buf");
   zip_entry_close($zip_entry);
   fclose($fp);
 }
}
zip_close($zip);
}
?>
로그인 후 복사


관련 라벨:
php
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!