php小代码(转)

function mySetCookie($data, $name){
    if(empty($data) || empty($name))return;
    $args = func_get_args();
    $time = empty($args[2])? time() + 3600 : time() + $args[2];
    $path = empty($args[3])? '' : $args[3];
    $domain = empty($args[4])? '' :  $args[4];
    $secure = empty($args[5])? '' : $args[5];
    if(is_array($data)){
        foreach($data as $key => $val){
            $full = "{$name}[$key]";
            setcookie($full, $val, $time, $path, $domain, $secure);
        }
    }else{
        setcookie($name, $data, $time, $path, $domain, $secure);
    }

}

$data = array('name' => '李四', 'age' => 15);
mySetCookie($data,'userInfo');
print_r($_COOKIE);
复制代码

 

//冒泡排序
function arrSort(&$arr, $asc = ''){
    $times = count($arr) - 1;
    for($i = 0; $i < $times; $i++){
        for($j = 0; $j < $times - $i; $j++){
            if($arr[$j] > $arr[$j + 1]){
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
    if('' != $asc) $arr = array_reverse($arr, false);//反转数组元素
}

//选择
function seleSort(&$arr){
    $times = count($arr) - 1;
    $jMax = count($arr);
    for($i = 0; $i < $times; $i++){
        $min = $arr[$i];
        $minId = $i; 
        for($j = $i + 1; $j < $jMax; $j++){
            if($min > $arr[$j]){
                $min = $arr[$j];
                $minId = $j;
            }
        }
        $temp = $arr[$i];
        $arr[$i] = $arr[$minId];
        $arr[$minId] = $temp;
    }
}

//插入
function inserSort(&$arr){
    $times = count($arr);
    for($i = 1; $i < $times; $i++){
        $insert = $arr[$i];
        $insertId = $i - 1;
        while($insertId >= 0 && $insert < $arr[$insertId]){
            $arr[$insertId + 1] = $arr[$insertId];
            $insertId--;
        }
        $arr[$insertId + 1] = $insert;
    }
}


写一个函数,算出两个文件的相对路径。
function relative_dir($fileA, $fileB){//A相当于B,所在目录
    $aPath = explode('/',dirname($fileA));
    $bPath = explode('/',dirname($fileB));
    $bLen = count($bPath);
    $j = 1;
    for($i = 1; $i < $bLen; $i++){
        if(isset($bPath) && isset($aPath)){
            if($aPath[$i] == $bPath[$i]){$j++;}//累计相同路径部分
            if($aPath[$i] != $bPath[$i]){$path .= '../';}//不同的,则增加退回上级
        }
    }
    $path .= implode('/',array_slice($aPath, $j)).'/'.basename($fileA);
    return $path;
}

$a = 'a/b/c/test/5/8/aaa.php';
$b = 'a/b/c/check/1/2/3/4/bbb.php';
echo relative_dir($a,$b);

以附件方式实现文件下载:
$file = 'e:/个人简历.doc';
$file = iconv('utf-8', 'gb2312',$file);
if(file_exists($file)){
    $fname = basename($file);
    $fsize = filesize($file);
    header("Content-type:application/octet-stream");//二进制数据
    header("Content-Disposition:attachment;filename={$fname}");//附件形式
    header("Accept-ranges:bytes");
    header("Accept-length:".$fsize);
    readfile($file);
}else{
    exit('flie not found!');
}

遍历一个目录,及其子目录:
function recurDir($pathName){
    $result = array();
    $temp = array();
    if(!is_dir($pathName) || !is_readable($pathName)) return null;
    $allFiles = scandir($pathName);
    foreach($allFiles as $fileName){
        if(in_array($fileName, array('.','..')))continue;
        $fullName = $pathName . '/' . $fileName;
        if(is_dir($fullName)){
            $result[$fileName] = recurdir($fullName);
        }else{
            $temp[] = $fileName;
        }
    }
    foreach($temp as $f){
        $result[] = $f;
    }
    return $result;
}
$pathName = 'D:\AppServ\www\zbseoag\\';
print_r(recurDir($pathName));

从URL中获取文件扩展名:
 function getExt($url){
   $arr = parse_url($url);//把URL解析成数组
   $file = basename($arr['path']);
   $ext = explode('.',$file);
   return end($ext);
}

mysql事务处理:

 mysql_query('BEGIN');
 mysql_query("INSERT INTO customerinfo(`name`) VALUES('$name1')");
 mysql_query('SELECT * FROM `orderinfo` where customerid='.$id);
 mysql_query('COMMIT');

获取用户或服务器信息:
echo $_SERVER['REMOTE_ADDR']; // 或者 getenv('REMOTE_ADDR') 浏览当前页面的用户的 IP 地址。 
echo gethostbyname('www.baidu.com'); //根据域名,取得IP地址
echo $_SERVER['QUERY_STRING'];//查询参数字符串
echo $_SERVER['SERVER_NAME'];//服务器名

修改SESSION的生存时间:
方法1:将php.ini中的 session.gc_maxlifetime 设置为9999
方法2:$savePath = "./session_save_dir/";
       $lifeTime = 100;//单位:s
       session_save_path($savePath);
       session_set_cookie_params($lifeTime);
       session_start();

PHP正则:
function checkEmail($email){
    $pregEmail = "/([a-z0-9]*[-_/.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[/.][a-z]{2,3}([/.][a-z]{2})?/i";
    return preg_match($pregEmail,$email); 
}

查看PHP支持的函数:
$arr = get_defined_functions(); 
echo "<pre>这里显示系统所支持的所有函数,和自定以函数"; 
print_r($arr); 
echo "</pre>";

把数据解析成变量:
$a = 'Orig';
$my_array = array("a" => "Cat", "b" => "Dog");
extract($my_array, EXTR_PREFIX_SAME, 'the');
echo '$a='.$a.'$b='.$b.'$the_a='.$the_a;

文件上传:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function addUpload(){
    document.getElementById("upfiles").innerHTML += '<li>文件:<input type="file" name="files[]" /></li>';
}
function resetUpload(){ 
  document.getElementById("upfiles").innerHTML = '<li>文件:<input type="file" name="files[]" /></li>';
}
</script>
<form action="" method="post" enctype="multipart/form-data" >
<ul id="upfiles">
<li>文件:<input type="file" name="files[]" /></li>
</ul>
<input type="submit" value="提交" />
<input type="button" value="增加上传框" onClick="addUpload()" />
<input type="button" value="重设上传框" onClick="resetUpload()" />
</form>

$files = 'files';//files是$_FILES中的一个元素数组,并所上传文件信息进行了归类
$upDir = './upImg/';
$fTypes = 'jpg|gif|txt|chm';

function upFilse($files, $upDir, $fTypes){
    if(isset($_FILES[$files]['name'])){
        if(!is_dir($upDir)) mkdir($upDir, 0777, true) or exit('上传目录创建失败!');
        $ftypeArr = explode('|',$fTypes);
        foreach($_FILES[$files]['name'] as $i => $value){
            $fType = strtolower(end(explode(".",$_FILES[$files]['name'][$i])));
            if(in_array($fType, $ftypeArr)){
                $path = $upDir.time().$_FILES[$files]['name'][$i];//指定目录,且包含有文件名
                move_uploaded_file($_FILES[$files]['tmp_name'][$i], $path);//移到指定目录
                if($_FILES[$files]['error'][$i] == 0){
                    $file[$_FILES[$files]['name'][$i]] = $path; 
                    list($name, $path) = each($file);//each(数组)返回当前由键名与键值所构成的数组;list(变量1, 变量n 【或数组】) = 数字索引的数组,将值赋给变量。
                    $sql = "INSERT INTO `database`.`table`(name, path) VALUES ('$name', '$path')";
                    $msg[] =  $value.'文件上传成功';    
                }else
                    $msg[] = $value.'文件上传失败!';
            }else 
                $msg[] = $value.'文件格式不正确!';
        }
        return $msg;
    }
}
print_r(upFilse($files, $upDir, $fTypes));

求今天是星期几:
$time = getdate();//获取当前时间戳中的时间信息
$weekday = array('星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
$wday = $time['wday'];//当前是一个星期中的第几天
echo date("今天是:Y年m月d日H:i:s $weekday[$wday]");

求下周一是几月几日:
$time = time();//当前时间戳
$weekday = date('w');//当天的数字星期
switch($weekday){
    case 0: $next_week = $time+86400;break;//星期天则加一天
    case 1: $next_week = $time+7*86400;break;//星期一,则加七天
    case 2: $next_week = $time+6*86400;break;
    case 3: $next_week = $time+5*86400;break;
    case 4: $next_week = $time+4*86400;break;
    case 5: $next_week = $time+3*86400;break;
    case 6: $next_week = $time+2*86400;break;
}
echo date('Y-m-d',$next_week);

逐行读取文件内容:
$fhandle = fopen('../open.txt','rb');
while(!feof($fhandle)){//判断是否到文件结尾
    echo fgets($fhandle);//一行
    echo fgetss($fhandle);//一行,且去除标记代码
}
fclose($fhandle);

逐字读取文件内容:
$fhandle = fopen('../open.txt','rb');
while(($letter = fgetc($fhandle)) != false){//逐个循环获取每个字符
    echo $letter;
}
fclose($fhandle);

读取文件指定字符长度:
$fhandle = fopen('../open.txt', 'rb');
echo fread($fhandle, 3);//读取3个字符
echo fread($fhandle, filesize('../open.txt'));//剩余字符绝对小于文件总大小,故可用作剩余内容的

ADODB 类库操作数据库:
include('adodb5/adodb.inc.php');
$db_path = 'data/db_meeting.mdb';
$db = ADONewConnection('access');
$db->Pconnect('Driver={Microsoft Access Driver (*.mdb)};Dbq='.$db_path);
$db->Execute("set names gb2312");
$ADODB_FETCH_MODE = 1; 
$result = $db->SelectLimit($sql, $count, $offset);
$result-> FieldCount();

if(!$result){
    echo $db->ErrorMsg();
}else{
    while(!$result->EOF){  
        $result->fields[1];
    }
      $result->MoveNext();//MoveFirst, MoveLast, Move(10)
}

格式化时间:
 function units($time){
    $year   = floor($time / 60 / 60 / 24 / 365);//当前时间戳,最多有 $year 个整数年
    $time  -= $year * 60 * 60 * 24 * 365;//减$year 年的时间
    $month  = floor($time / 60 / 60 / 24 / 30);//同理向下
    $time  -= $month * 60 * 60 * 24 * 30;
    $week   = floor($time / 60 / 60 / 24 / 7);
    $time  -= $week * 60 * 60 * 24 * 7;
    $day    = floor($time / 60 / 60 / 24);
    $time  -= $day * 60 * 60 * 24;
    $hour   = floor($time / 60 / 60);
    $time  -= $hour * 60 * 60;
    $minute = floor($time / 60);
    $time  -= $minute * 60;
    $second = $time;
    $elapse = '';
    $unitArr = array('年'  =>'year', '个月'=>'month',  '周'=>'week', '天'=>'day','小时'=>'hour', '分钟'=>'minute', '秒'=>'second'
    );

    foreach ( $unitArr as $cn => $u )  {
        if ( $$u > 0 ) {
            $elapse = $$u . $cn;
            break;
        }
    }
    return $elapse;
}

删除数据库中没有记录的图片:
public function delImg($datas, $delDir = '.'){
    $arrExt = array('png','jpg','gif');
    $files = scandir($dir);
    foreach($files as $val){
        $temp = explode('.', $val);
        if(in_array(end($temp),$arrExt)){
            $allFiles[] = $val;
        }
    }
    $delFiles = array_diff($allFiles,$data);
    foreach($delFiles as $val){
        $file = rtrim($dir,'/').'/'.$val;
        unlink($file);echo $file.'<br/>';
    }
 }
posted @ 2013-03-14 23:03  幻星宇  阅读(290)  评论(0编辑  收藏  举报