首页 > 编程技术 > php

php计算几分钟前发贴子

发布时间:2016-11-25 17:31

php中时间轴开发,即显示为“刚刚”、“5分钟前”、“昨天10:23”等,有需要的朋友可以参考一下。
 代码如下 复制代码
function tranTime($time) {
    $rtime = date("m-d H:i",$time);
    $htime = date("H:i",$time);
    
    $time = time() - $time;
 
    if ($time < 60) {
        $str = '刚刚';
    }
    elseif ($time < 60 * 60) {
        $min = floor($time/60);
        $str = $min.'分钟前';
    }
    elseif ($time < 60 * 60 * 24) {
        $h = floor($time/(60*60));
        $str = $h.'小时前 '.$htime;
    }
    elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time/(60*60*24));
        if($d==1)
           $str = '昨天 '.$rtime;
        else
           $str = '前天 '.$rtime;
    }
    else {
        $str = $rtime;
    }
    return $str;
}

函数tranTime()中的参数$time必须为Unix时间戳,如果不是请先用strtotime()将其转换成Unix时间戳

调用

 代码如下 复制代码

$times="1286861696 ";  
echo tranTime($times);

一个简单的利用php的相关函数来实现数据提交,有需要的朋友可以参考一下。
 代码如下 复制代码

<?php
function wfopen($url,$post='',$cookie='',$timeout=15) {
        $matches = parse_url($url);
        $out = "POST {$matches['path']} HTTP/1.0rn";
        $out .= "Accept: */*rn";
        $out .= "Accept-Language: zh-cnrn";
        $out .= "Content-Type: application/x-www-form-urlencodedrn";
        $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT] rn";
        $out .= "Host: {$matches['host']}rn";
        $out .= 'Content-Length: '.strlen($post)."rn";
        $out .= "Connection: Closern";
        $out .= "Cache-Control: no-cachern";
        $out .= "Cookie: $cookiernrn";
        $out .= $post;
        $socket = @fsockopen($matches['host'],80,$errno,$errstr,$timeout) or die("$errstr($errno)");
        fwrite($socket,$out);
        $header = $data = "";
        while($infos = trim(fgets($socket,4096))) {
                $header.=$infos;
        }
        while(!feof($socket)) {
                $data .= fgets($socket,4096);
        }
        return $data;
}
echo wfopen('http://localhost/te.php','id=5');
?>

te.php

<?php
if(!empty($_POST['id'])) {
echo setcookie('auth','haowei',time()+3600,'/') ? 1 : 0;
}

一款实用的PHP货币换算程序代码哦,有需要的朋友可以参考一下。
 代码如下 复制代码
<?php
 
