PHP 干货集

利用Mcrypt扩展进行加密、解密字符串

function myCrypt($key,$str){
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES,MCRYPT_MODE_ECB),MCRYPT_RAND);


    return mcrypt_encrypt(MCRYPT_DES,$key,$str, MCRYPT_MODE_ECB,$iv);
}

function myDecrypt($key,$en_str){
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES,MCRYPT_MODE_ECB),MCRYPT_RAND);

    return mcrypt_decrypt(MCRYPT_DES,$key,$en_str, MCRYPT_MODE_ECB,$iv);
}

 

求数组中的最大值:

function getArrayMax($arr) {
    $pos = array_search(max($arr), $arr);
    return $arr[$pos];
}

 

求数组中的最小值:

function getArrayMin($arr) {
    $pos = array_search(min($arr), $arr);
    return $arr[$pos];
}

 

获取距离今天以前的前30天的时间日期格式的数组:

function get30days () {
    $today = date('Y-m-d',strtotime('-1 day'));
    $days = array();
    for($i=1; $i<=30; ++$i) {
        $days[] = date('Y-m-d', strtotime('-'.$i.' day'));
    }
    return $days;
}

 

获取某个月的第一天

function getMonthFirstDay($date) {
    return date('Y-m-01', strtotime($date));
}

获取某个月的最后一天

function getMonthLastDay($date) {
    return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +1 month -1 day'));
}

 

兼容php低版本的array_column()函数

/**
 * array_column() // 不支持低版本;
 * 以下方法兼容PHP低版本
 */
function _array_column(array $array, $column_key, $index_key=null){
    $result = [];
    foreach($array as $arr) {
        if(!is_array($arr)) continue;

        if(is_null($column_key)){
            $value = $arr;
        }else{
            $value = $arr[$column_key];
        }

        if(!is_null($index_key)){
            $key = $arr[$index_key];
            $result[$key] = $value;
        }else{
            $result[] = $value;
        }
    }
    return $result; 
}

 

PHP对象转数组函数, 为什么转数组, PHP数组灵活啊 :)

/**
 * PHP对象(stdClass)转数组
 */
function object_to_array($obj) { 
    $_arr= is_object($obj) ? get_object_vars($obj) : $obj; 
    foreach($_arr as $key=> $val) { 
        $val= (is_array($val) || is_object($val)) ?       object_to_array($val) : $val; 
        $arr[$key] = $val; 
    } 
    return $arr; 
}

 

两个数字数组对应key相加, 两个数组必须长度相同

/**
 * 两个数字数组对应key相加, 两个数组必须长度相同
 * @param  [type] $arr1 [description]
 * @param  [type] $arr2 [description]
 * @return [type]       [description]
 */
private function plus_array($arr1, $arr2) {
    $diff = array();
    //因为长度相同
    foreach($arr1 as $k=>$v) {
        $diff[] = $v+$arr2[$k];
    }
    return $diff;
}

 

两个数字数组对应key相减, 两个数组必须长度相同

/**
 * 两个数字数组对应key相减, 两个数组必须长度相同
 * @param  [type] $arr1 [description]
 * @param  [type] $arr2 [description]
 * @return [type]       [description]
 */
private function minus_array($arr1, $arr2) {
    $diff = array();
    //因为长度相同
    foreach($arr1 as $k=>$v) {
        $diff[] = $v-$arr2[$k];
    }
    return $diff;
}

 

PHP数组转XML格式字符串, 通常在ajax请求, 需要返回xml格式数据时使用!

$xml = simplexml_load_string('<ZellDincht />');
function create($arr, $xml) {
    foreach($arr as $k=>$v) {
        if(is_array($v)) {
            $x = $xml->addChild($k);
            create($v, $x);
        }else $xml->addChild($k, $v);
    }
}
$_username = $_GET['username'];
$_comment = $_GET['content'];
$data = array("username"=>$_username,"comment"=>$_comment);
create($data, $xml);
echo $xml->saveXML();

 

xml字符串转数组

function simplest_xml_to_array($xmlstring) {//$xmlstring是xml字符串
    return json_decode(json_encode((array) simplexml_load_string($xmlstring)), true);
}
$array = simplest_xml_to_array($xml_string);
echo "<pre>";
print_r($array);

 

获取ip地址,这是一个类。摘自zend框架

/**
 * Functionality for determining client IP address.
 */
