Table of Contents
2. [代码]PHP function to display limited words from a string.    
3. [代码]显示 Youtube 或 Vimeo 视频缩略图    
4. [代码]根据生日计算年龄 
5. [代码]Cookie 操作
6. [代码]生成随机密码    
7. [代码]计算日期差异   
8. [代码]转换秒到日期、时或者分  
9. [代码]文件解压 
Home php教程 PHP源码 一些很有用的 PHP 代码片段

一些很有用的 PHP 代码片段

May 25, 2016 pm 04:58 PM
php

一些很有用的 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");
 
?>
Copy after login

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);
Copy after login

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;); ?>" />
Copy after login

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.
Copy after login
//设置 Cookie
setcookie("name", &#39;value&#39;, time()+3600*60*30);

//显示 Cookie
if ($_COOKIE["name"]!=""){
$_SESSION[&#39;name&#39;] = $_COOKIE["name"];
}
Copy after login

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);
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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);
}
?>
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles