PHP 小代碼

來源:互聯網
上載者:User
//擷取網上的一個檔案function getUrlImage($url, $file = '', $maxExe = 0, $safe = false){    $urlExt = explode('.', $url);    $fileExt = array('txt','jpg','gif','png');    if(!in_array(end($urlExt), $fileExt, true)) return false;    $file = ($file)? $file.$urlExt : basename($url);    $file = rand(1,1000).$file;    ob_start(); //開啟輸出緩衝    set_time_limit($maxExe); //開啟最大已耗用時間    readfile($url);//讀入一個檔案並寫入到輸出緩衝    $data = ob_get_contents();    ob_end_clean();    file_put_contents($file,$data);    if($safe && is_executable($file)){//為安全起見,判定一下檔案是否可執行        unlink($file);        return false;    }    return $file;}getUrlImage('http://www.test.com/3675.jpg','newName');//批量產生cookiefunction 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);}//PHP驗證email格式function checkEmail($email){    $pattern = "/([a-z0-9]*[-_/.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[/.][a-z]{2,3}([/.][a-z]{2})?/i";    return preg_match($pattern,$email); }//檔案上傳$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: $nextMonday = $time+86400;break;//星期天則加一天    case 1: $nextMonday = $time+7*86400;break;//星期一,則加七天    case 2: $nextMonday = $time+6*86400;break;    case 3: $nextMonday = $time+5*86400;break;    case 4: $nextMonday = $time+4*86400;break;    case 5: $nextMonday = $time+3*86400;break;    case 6: $nextMonday = $time+2*86400;break;}echo date('Y-m-d',$nextMonday);//逐行讀取檔案指定行數的內容:function getRowData($file, $row = 0, mark = false){    $fhandle = fopen($file,'rb');    $row = ($row == 0)? filesize($file) : $row;    while($row >0 && !feof($fhandle)){       $data[] = (mark)? fgets($fhandle) : fgetss($fhandle);       $row--;    }    fclose($fhandle);}//讀取檔案指定字元長度function getLetterData($file, $num = 0, mark = false){    $fhandle = fopen($file,'rb');    $row = ($num)? filesize($file) : $num;    $data = fread($fhandle, $num);    fclose($fhandle);}//刪除目錄中在資料庫中沒有記錄的圖片public function delImg($data, $dir = '.'){    $files = scandir($dir);    $delFiles = array_diff($allFiles,$data);    foreach($delFiles as $name){        $file = rtrim($dir,'/').'/'.$name;        unlink($file);        echo $file.'
'; }}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.