class RemoteAddress
{
    /**
     * Whether to use proxy addresses or not.
     *
     * As default this setting is disabled - IP address is mostly needed to increase
     * security. HTTP_* are not reliable since can easily be spoofed. It can be enabled
     * just for more flexibility, but if user uses proxy to connect to trusted services
     * it's his/her own risk, only reliable field for IP address is $_SERVER['REMOTE_ADDR'].
     *
     * @var bool
     */
    protected $useProxy = false;

    /**
     * List of trusted proxy IP addresses
     *
     * @var array
     */
    protected $trustedProxies = [];

    /**
     * HTTP header to introspect for proxies
     *
     * @var string
     */
    protected $proxyHeader = 'HTTP_X_FORWARDED_FOR';


    /**
     * Changes proxy handling setting.
     *
     * This must be static method, since validators are recovered automatically
     * at session read, so this is the only way to switch setting.
     *
     * @param  bool  $useProxy Whether to check also proxied IP addresses.
     * @return RemoteAddress
     */
    public function setUseProxy($useProxy = true)
    {
        $this->useProxy = $useProxy;
        return $this;
    }

    /**
     * Checks proxy handling setting.
     *
     * @return bool Current setting value.
     */
    public function getUseProxy()
    {
        return $this->useProxy;
    }

    /**
     * Set list of trusted proxy addresses
     *
     * @param  array $trustedProxies
     * @return RemoteAddress
     */
    public function setTrustedProxies(array $trustedProxies)
    {
        $this->trustedProxies = $trustedProxies;
        return $this;
    }

    /**
     * Set the header to introspect for proxy IPs
     *
     * @param  string $header
     * @return RemoteAddress
     */
    public function setProxyHeader($header = 'X-Forwarded-For')
    {
        $this->proxyHeader = $this->normalizeProxyHeader($header);
        return $this;
    }

    /**
     * Returns client IP address.
     *
     * @return string IP address.
     */
    public function getIpAddress()
    {
        $ip = $this->getIpAddressFromProxy();
        if ($ip) {
            return $ip;
        }

        // direct IP address
        if (isset($_SERVER['REMOTE_ADDR'])) {
            return $_SERVER['REMOTE_ADDR'];
        }

        return '';
    }

    /**
     * Attempt to get the IP address for a proxied client
     *
     * @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2
     * @return false|string
     */
    protected function getIpAddressFromProxy()
    {
        if (!$this->useProxy
            || (isset($_SERVER['REMOTE_ADDR']) && !in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies))
        ) {
            return false;
        }

        $header = $this->proxyHeader;
        if (!isset($_SERVER[$header]) || empty($_SERVER[$header])) {
            return false;
        }

        // Extract IPs
        $ips = explode(',', $_SERVER[$header]);
        // trim, so we can compare against trusted proxies properly
        $ips = array_map('trim', $ips);
        // remove trusted proxy IPs
        $ips = array_diff($ips, $this->trustedProxies);

        // Any left?
        if (empty($ips)) {
            return false;
        }

        // Since we've removed any known, trusted proxy servers, the right-most
        // address represents the first IP we do not know about -- i.e., we do
        // not know if it is a proxy server, or a client. As such, we treat it
        // as the originating IP.
        // @see http://en.wikipedia.org/wiki/X-Forwarded-For
        $ip = array_pop($ips);
        return $ip;
    }

    /**
     * Normalize a header string
     *
     * Normalizes a header string to a format that is compatible with
     * $_SERVER
     *
     * @param  string $header
     * @return string
     */
    protected function normalizeProxyHeader($header)
    {
        $header = strtoupper($header);
        $header = str_replace('-', '_', $header);
        if (0 !== strpos($header, 'HTTP_')) {
            $header = 'HTTP_' . $header;
        }
        return $header;
    }
}

 

//邮箱验证

/^\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*$/

 

// 二维数组根据某个字段进行排序

/**
 * 根据某个字段进行排序
 * @param  [array] $list   [操作数组]
 * @param  [string] $field  [字段名称]
 * @param  string $sortby [操作顺序]
 * @return [type]         [排序后的数组]
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
    if (is_array($list))
    {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
        {
            $refer[$i] = &$data[$field];
        }
        switch ($sortby)
        {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc': // 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
        {
            $resultSet[] = &$list[$key];
        }
        return $resultSet;
    }
    return false;
}

 

/**
 * [判断文件的mine类型]
 * @param  [string] $filename [页面路径]
 * @return [string]           [mime类型和字符集]
 */
