1. 程式人生 > >php 常用自定義方法

php 常用自定義方法

主要方法有 檢測 ajax 請求 調整影象尺寸 網址字串轉換成超級連結 URL地址預設 http 字串 解壓縮 Zip 檔案 檔案 Zip 壓縮 建立標籤雲 強制性檔案下載 返回字串相似程度的百分比 截斷文字

強制性檔案下載

//      1. PHP強制性檔案下載
function force_download($file)  
{  
    if ((isset($file))&&(file_exists($file))) {  
        header("Content-length: ".filesize($file));  
        header('Content-Type: application/octet-stream');  
        header('Content-Disposition: attachment; filename="' . $file . '"');  
        readfile("$file");  
    } else {  
        echo "No file selected";  
    }  
}  

建立標籤雲

//  2. PHP建立標籤雲
function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )  
{  
    $minimumCount = min( array_values( $data ) );  
    $maximumCount = max( array_values( $data ) );  
    $spread = $maximumCount - $minimumCount;  
    $cloudHTML = '';  
    $cloudTags = array();   
      
    $spread == 0 && $spread = 1;   
  
    foreach( $data as $tag => $count )  
    {  
        $size = $minFontSize + ( $count - $minimumCount )  * ( $maxFontSize - $minFontSize ) / $spread;  
        $cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px' . '" href="#" title="\'' . $tag .  
        '\' returned a count of ' . $count . '">' . htmlspecialchars( stripslashes( $tag ) ) . '</a>';  
    }   
      
    return join( "\n", $cloudTags ) . "\n";  
}  

$arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43,  'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42,  
'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30,  'Extract' => 28, 'Filters' => 42);  

echo getCloud($arr, 12, 36);  

尋找兩個字串的相似性 返回相似程度的百分比


//  3. PHP尋找兩個字串的相似性  返回相似程度的百分比
//    PHP 提供了一個極少使用的 similar_text 函式,但此函式非常有用,用於比較兩個字串並返回相似程度的百分比。
similar_text($string1, $string2, $percent);  
//$percent will have the percentage of similarity  

使用 Gravatar 通用頭像

//  4. PHP在應用程式中使用 Gravatar 通用頭像
//  隨著 WordPress 越來越普及,Gravatar 也隨之流行。由於 Gravatar 提供了易於使用的 API,將其納入應用程式也變得十分方便。
function show_gravatar($email, $size, $default, $rating)  
{  
    echo '<!!!!img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).  
    '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px" height="'.$size.'px" />';  
} 

在字元斷點處截斷文字

//  5. PHP在字元斷點處截斷文字
//  所謂斷字 (word break),即一個單詞可在轉行時斷開的地方。這一函式將在斷字處截斷字串。
// Original PHP code by Chirp Internet: www.chirp.com.au  
// Please acknowledge use of this code by including this header. 
function myTruncate($string, $limit, $break=".", $pad="...") {  
    // return with no change if string is shorter than $limit  
    if(strlen($string) <= $limit)  
    return $string;   
    // is $break present between $limit and the end of the string?  
    if(false !== ($breakpoint = strpos($string, $break, $limit))) {  
        if($breakpoint < strlen($string) - 1) {  
            $string = substr($string, 0, $breakpoint) . $pad;  
        }  
    }  
    return $string;  
}  
 
$short_string=myTruncate($long_string, 100, ' ');  

檔案 Zip 壓縮

//  6. PHP檔案 Zip 壓縮
function create_zip($files = array(),$destination = '',$overwrite = false) {  
    //if the zip file already exists and overwrite is false, return false  
    if(file_exists($destination) && !$overwrite) { return false; }  
    //vars  
    $valid_files = array();  
    //if files were passed in...  
    if(is_array($files)) {  
    //cycle through each file  
        foreach($files as $file) {  
        //make sure the file exists  
            if(file_exists($file)) {  
                $valid_files[] = $file;  
            }  
        }  
    }  
    //if we have good files...  
    if(count($valid_files)) {  
        //create the archive  
        $zip = new ZipArchive();  
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {  
            return false;  
        }  
        //add the files  
        foreach($valid_files as $file) {  
            $zip->addFile($file,$file);  
        }  
        //debug  
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;   
      
        //close the zip -- done!  
        $zip->close();   
      
        //check to make sure the file exists  
        return file_exists($destination);  
    }  
    else  
    {  
        return false;  
    }  
}  
 
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');  
create_zip($files, 'myzipfile.zip', true);  

解壓縮 Zip 檔案

//  7. PHP解壓縮 Zip 檔案
function unzip_file($file, $destination){  
    // create object  
    $zip = new ZipArchive() ;  
    // open archive  
    if ($zip->open($file) !== TRUE) {  
        die ('Could not open archive');  
    }  
    // extract contents to destination directory  
    $zip->extractTo($destination);  
    // close archive  
    $zip->close();  
    echo 'Archive extracted to directory';  
}  

URL 地址預設 http 字串

//  8. PHP為 URL 地址預設 http 字串
if (!preg_match("/^(http|ftp):/", $_POST['url'])) {  
   $_POST['url'] = 'http://'.$_POST['url'];  
}  

URL 和 E-mail 地址字串轉換為可點選的超級連結。

//  9. PHP將網址字串轉換成超級連結
function makeClickableLinks($text) {  
    $text = eregi_replace('(((f|ht){1}tp://)[[email protected]:%_+.~#?&//=]+)', '<a href="\1">\1</a>', $text);  
    $text = eregi_replace('([[:space:]()[{}])(www.[[email protected]:%_+.~#?&//=]+)','\1<a href="http://\2">\2</a>', $text);  
    $text = eregi_replace('([_.0-9a-z-][email protected]([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',  '<a href="mailto:\1">\1</a>', $text);   
    return $text;  
}  

後臺重新定義影象尺寸 方法為阻塞方式 需要許多時間 此程式碼將有助於瞭解縮圖的邏輯。

//  10. PHP調整影象尺寸
function resize_image($filename, $tmpname, $xmax, $ymax) {  
    $ext = explode(".", $filename);  
    $ext = $ext[count($ext)-1];    
  
    if($ext == "jpg" || $ext == "jpeg")  
        $im = imagecreatefromjpeg($tmpname);  
    elseif($ext == "png")  
        $im = imagecreatefrompng($tmpname);  
    elseif($ext == "gif")  
        $im = imagecreatefromgif($tmpname);    
  
    $x = imagesx($im);  
    $y = imagesy($im);    
    
    if($x <= $xmax && $y <= $ymax)  
        return $im;    
    if($x >= $y) {  
        $newx = $xmax;  
        $newy = $newx * $y / $x;  
    } else {  
        $newy = $ymax;  
        $newx = $x / $y * $newy;  
    }    
    $im2 = imagecreatetruecolor($newx, $newy);  
    imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);  
    return $im2;  
}  

檢測 ajax 請求 主要判斷的是頭部資訊 HTTP_X_REQUESTED_WITH == xmlhttprequest

//  11. PHP檢測 ajax 請求

if( !emptyempty($_SERVER['HTTP_X_REQUESTED_WITH'])  && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){  
    //If AJAX Request Then  
}else{  
    //something else  
}