登录  /  注册
首页 > php教程 > PHP源码 > 正文

一些很有用的 PHP 代码片段

PHP中文网
发布: 2016-05-25 16:58:08
原创
957人浏览过

一些很有用的 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='' ){
$words = preg_split( '/[\s]+/', $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,'...'); 

or

echo words_limit($yourString, 50);
登录后复制

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

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

<img src="<?php echo video_image('youtube URL'); ?>" />
登录后复制

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

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

echo age_from_dob('2005/04/19'); date in yyyy/mm/dd format.
登录后复制

5. [代码]Cookie 操作

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

//显示 Cookie
if ($_COOKIE["name"]!=""){
$_SESSION['name'] = $_COOKIE["name"];
}
登录后复制

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

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

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

  $str = '';
  $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 '0 second';
    }

    $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 = '';

    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中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学