function get_mime($filename) {
    $finfo = finfo_open(FILEINFO_MIME);
    $mimetype = finfo_file($finfo, $filename);
    finfo_close($finfo);
    return $mimetype;   
}

 

/**
 * download files
 * $file_path : the file to download
 * $out_filename: 下载显示的文件名称
 */
function _download($file_path,$out_filename="download.log") {
    if(is_file($file_path)) {
        $file = fopen($file_path, "r"); // 打开文件
        if($file) {
            // 输入文件标签
            $out_filename = str_replace(pathinfo($out_filename,PATHINFO_EXTENSION),'',$out_filename).date("Y.m.d.His").'.'.pathinfo($out_filename,PATHINFO_EXTENSION);
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            header('Content-Transfer-Encoding: binary');
            Header("Accept-Length: ".filesize($file_path));
            //rename
            Header("Content-Disposition: attachment;filename=".$out_filename);
            // 输出文件内容
            echo fread($file, filesize($file_path));
            fclose($file);
            exit();     
        }  
    }
}
/** 
 * js escape php 实现 
 * @param $string           the sting want to be escaped 
 * @param $in_encoding       
 * @param $out_encoding      
 */ 
if( ! function_exists('escape')) {
    function escape($string, $in_encoding = 'UTF-8',$out_encoding = 'UCS-2') { 
        $return = ''; 
        if (function_exists('mb_get_info')) { 
            for($x = 0; $x < mb_strlen ( $string, $in_encoding ); $x ++) { 
                $str = mb_substr ( $string, $x, 1, $in_encoding ); 
                if (strlen ( $str ) > 1) { // 多字节字符 
                    $return .= '%u' . strtoupper ( bin2hex ( mb_convert_encoding ( $str, $out_encoding, $in_encoding ) ) ); 
                } else { 
                    $return .= '%' . strtoupper ( bin2hex ( $str ) ); 
                } 
            } 
        } 
        return $return; 
    }    
}

/**
 * PHP实现javascript的unescape函数
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
if( ! function_exists('unescape')) {
    function unescape($str) { 
        $ret = ''; 
        $len = strlen($str); 
        for ($i = 0; $i < $len; $i ++) { 
            if ($str[$i] == '%' && $str[$i + 1] == 'u') { 
                $val = hexdec(substr($str, $i + 2, 4)); 
                if ($val < 0x7f) {
                    $ret .= chr($val); 
                } else {
                    if ($val < 0x800) {
                        $ret .= chr(0xc0 | ($val >> 6)) . 
                         chr(0x80 | ($val & 0x3f)); 
                    } else {
                        $ret .= chr(0xe0 | ($val >> 12)) . 
                        chr(0x80 | (($val >> 6) & 0x3f)) . 
                        chr(0x80 | ($val & 0x3f));
                    }
                    $i += 5;
                }
            } else  {
                if ($str[$i] == '%') { 
                    $ret .= urldecode(substr($str, $i, 3)); 
                    $i += 2; 
                } else {
                    $ret .= $str[$i]; 
                }
            }
        } 
        return $ret; 
    }    
}

 

以下是几个常用正则:

/**
 * 判断 国际电话是否OK
 * @param  [type]  $phone [description]
 * @return boolean        [description]
 */
function is_internationalphonenumber($phone) {
    $reg = "/^\s*(?:\+?(\d{1,3}))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/im";
    if( preg_match($reg, $phone) ) {
        return true;
    } else {
        return false;
    }
}

//匹配中英文、数字、下划线
//注意模式修正符 u, 有这个才能匹配正确。
function check_mix_cn($str) {

  $regex = "/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_——]{1,30}$/iu";//匹配中文,英文大小写字母、数字、下划线
  $r = preg_match($regex, $name);
  return $r!==false && $r>0 ? true : false;

}

/**
 * 匹配Html标签
 * <a href="http://net.tutsplus.com/">Nettuts+</a>
 * <img src="img.jpg" alt="My image" /> 
 * @param  [type]  $html [description]
 * @return boolean       [description]
 */
