php检查日期

PHP中文网
PHP中文网オリジナル
2016-05-25 17:11:311272ブラウズ

1. [代码][PHP]代码    

<?php
function GetIP() { //获取IP
    if ($_SERVER["HTTP_X_FORWARDED_FOR"])
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    else if ($_SERVER["HTTP_CLIENT_IP"])
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    else if ($_SERVER["REMOTE_ADDR"])
        $ip = $_SERVER["REMOTE_ADDR"];
    else if (getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else
        $ip = "Unknown";
    return $ip;
}
?>


<?php
function DateAdd($date, $int, $unit = "d") { //时间的增加(还可以改进成时分秒都可以增加,有时间再补上)
    $dateArr = explode("-", $date);
    $value[$unit] = $int;
    return date("Y-m-d", mktime(0,0,0, $dateArr[1] + $value[&#39;m&#39;], $dateArr[2] + $value[&#39;d&#39;], $dateArr[0] + $value[&#39;y&#39;]));
}

function GetWeekDay($date) {  //计算出给出的日期是星期几
    $dateArr = explode("-", $date);
    return date("w", mktime(0,0,0,$dateArr[1],$dateArr[2],$dateArr[0]));
}
?>


<?
function check_date($date) { //检查日期是否合法日期
    $dateArr = explode("-", $date);
    if (is_numeric($dateArr[0]) && is_numeric($dateArr[1]) && is_numeric($dateArr[2])) {
        return checkdate($dateArr[1],$dateArr[2],$dateArr[0]);
    }
    return false;
}
function check_time($time) {  //检查时间是否合法时间
    $timeArr = explode(":", $time);
    if (is_numeric($timeArr[0]) && is_numeric($timeArr[1]) && is_numeric($timeArr[2])) {
        if (($timeArr[0] >= 0 && $timeArr[0] <= 23) && ($timeArr[1] >= 0 && $timeArr[1] <= 59) && ($timeArr[2] >= 0 && $timeArr[2] <= 59))
            return true;
        else
            return false;
    }
    return false;
}

function DateDiff($date1, $date2, $unit = "") { //时间比较函数,返回两个日期相差几秒、几分钟、几小时或几天
    switch ($unit) {
        case &#39;s&#39;:
            $pidend = 1;
            break;
        case &#39;i&#39;:
            $pidend = 60;
            break;
        case &#39;h&#39;:
            $pidend = 3600;
            break;
        case &#39;d&#39;:
            $pidend = 86400;
            break;
        default:
            $pidend = 86400;
    }
    $time1 = strtotime($date1);
    $time2 = strtotime($date2);
    if ($time1 && $time2)
        return (float)($time1 - $time2) / $pidend;
    return false;
}

?>


PHP重定向
<?
方法一:header("Location: index.php");
方法二:echo "<scrīpt>window.location ="$PHP_SELF";</scrīpt>";
方法三:echo "<META HTTP-EQUIV="Refresh" CONTENT="0; URL=index.php">";

?>


获取访问者浏览器
<?
function browse_infor()
{
$browser="";$browserver="";
$Browsers =array("Lynx","MOSAIC","AOL","Opera","JAVA","MacWeb","WebExplorer","OmniWeb");
$Agent = $GLOBALS["HTTP_USER_AGENT"];
for ($i=0; $i<=7; $i++)
{
if (strpos($Agent,$Browsers[$i]))
{
$browser = $Browsers[$i];
$browserver ="";
}
}
if (ereg("Mozilla",$Agent) && !ereg("MSIE",$Agent))
{
$temp =explode("(", $Agent); $Part=$temp[0];
$temp =explode("/", $Part); $browserver=$temp[1];
$temp =explode(" ",$browserver); $browserver=$temp[0];
$browserver =preg_replace("/([d.]+)/","1",$browserver);
$browserver = " $browserver";
$browser = "Netscape Navigator";
}
if (ereg("Mozilla",$Agent) && ereg("Opera",$Agent))
{
$temp =explode("(", $Agent); $Part=$temp[1];
$temp =explode(")", $Part); $browserver=$temp[1];
$temp =explode(" ",$browserver);$browserver=$temp[2];
$browserver =preg_replace("/([d.]+)/","1",$browserver);
$browserver = " $browserver";
$browser = "Opera";
}
if (ereg("Mozilla",$Agent) && ereg("MSIE",$Agent))
{
$temp = explode("(", $Agent); $Part=$temp[1];
$temp = explode(";",$Part); $Part=$temp[1];
$temp = explode(" ",$Part);$browserver=$temp[2];
$browserver =preg_replace("/([d.]+)/","1",$browserver);
$browserver = " $browserver";
$browser = "Internet Explorer";
}
if ($browser!="")
{
$browseinfo = "$browser$browserver";
}
else
{
$browseinfo = "Unknown";
}
return $browseinfo;
}
//调用方法$browser=browseinfo() ;直接返回结果

?>


获取访问者操作系统
<?
function osinfo() {
$os="";
$Agent = $GLOBALS["HTTP_USER_AGENT"];
if (eregi(&#39;win&#39;,$Agent) && strpos($Agent, &#39;95&#39;)) {
$os="Windows 95";
}
elseif (eregi(&#39;win 9x&#39;,$Agent) && strpos($Agent, &#39;4.90&#39;)) {
$os="Windows ME";
}
elseif (eregi(&#39;win&#39;,$Agent) && ereg(&#39;98&#39;,$Agent)) {
$os="Windows 98";
}
elseif (eregi(&#39;win&#39;,$Agent) && eregi(&#39;nt 5.0&#39;,$Agent)) {
$os="Windows 2000";
}
elseif (eregi(&#39;win&#39;,$Agent) && eregi(&#39;nt&#39;,$Agent)) {
$os="Windows NT";
}
elseif (eregi(&#39;win&#39;,$Agent) && eregi(&#39;nt 5.1&#39;,$Agent)) {
$os="Windows XP";
}
elseif (eregi(&#39;win&#39;,$Agent) && ereg(&#39;32&#39;,$Agent)) {
$os="Windows 32";
}
elseif (eregi(&#39;linux&#39;,$Agent)) {
$os="Linux";
}
elseif (eregi(&#39;unix&#39;,$Agent)) {
$os="Unix";
}
elseif (eregi(&#39;sun&#39;,$Agent) && eregi(&#39;os&#39;,$Agent)) {
$os="SunOS";
}
elseif (eregi(&#39;ibm&#39;,$Agent) && eregi(&#39;os&#39;,$Agent)) {
$os="IBM OS/2";
}
elseif (eregi(&#39;Mac&#39;,$Agent) && eregi(&#39;PC&#39;,$Agent)) {
$os="Macintosh";
}
elseif (eregi(&#39;PowerPC&#39;,$Agent)) {
$os="PowerPC";
}
elseif (eregi(&#39;AIX&#39;,$Agent)) {
$os="AIX";
}
elseif (eregi(&#39;HPUX&#39;,$Agent)) {
$os="HPUX";
}
elseif (eregi(&#39;NetBSD&#39;,$Agent)) {
$os="NetBSD";
}
elseif (eregi(&#39;BSD&#39;,$Agent)) {
$os="BSD";
}
elseif (ereg(&#39;OSF1&#39;,$Agent)) {
$os="OSF1";
}
elseif (ereg(&#39;IRIX&#39;,$Agent)) {
$os="IRIX";
}
elseif (eregi(&#39;FreeBSD&#39;,$Agent)) {
$os="FreeBSD";
}
if ($os==&#39;&#39;) $os = "Unknown";
return $os;
}
//调用方法$os=os_infor() ;

?>


文件格式类
<?
$mime_types = array(
&#39;gif&#39; => &#39;image/gif&#39;,
&#39;jpg&#39; => &#39;image/jpeg&#39;,
&#39;jpeg&#39; => &#39;image/jpeg&#39;,
&#39;jpe&#39; => &#39;image/jpeg&#39;,
&#39;bmp&#39; => &#39;image/bmp&#39;,
&#39;png&#39; => &#39;image/png&#39;,
&#39;tif&#39; => &#39;image/tiff&#39;,
&#39;tiff&#39; => &#39;image/tiff&#39;,
&#39;pict&#39; => &#39;image/x-pict&#39;,
&#39;pic&#39; => &#39;image/x-pict&#39;,
&#39;pct&#39; => &#39;image/x-pict&#39;,
&#39;tif&#39; => &#39;image/tiff&#39;,
&#39;tiff&#39; => &#39;image/tiff&#39;,
&#39;psd&#39; => &#39;image/x-photoshop&#39;,

&#39;swf&#39; => &#39;application/x-shockwave-flash&#39;,
&#39;js&#39; => &#39;application/x-javascrīpt&#39;,
&#39;pdf&#39; => &#39;application/pdf&#39;,
&#39;ps&#39; => &#39;application/postscrīpt&#39;,
&#39;eps&#39; => &#39;application/postscrīpt&#39;,
&#39;ai&#39; => &#39;application/postscrīpt&#39;,
&#39;wmf&#39; => &#39;application/x-msmetafile&#39;,

&#39;css&#39; => &#39;text/css&#39;,
&#39;htm&#39; => &#39;text/html&#39;,
&#39;html&#39; => &#39;text/html&#39;,
&#39;txt&#39; => &#39;text/plain&#39;,
&#39;xml&#39; => &#39;text/xml&#39;,
&#39;wml&#39; => &#39;text/wml&#39;,
&#39;wbmp&#39; => &#39;image/vnd.wap.wbmp&#39;,

&#39;mid&#39; => &#39;audio/midi&#39;,
&#39;wav&#39; => &#39;audio/wav&#39;,
&#39;mp3&#39; => &#39;audio/mpeg&#39;,
&#39;mp2&#39; => &#39;audio/mpeg&#39;,

&#39;avi&#39; => &#39;video/x-msvideo&#39;,
&#39;mpeg&#39; => &#39;video/mpeg&#39;,
&#39;mpg&#39; => &#39;video/mpeg&#39;,
&#39;qt&#39; => &#39;video/quicktime&#39;,
&#39;mov&#39; => &#39;video/quicktime&#39;,

&#39;lha&#39; => &#39;application/x-lha&#39;,
&#39;lzh&#39; => &#39;application/x-lha&#39;,
&#39;z&#39; => &#39;application/x-compress&#39;,
&#39;gtar&#39; => &#39;application/x-gtar&#39;,
&#39;gz&#39; => &#39;application/x-gzip&#39;,
&#39;gzip&#39; => &#39;application/x-gzip&#39;,
&#39;tgz&#39; => &#39;application/x-gzip&#39;,
&#39;tar&#39; => &#39;application/x-tar&#39;,
&#39;bz2&#39; => &#39;application/bzip2&#39;,
&#39;zip&#39; => &#39;application/zip&#39;,
&#39;arj&#39; => &#39;application/x-arj&#39;,
&#39;rar&#39; => &#39;application/x-rar-compressed&#39;,

&#39;hqx&#39; => &#39;application/mac-binhex40&#39;,
&#39;sit&#39; => &#39;application/x-stuffit&#39;,
&#39;bin&#39; => &#39;application/x-macbinary&#39;,

&#39;uu&#39; => &#39;text/x-uuencode&#39;,
&#39;uue&#39; => &#39;text/x-uuencode&#39;,

&#39;latex&#39;=> &#39;application/x-latex&#39;,
&#39;ltx&#39; => &#39;application/x-latex&#39;,
&#39;tcl&#39; => &#39;application/x-tcl&#39;,

&#39;pgp&#39; => &#39;application/pgp&#39;,
&#39;asc&#39; => &#39;application/pgp&#39;,
&#39;exe&#39; => &#39;application/x-msdownload&#39;,
&#39;doc&#39; => &#39;application/msword&#39;,
&#39;rtf&#39; => &#39;application/rtf&#39;,
&#39;xls&#39; => &#39;application/vnd.ms-excel&#39;,
&#39;ppt&#39; => &#39;application/vnd.ms-powerpoint&#39;,
&#39;mdb&#39; => &#39;application/x-msaccess&#39;,
&#39;wri&#39; => &#39;application/x-mswrite&#39;,
);

?>


php生成excel文档
<?
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=test.xls");
echo "test1t";
echo "test2tn";
echo "test1t";
echo "test2tn";
echo "test1t";
echo "test2tn";
echo "test1t";
echo "test2tn";
echo "test1t";
echo "test2tn";
echo "test1t";
echo "test2tn";
//改动相应文件头就可以输出.doc .xls等文件格式了

?>


时间比较问题
举一个简单例子说明:比如一个论坛对当天发表的贴子用new图片标记一下。
方法一:
<?
//$db->rows[$i][date]中为数据库中datetime字段值.
$today=time();
$theDay=date("Y-m-d H:i:s",$today-24*3600);
$newTag=$db->rows[$i][date]>=$theDay?"<img src=&#39;../image/newinfor.gif&#39;>":"";
//方法二:
$newTag=$db->rows[$i][date]>=date("Y-m-d 00:00:00")?"<img src=&#39;../image/newinfor.gif&#39;>":"";

?>

//提取页面和浏览器提交的变量,作用相当于使PHP.INI开了全局变量
<?
@extract($_SERVER, EXTR_SKIP);
@extract($_SESSION, EXTR_SKIP);
@extract($_POST, EXTR_SKIP);
@extract($_FILES, EXTR_SKIP);
@extract($_GET, EXTR_SKIP);
@extract($_ENV, EXTR_SKIP);

?>

//读取文件函数
<?
function readfromfile($file_name) {
if (file_exists($file_name)) {
$filenum=fopen($file_name,"r");
flock($filenum,LOCK_EX);
$file_data=fread($filenum, filesize($file_name));
rewind($filenum);
fclose($filenum);
return $file_data;
}
}

?>

//写入文件函数
<?
function writetofile($file_name,$data,$method="w") {
$filenum=fopen($file_name,$method);
flock($filenum,LOCK_EX);
$file_data=fwrite($filenum,$data);
fclose($filenum);
return $file_data;
}

?>

//页面快速转向
<?
function turntopage($url="index.php",$info = "页面转向中...",$second=2){
print "<html>n<head>n<title>页面转向中....</title>n";
print "<meta http-equiv="refresh" content="$second;url=$url">n";
print "<style type="text/css">n<!--n";
print "td { font-family: "Verdana", "Arial";font-size: 12px}n";
print "A {COLOR: #000000; TEXT-DECORATION: none}n";
print "-->n</style>n";
print "</head>n<body>n";
print "<table width="100%" border="0" align="center">n";
print " <tr>n";
print " <td height="200"> </td>n";
print " </tr>n";
print " <tr>n";
print " <td align="center">n";
print " <table width="60%" border="0" cellpadding="8" bgcolor="#AA9FFF">n";
print " <tr>n";
print " <td height="30" align="center">页面转向提示信息</td>n";
print " </tr>n";
print " <tr>n";
print " <td align="center">$info</td>n";
print " </tr>n";
print " <tr>n";
print " <td align="center">n";
print " <a href="$url">如果你的浏览器不支持自动跳转,请按这里</a></td>n";
print " </tr>n";
print " </tr>n";
print " </table></td>n";
print " </tr>n";
print " <tr>n";
print " <td height="200"> </td>n";
print " </tr>n";
print "</table>n";
print "</body>n</html>";
exit;
?>


产生随机字符串函数
<?
function random($length) {
$hash = @#@#;
$chars = @#ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@#;
$max = strlen($chars) - 1;
mt_srand((double)microtime() * 1000000);
for($i = 0; $i < $length; $i++) {
  $hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}

?>

截取一定长度的字符串(该函数对GB2312使用有效)
<?
function Wordscut($string, $length ,$sss=0) {
if(strlen($string) > $length) {
               if($sss){
                      $length=$length - 3;
                      $addstr=@# ...@#;
                }
  for($i = 0; $i < $length; $i++) {
   if(ord($string[$i]) > 127) {
    $wordscut .= $string[$i].$string[$i + 1];
    $i++;
   } else {
    $wordscut .= $string[$i];
   }
  }
  return $wordscut.$addstr;
}
return $string;
}

?>

取得客户端IP地址
<?
function GetIP(){
             if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
                   $ip = getenv("HTTP_CLIENT_IP");
             else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
                   $ip = getenv("HTTP_X_FORWARDED_FOR");
             else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                   $ip = getenv("REMOTE_ADDR");
             else if (isset($_SERVER[@#REMOTE_ADDR@#]) && $_SERVER[@#REMOTE_ADDR@#] && strcasecmp($_SERVER[@#REMOTE_ADDR@#], "unknown"))
                   $ip = $_SERVER[@#REMOTE_ADDR@#];
             else
                  $ip = "unknown";

             return($ip);
}

?>

判断邮箱地址
<?
function checkEmail($inAddress)
{
return (ereg("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+",$inAddress));
}

?>

分页(两个函数配合使用)
<?
function getpage($sql,$page_size=20)
{
      global $page,$totalpage,$sums;  //out param
      $page = $_GET["page"];
      //$eachpage = $page_size;
      $pagesql = strstr($sql," from ");
      $pagesql = "select count(*) as ids ".$pagesql;
      $result = mysql_query($pagesql);
      if($rs = mysql_fetch_array($result)) $sums = $rs[0];
      $totalpage = ceil($sums/$page_size);
      if((!$page)($page<1)) $page=1;
   $startpos = ($page-1)*$page_size;
   $sql .=" limit $startpos,$page_size ";
    return $sql;
}
function showbar($string="")
{     
    global $page,$totalpage;
$out="共<font ".$totalpage."color=@#red@#><b>".$totalpage."</b></font>页  ";
    $linkNum =4;
    $start = ($page-round($linkNum/2))>0 ? ($page-round($linkNum/2)) : "1";
    $end   = ($page+round($linkNum/2))<$totalpage ? ($page+round($linkNum/2)) : $totalpage;
    $prestart=$start-1;
    $nextend=$end+1;
    if($page<>1) 
$out .= "<a href=@#?page=1&&".$string."@#title=第一页>第一页</a> ";
    if($start>1)
$out.="<a href=@#?page=".$prestart."@# title=上一页>..<<</a> ";

for($t=$start;$t<=$end;$t++)
    {
     $out .= ($page==$t) ? "<font [".$t."]color=@#red@#><b>[".$t."]</b></font> " : "<a $thref=@#?page=$t&&".$string."@#>$t</a> ";
    }
if($end<$totalpage)
$out.="<a href=@#?page=".$nextend."&&".$string."@# title=下一页>>>..</a>";
    if($page<>$totalpage)
   $out .= " <a href=@#?page=".$totalpage."&&".$string."@# title=最后页>最后页</a>";
   return $out;
}

?>

获取新插入数据的ID
<?
mysql_insert_id();
?>



//获得当前的脚本网址
<?
function get_php_url(){
        if(!empty($_server["REQUEST_URI"])){
                $scriptName = $_SERVER["REQUEST_URI"];
                $nowurl = $scriptName;
        }else{
                $scriptName = $_SERVER["PHP_SELF"];
                if(empty($_SERVER["QUERY_STRING"])) $nowurl = $scriptName;
                else $nowurl = $scriptName."?".$_SERVER["QUERY_STRING"];
        }
        return $nowurl;
}

?>


//把全角数字转为半角数字
<?
function GetAlabNum($fnum){
        $nums = array("0","1","2","3","4","5","6","7","8","9");
        $fnums = "0123456789";
        for($i=0;$i<=9;$i++) $fnum = str_replace($nums[$i],$fnums[$i],$fnum);
        $fnum = ereg_replace("[^0-9.]|^0{1,}","",$fnum);
        if($fnum=="") $fnum=0;
        return $fnum;
}

?>



//去除HTML标记
<?
function Text2Html($txt){
        $txt = str_replace("  "," ",$txt);
        $txt = str_replace("<","&lt;",$txt);
        $txt = str_replace(">","&gt;",$txt);
        $txt = preg_replace("/[rn]{1,}/isU","
rn",$txt);
        return $txt;
}

?>



//相对路径转化成绝对路径
<?
function relative_to_absolute($content, $feed_url) { 
    preg_match(&#39;/(http|https|ftp):///&#39;, $feed_url, $protocol); 
    $server_url = preg_replace("/(http|https|ftp|news):///", "", $feed_url); 
    $server_url = preg_replace("//.*/", "", $server_url); 

    if ($server_url == &#39;&#39;) { 
        return $content; 
    } 

    if (isset($protocol[0])) { 
        $new_content = preg_replace(&#39;/href="//&#39;, &#39;href="&#39;.$protocol[0].$server_url.&#39;/&#39;, $content); 
        $new_content = preg_replace(&#39;/src="//&#39;, &#39;src="&#39;.$protocol[0].$server_url.&#39;/&#39;, $new_content); 
    } else { 
        $new_content = $content; 
    } 
    return $new_content; 
} 

?>


//取得所有链接
<?
function get_all_url($code){ 
        preg_match_all(&#39;/<as+href=["|&#39;]?([^>"&#39; ]+)["|&#39;]?s*[^>]*>([^>]+)</a>/i&#39;,$code,$arr); 
        return array(&#39;name&#39;=>$arr[2],&#39;url&#39;=>$arr[1]); 
}

?>



//HTML表格的每行转为CSV格式数组
<?
function get_tr_array($table) {
        $table = preg_replace("&#39;<td[^>]*?>&#39;si",&#39;"&#39;,$table);
        $table = str_replace("</td>",&#39;",&#39;,$table);
        $table = str_replace("</tr>","{tr}",$table);
        //去掉 HTML 标记 
        $table = preg_replace("&#39;<[/!]*?[^<>]*?>&#39;si","",$table);
        //去掉空白字符  
        $table = preg_replace("&#39;([rn])[s]+&#39;","",$table);
        $table = str_replace(" ","",$table);
        $table = str_replace(" ","",$table);

        $table = explode(",{tr}",$table);
        array_pop($table);
        return $table;
}

?>


//将HTML表格的每行每列转为数组,采集表格数据
<?
function get_td_array($table) {
        $table = preg_replace("&#39;<table[^>]*?>&#39;si","",$table);
        $table = preg_replace("&#39;<tr[^>]*?>&#39;si","",$table);
        $table = preg_replace("&#39;<td[^>]*?>&#39;si","",$table);
        $table = str_replace("</tr>","{tr}",$table);
        $table = str_replace("</td>","{td}",$table);
        //去掉 HTML 标记 
        $table = preg_replace("&#39;<[/!]*?[^<>]*?>&#39;si","",$table);
        //去掉空白字符  
        $table = preg_replace("&#39;([rn])[s]+&#39;","",$table);
        $table = str_replace(" ","",$table);
        $table = str_replace(" ","",$table);
        
        $table = explode(&#39;{tr}&#39;, $table);
        array_pop($table);
        foreach ($table as $key=>$tr) {
                $td = explode(&#39;{td}&#39;, $tr);
                array_pop($td);
            $td_array[] = $td;
        }
        return $td_array;
}

?>



//返回字符串中的所有单词 $distinct=true 去除重复
<?
function split_en_str($str,$distinct=true) {
        preg_match_all(&#39;/([a-zA-Z]+)/&#39;,$str,$match);
        if ($distinct == true) {
                $match[1] = array_unique($match[1]);
        }
        sort($match[1]);
        return $match[1];
}
?>


//打印出为本PHP项目做出贡献的人员的清单
<?
string phpcredits(void)

?>

                   


                   

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。