/*
* File: CurrencyConverter.php
* Author: Simon Jarvis
* Copyright: 2005 Simon Jarvis
* Date: 10/12/05
* Link: http://www.white-hat-web-design.co.uk/articles/php-currency-conversion.php
 
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
 
class CurrencyConverter {
 
   var $xml_file = "www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
   var $mysql_host, $mysql_user, $mysql_pass, $mysql_db, $mysql_table;
   var $exchange_rates = array();
 
   //Load Currency Rates
 
   function CurrencyConverter($host,$user,$pass,$db,$tb) {
 
      $this->mysql_host = $host;
      $this->mysql_user = $user;
      $this->mysql_pass = $pass;
      $this->mysql_db = $db;
      $this->mysql_table = $tb;
 
      $this->checkLastUpdated();
 
      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass);
 
      $rs = mysql_select_db($this->mysql_db,$conn);
 
      $sql = "SELECT * FROM ".$this->mysql_table;
 
      $rs =  mysql_query($sql,$conn);
 
      while($row = mysql_fetch_array($rs)) {
 
         $this->exchange_rates[$row['currency']] = $row['rate'];
      }
 
   }
 
   /* Perform the actual conversion, defaults to £1.00 GBP to USD */
   function convert($amount=1,$from="GBP",$to="USD",$decimals=2) {
 
      return(number_format(($amount/$this->exchange_rates[$from])*$this->exchange_rates[$to],$decimals));
   }
 
   /* Check to see how long since the data was last updated */
   function checkLastUpdated() {
      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass);
 
      $rs = mysql_select_db($this->mysql_db,$conn);
 
      $sql = "SHOW TABLE STATUS FROM ".$this->mysql_db." LIKE '".$this->mysql_table."'";
 
      $rs =  mysql_query($sql,$conn);
 
      if(mysql_num_rows($rs) == 0 ) {
 
         $this->createTable();
      } else {
         $row = mysql_fetch_array($rs);
         if(time() > (strtotime($row["Update_time"])+(12*60*60)) ) {
 
            $this->downloadExchangeRates();
         }
      }
   }
 
   /* Download xml file, extract exchange rates and store values in database */
 
   function downloadExchangeRates() {
      $currency_domain = substr($this->xml_file,0,strpos($this->xml_file,"/"));
      $currency_file = substr($this->xml_file,strpos($this->xml_file,"/"));
      $fp = @fsockopen($currency_domain, 80, $errno, $errstr, 10);
      if($fp) {
 
         $out = "GET ".$currency_file." HTTP/1.1rn";
         $out .= "Host: ".$currency_domain."rn";
         $out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5rn";
         $out .= "Connection: Closernrn";
         fwrite($fp, $out);
         while (!feof($fp)) {
 
            $buffer .= fgets($fp, 128);
         }
         fclose($fp);
 
         $pattern = "{<Cubes*currency='(w*)'s*rate='([d.]*)'/>}is";
         preg_match_all($pattern,$buffer,$xml_rates);
         array_shift($xml_rates);
 
         for($i=0;$i<count($xml_rates[0]);$i++) {
 
            $exchange_rate[$xml_rates[0][$i]] = $xml_rates[1][$i];
         }
 
         $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass);
 
         $rs = mysql_select_db($this->mysql_db,$conn);
 
         foreach($exchange_rate as $currency=>$rate) {
 
            if((is_numeric($rate)) && ($rate != 0)) {
 
               $sql = "SELECT * FROM ".$this->mysql_table." WHERE currency='".$currency."'";
               $rs =  mysql_query($sql,$conn) or die(mysql_error());
               if(mysql_num_rows($rs) > 0) {
 
                  $sql = "UPDATE ".$this->mysql_table." SET rate=".$rate." WHERE currency='".$currency."'";
               } else {
 
                  $sql = "INSERT INTO ".$this->mysql_table." VALUES('".$currency."',".$rate.")";
               }
 
               $rs =  mysql_query($sql,$conn) or die(mysql_error());
            }
 
         }
      }
   }
 
   /* Create the currency exchange table */
   function createTable() {
 
      $conn = mysql_connect($this->mysql_host,$this->mysql_user,$this->mysql_pass);
 
      $rs = mysql_select_db($this->mysql_db,$conn);
 
      $sql = "CREATE TABLE ".$this->mysql_table." ( currency char(3) NOT NULL default '', rate float NOT NULL default '0', PRIMARY KEY(currency) ) ENGINE=MyISAM";
 
      $rs =  mysql_query($sql,$conn) or die(mysql_error());
 
      $sql = "INSERT INTO ".$this->mysql_table." VALUES('EUR',1)";
 
      $rs =  mysql_query($sql,$conn) or die(mysql_error());
 
      $this->downloadExchangeRates();
   }
 
}
 
?>


Copy the above code into a new file and save it as CurrencyConverter.php. Whenever you need to make a conversion just include the class file and call the ‘convert’ function. You will need to enter your own mysql database variables such as the login details. The example below will convert £2.50 GBP into US Dollars ($).

 代码如下 复制代码

<?php
   include('CurrencyConverter.php');
   $x = new CurrencyConverter('your_host','your_username','your_password','your_database_name','your_table_name');
   echo $x->convert(2.50,'GBP','USD');
?>

从国外网站找到的一款php随机密码生成程序哦,先是可以定义基数,然后再利用mt_rand与substr进来取第N个字符。

Randomly generated password: m1ztpxw8

 

 代码如下 复制代码