function is_htmltag($html) {
    $reg = "/^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/";
    if(preg_match($reg, $html)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 判断用户名是否正确
 * my-us3r_n4m3
 * h1s1s-wayt00_l0ngt0beausername (too long)
 * @param  [type]  $username [description]
 * @return boolean           [description]
 */
function is_username($username) {
    $reg = "/^[a-z0-9_-]{3,16}$/";
    if(preg_match($reg, $username)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 判断是否是合格的密码
 * myp4ssw0rd
 * mypa$$w0rd (contains a dollar sign)
 * @param  [type]  $password [description]
 * @return boolean           [description]
 */
function is_password($password) {
    $reg = "/^[a-z0-9_-]{6,18}$/";
    if(preg_match($reg, $password)) {
        return true;
    }else{
        return false;
    }
}

/**
 * is Hex Value
 * #a3c113    right
 * #4d82h4 (contains the letter h)    wrong
 * @param  [type]  $hex_value [description]
 * @return boolean            [description]
 */
function is_hexvalue($hex_value) {
    $reg = "/^#?([a-f0-9]{6}|[a-f0-9]{3})$/";
    if(preg_match($reg, $hex_value)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 判断是否是 slug --- slug 指形如: word1-word2-word3-word4 格式的字符串
 * my-title-here
 * my_title_here (contains underscores)   wrong
 * @param  [type]  $slug [description]
 * @return boolean       [description]
 */
function is_slug($slug) {
    $reg = "/^[a-z0-9-]+$/";
    if(preg_match($reg, $slug)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 验证IP地址
 * 73.60.124.136 (no, that is not my IP address :P)
 * 256.60.124.136 (the first group must be "25" and a number between zero and five)  wrong
 * @param  [type]  $ip [description]
 * @return boolean     [description]
 */
function is_ip($ip) {
    $reg = "/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/";
    if(preg_match($reg, $ip)) {
        return true;
    }else{
        return false;
    }
}

/**
 * 验证邮箱email
 * john@doe.com   right
 * john@doe.something (TLD is too long)    wrong
 */
function is_email($email) {
    $reg = "/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/i";
    if( preg_match($reg, $email) ) {
        return true;
    }else{
        return false;
    }
}

/**
 * 验证url地址格式
 * http://net.tutsplus.com/about    right
 * http://google.com/some/file!.html (contains an exclamation point)
 */
function is_url($url) {
    $reg = "/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/i";
    if(preg_match($reg, $url)) {
        return true;
    } else {
        return false;
    }
}

 

/**
 * 获取IP地址对应的城市
 * @param  [ip string] $ip [description]
 * @return [type]     [description]
 */
if( ! function_exists('get_cityname_by_ip')) {
    function get_city_by_ip($ip){  
        $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$ip;
        $res = @file_get_contents($url);
        if($res === false) {
            $ch = curl_init();
            $timeout = 30;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $res = curl_exec($ch);
            curl_close($ch);
        }
        return json_decode($res,true);
    }    
}
/**
 * 根据某个字段进行排序
 * @param  [array] $list   [操作数组]
 * @param  [string] $field  [字段名称]
 * @param  string $sortby [操作顺序]
 * @return [type]         [排序后的数组]
 */
if( ! function_exists('list_sort_by_column')) {
    function list_sort_by_column($list, $field, $sortby = 'asc')
    {
        if (is_array($list))
        {
            $refer = $resultSet = array();
            foreach ($list as $i => $data)
            {
                $refer[$i] = &$data[$field];
            }
            switch ($sortby)
            {
                case 'asc': // 正向排序
                    asort($refer);
                    break;
                case 'desc': // 逆向排序
                    arsort($refer);
                    break;
                case 'nat': // 自然排序
                    natcasesort($refer);
                    break;
            }
            foreach ($refer as $key => $val)
            {
                $resultSet[] = &$list[$key];
            }
            return $resultSet;
        }
        return false;
    }    
}

 

/**
 * 创建多级目录函数
 */
if( ! function_exists('mk_dirs')) 
{
    function mk_dirs($dir, $mode=0777) {
        if(is_dir($dir) || @mkdir($dir, $mode)){
            return true;
        }
        if(!mk_dirs(dirname($dir), $mode)){
            return false;
        }
        return @mkdir($dir, $mode);
    }
}

 

但从数据库中获取的数据量不多时,或者获取的数据量有一定数量限制,往往这些数据可以被缓存起来。那么我们在操作的时候,将这些数据缓存为数组,然后分页操作时

我们针对数组进行操作,下面是根据数据进行的分页

/**
 * 给定数组,根据页码进行数组分页操作
 * 
 * @param  [type] $arr     [给定的数组]
 * @param  [type] $p_start [页码]
 * @param  [type] $p_limit [每页显示行数]
 * @return [type]          [要取出的数组]
 */
if( ! function_exists('get_page_array')) 
{
    function get_page_array($arr, $p_start, $p_limit) {
        return array_slice($arr, ($p_start-1)*$p_limit, $p_limit);
    }
}

 

if ( ! function_exists('byte_format'))
{
    /**
   * 改自 CodeIgniter 框架 * Formats a numbers as bytes, based on size, and adds the appropriate suffix * * @param mixed 数字,或者数字型的字符串 * @param int 会保留的小数位 * @return string 返回一个格式化之后的(带单位的)字符串
*/ function byte_format($num, $precision = 1) { $lang['terabyte_abbr'] = 'TB'; $lang['gigabyte_abbr'] = 'GB'; $lang['megabyte_abbr'] = 'MB'; $lang['kilobyte_abbr'] = 'KB'; $lang['bytes'] = 'Bytes'; if ($num >= 1000000000000) { $num = round($num / 1099511627776, $precision); $unit = $lang['terabyte_abbr']; } elseif ($num >= 1000000000) { $num = round($num / 1073741824, $precision); $unit = $lang['gigabyte_abbr']; } elseif ($num >= 1000000) { $num = round($num / 1048576, $precision); $unit = $lang['megabyte_abbr']; } elseif ($num >= 1000) { $num = round($num / 1024, $precision); $unit = $lang['kilobyte_abbr']; } else { $unit = $lang['bytes']; return number_format($num).' '.$unit; } return number_format($num, $precision).' '.$unit; } }

 

// 获取客户端浏览器信息和系统信息

function getBrowser() { 
    $u_agent = $_SERVER['HTTP_USER_AGENT']; 
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version = "";
    
    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
       $platform = 'linux';
    }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
       $platform = 'mac';
    }elseif (preg_match('/windows|win32/i', $u_agent)) {
       $platform = 'windows';
    }
    
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) {
       $bname = 'Internet Explorer';
       $ub = "MSIE";
    } elseif(preg_match('/Firefox/i',$u_agent)) {
       $bname = 'Mozilla Firefox';
       $ub = "Firefox";
    } elseif(preg_match('/Chrome/i',$u_agent)) {
       $bname = 'Google Chrome';
       $ub = "Chrome";
    }elseif(preg_match('/Safari/i',$u_agent)) {
       $bname = 'Apple Safari';
       $ub = "Safari";
    }elseif(preg_match('/Opera/i',$u_agent)) {
       $bname = 'Opera';
       $ub = "Opera";
    }elseif(preg_match('/Netscape/i',$u_agent)) {
       $bname = 'Netscape';
       $ub = "Netscape";
    }
    
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    
    if (!preg_match_all($pattern, $u_agent, $matches)) {
       // we have no matching number just continue
    }
    
    // see how many we have
    $i = count($matches['browser']);
    
    if ($i != 1) {
       //we will have two since we are not using 'other' argument yet
       
       //see if version is before or after the name
       if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
          $version= $matches['version'][0];
       }else {
          $version= $matches['version'][1];
       }
    }else {
       $version= $matches['version'][0];
    }
    
    // check if we have a number
    if ($version == null || $version == "") {$version = "?";}
    return array(
       'userAgent' => $u_agent,
       'name'      => $bname,
       'version'   => $version,
       'platform'  => $platform,
       'pattern'   => $pattern
    );
}
$ua = getBrowser();
echo '<pre>';
print_r($ua);

 

随机显示图片:

当用户访问站点时,每次访问所得的图片不同,下面是简单的PHP实现方法。

srand( microtime() * 1000000 );
$num = rand( 1, 4 );

switch( $num ) {
    case 1: $image_file = "/php/images/logo.png";
       break;

    case 2: $image_file = "/php/images/php.jpg";
       break;

    case 3: $image_file = "/php/images/logo.png";
       break;

    case 4: $image_file = "/php/images/php.jpg";
       break;
}
echo "Random Image : <img src=$image_file />"; 

 

获取指定文件的后缀名。

// 获取后缀名的方法
$filename = 'htmls/a-b-c.124.165-17956.zelldincht.php';
// one
$array = explode('.', $filename);
$ext = end($array);
echo $ext.'<br>';
// two
$ext = pathinfo($filename, PATHINFO_EXTENSION);
echo $ext.'<br>';
// three
$ext = substr($filename, strrpos($filename, '.')+1);
echo $ext.'<br>';
// four
$ext = array_pop($array);
echo $ext.'<br>';
// five
$ext = substr(strrchr($filename, '.'),1);
echo $ext.'<br>';
// 以上方法中的第一种是最简方法,所以封装一个自定义函数

 function get_suffix($filename) {
   return pathinfo($filename, PATHINFO_EXTENSION);
 }

 

处理文件上传的过程中,错误信息不好处理,所以这里有一个类专门处理错误信息的-来源手册!

<?php 

class UploadException extends Exception 
{ 
    public function __construct($code) { 
        $message = $this->codeToMessage($code); 
        parent::__construct($message, $code); 
    } 

    private function codeToMessage($code) 
    { 
        switch ($code) { 
            case UPLOAD_ERR_INI_SIZE: 
                $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
                break; 
            case UPLOAD_ERR_FORM_SIZE: 
                $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
                break; 
            case UPLOAD_ERR_PARTIAL: 
                $message = "The uploaded file was only partially uploaded"; 
                break; 
            case UPLOAD_ERR_NO_FILE: 
                $message = "No file was uploaded"; 
                break; 
            case UPLOAD_ERR_NO_TMP_DIR: 
                $message = "Missing a temporary folder"; 
                break; 
            case UPLOAD_ERR_CANT_WRITE: 
                $message = "Failed to write file to disk"; 
                break; 
            case UPLOAD_ERR_EXTENSION: 
                $message = "File upload stopped by extension"; 
                break; 

            default: 
                $message = "Unknown upload error"; 
                break; 
        } 
        return $message; 
    } 
} 

// Use 
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { 
//uploading successfully done 
} else { 
throw new UploadException($_FILES['file']['error']); 
} 
?>

 

实用的上传处理代码示例(手册), 看了豁然开朗!

<?php 
$error_types = array(   

  0 => 'There is no error, the file uploaded with success',
  1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
  2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
  3 => 'The uploaded file was only partially uploaded',
  4 => 'No file was uploaded',
  6 => 'Missing a temporary folder',
  7 => 'Failed to write file to disk.',
  8 => 'A PHP extension stopped the file upload.',

); 

// Outside a loop... 
if($_FILES['userfile']['error']==0) { 
  // process 
} else { 
  $error_message = $error_types[$_FILES['userfile']['error']]; 
  // do whatever with the error message 
} 

// In a loop... 
for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) { 
  if($_FILES['userfile']['error'][$x]==0) { 
    // process 
  } else { 
    $error_message = $error_types[$_FILES['userfile']['error'][$x]]; 
    // Do whatever with the error message 
  } 
} 

// When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory 
unset($error_types); 

 

无限级分类中使用到的数组操作:

/**
 * 无限级分类
 * 当前台调用无限级分类的时候需要做缓存,减低数据库的压力和开销
 */
class Category{
    //组合多维数组
    Static Public function unlimitedForLayer($cate, $name = "child", $pid = 0){
        $arr = array();
        foreach($cate as $v){
            if($v["pid"] == $pid){
                $v[$name] = self::unlimitedForLayer($cate, $name="child", $v['id']);
                $arr[] = $v;
            }
        }
        return $arr;
    }
    //组合一位数组
    Static Public function unlimitedForLevel ($cate, $html = ' ┖&nbsp;', $pid = 0, $level = 0){
        $arr = array();
        foreach($cate as $v){
            if($v['pid'] == $pid){
                $v['level'] = $level + 1;
                $v['html'] = str_repeat($html, $level);
                $arr[] = $v;
                $arr = array_merge($arr, self::unlimitedForLevel($cate, $html, $v['id'], $level +1));
            }
        }
        return $arr;
    }
    //传递一个子类id找父类
    Static Public function getParent($cate,$id){
        $arr = array();
        foreach($cate as $v) {
            if($v["id"] == $id){
                $arr[] = $v;
                $arr = array_merge(self::getParent($cate,$v["pid"]),$arr);
            }
        }
        return $arr;
    }
    //传递一个父级ID返回所有的子级ID
    Static Public function getChildrenId($cate, $pid=0){
        $arr = array();
        foreach($cate as $v){
            if($v['pid'] == $pid){
                $arr[] = $v['id'];
                $arr = array_merge(self::getChildrenId($cate, $v["id"]),$arr);
            }
        }
        return $arr;
    }
    //传递一个父级ID返回所有子级分类
    Static Public function getChildren($cate, $pid=0){
        $arr = array();
        foreach($cate as $v){
            if($pid == $v['pid']){
                $arr[] = $v;
                $arr = array_merge($arr,self::getchildren($cate, $v['id']));
            }
        }
        return $arr;
    }
}

 

posted @ 2015-06-26 16:19  Zell~Dincht  阅读(373)  评论(0)    收藏  举报