<?php
function genPwd($length=6) {
   $password = '';
   $possible = '23456789bcdfghjkmnpqrstvwxyz';
   $i = 0;
   while ($i < $length) {
 
      $password .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
      $i++;
   }
 
   return $password;
}
?>

测试方法

 代码如下 复制代码

<?php
   $password = genPwd(8);
?>

提供一款可以自动cookie登录方法,用户可以在登录时选择保存进程几天几个月等,我们只要进来页面时判断一下就KO了。
 代码如下 复制代码

<html>
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<form name="form1" method="post" action="login.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="2">
    <tr>
      <td width="150"><div align="right">用户名:</div></td>
      <td width="150"><input type="text" name="username"></td>
    </tr>
    <tr>
      <td><div align="right">密码:</div></td>
      <td><input type="password" name="passcode"></td>
    </tr>
    <tr>
      <td><div align="right">Cookie保存时间:</div></td>
      <td><select name="cookie" id="cookie">
        <option value="0" selected>浏览器进程</option>
        <option value="1">保存1天</option>
        <option value="2">保存30天</option>
        <option value="3">保存365天</option>
      </select></td>
    </tr>
</table>
<p align="center">
    <input type="submit" name="Submit" value="Submit">
    <input type="reset" name="Reset" value="Reset">
</p>
</form>
</body>
</html>

-------------------------------------------------------------------------------------------------------------------------

 代码如下 复制代码

<?php
@mysql_connect("localhost", "root","1981427")     //选择数据库之前需要先连接数据库服务器
or die("数据库服务器连接失败");
@mysql_select_db("test")      //选择数据库mydb
or die("数据库不存在或不可用");
//获取用户输入
$username = $_POST['username'];
$passcode = $_POST['passcode'];
$cookie   = $_POST['cookie'];
//执行SQL语句
$query = @mysql_query("select username, userflag from users "
."where username = '$username' and passcode = '$passcode'")
or die("SQL语句执行失败");
//判断用户是否存在,密码是否正确
if($row = mysql_fetch_array($query))
{
if($row['userflag'] == 1 or $row['userflag'] == 0)    //判断用户权限信息是否有效
{
   switch($cookie)         //根据用户的选择设置cookie保存时间
   {
    case 0:         //保存Cookie为浏览器进程
     setcookie("username", $row['username']);
     break;
    case 1:         //保存1天
     setcookie("username", $row['username'], time()+24*60*60);
     break;
    case 2:         //保存30天
     setcookie("username", $row['username'], time()+30*24*60*60);
     break;
    case 3:         //保存365天
     setcookie("username", $row['username'], time()+365*24*60*60);
     break;
   }
   header("location: main.php");      //自动跳转到main.php
}
else
{
   echo "用户权限信息不正确";
}
}
else
{
echo "用户名或密码错误";
}
?>

-------------------------------------------------------------------------------------------------------------------------

 代码如下 复制代码

<?php
session_start();
if(isset($_COOKIE['username']))
{
@mysql_connect("localhost", "root","1981427")     //选择数据库之前需要先连接数据库服务器
or die("数据库服务器连接失败");
@mysql_select_db("test")      //选择数据库mydb
or die("数据库不存在或不可用");
//获取Session
$username = $_COOKIE['username'];
//执行SQL语句获得userflag的值
$query = @mysql_query("select userflag from users "
."where username = '$username'")
or die("SQL语句执行失败");
$row = mysql_fetch_array($query);
//获得用户权限信息
$flag = $row['userflag'];
//根据userflag的值输出不同的欢迎信息
if($flag == 1)
   echo "欢迎管理员".$_SESSION['username']."登录系统";
if($flag == 0)
   echo "欢迎用户".$_SESSION['username']."登录系统";
echo "<a href="logout.php" mce_href="logout.php">注销</a>";
}
else
{
echo "您没有权限访问本页面";
}
?>

-------------------------------------------------------------------------------------------------------------------------

 代码如下 复制代码

<?php
setcookie("username");
echo "注销成功";
?>

标签:[!--infotagslink--]

您可能感兴趣的文章: