php常用函数
#删除不为空的目录 function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); } } reset($objects); rmdir($dir); } }
#批量创建目录function MakeDirectory($dir, $mode = 0755) { umask(0); if (is_dir($dir) || @mkdir($dir,$mode)) return TRUE; if (!MakeDirectory(dirname($dir),$mode)) return FALSE; return @mkdir($dir,$mode); }
#批量创建目录 function recursive_mkdir($path, $mode = 0777) { $dirs = explode(DIRECTORY_SEPARATOR , $path); $count = count($dirs); $path = substr($path, 0, 1) === DIRECTORY_SEPARATOR ? DIRECTORY_SEPARATOR : '.'; umask(0); for ($i = 0; $i < $count; ++$i) { $path .= DIRECTORY_SEPARATOR . $dirs[$i]; if (!is_dir($path) && !mkdir($path, $mode)) { return false; } } return true; }
/** * 判断是否是合法整形 加强版 * @param unknown_type $a * @return boolean */ function is_intval($a) { return ((string)$a === (string)(int)$a); } // true for ("123", "0", "-1", 0, 11, 9011, 00, 0x12, true) // false for (" ", "", 1.1, "123.1", "00", "0x123", "123a", "ada", "--1", "999999999999999999999999999999999", false, null, '1 ')
/** * 多进程同时写入一个文件 不支持NFS文件系统 * @param string $filename * @param string $str */ function write($filename, $str) { $f = fopen ( $filename, "a" ); if (flock ( $f, LOCK_EX )) { fwrite ( $f, $str ); //sleep(5); flock ( $f, LOCK_UN ); } fclose ( $f ); } write("/home/v_jksong/lock.data", "sjk");
/** * 检测一维数组是否相等,如果(string)$v1 === (string)$v2 则为相等 * @param unknown_type $a * @param unknown_type $b * @param unknown_type $assoc * @return boolean */ function array_equal($a, $b, $assoc = true) { $func = 'array_diff'; if($assoc === true) { $func = 'array_diff_assoc'; } $diff_a_b = $func($a, $b); $diff_b_a = $func($b, $a); if(empty($diff_a_b) && empty($diff_b_a)) { return true; } return false; }
//解析 js中escap编码的字符串 function js_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; } echo js_unescape('%u4E03%u5915%u628A%u59B9%u5FC5%u5907%20%u56DB%u6B3ESUV%u6700%u9AD8%u964D6.5%u4E07_%u5927%u7CA4%u7F51_%u817E%u8BAF%u7F51');
/** * 获取ip地址,注意服务器是双网卡的情况 * @param unknown_type $dest * @param unknown_type $port * @return unknown */ function my_ip($dest='64.0.0.0', $port=80) { $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_connect($socket, $dest, $port); socket_getsockname($socket, $addr, $port); socket_close($socket); return $addr; }
/** * 用以取代file_get_contents函数,可以设置主机名以及超时时间等设置 * @param $url 主机名 * @param $path 路径 * @param $port=80 端口 * @param $timeout=10 超时设置,单位秒 * @return integer/string -1:连接不上主机 -2:发送请求串失败 */ function get_file_contents($url,$path,$port=80,$timeout=10) { $errno=null; $errstr=null; $fp=fsockopen($url,$port); if(!$fp) { return -1; } $command='GET '.$path.' HTTP/1.1'."\r\n"; $command.='Accept: */*'."\r\n"; $command.='Accept-Language: zh-cn'."\r\n"; $command.='Host: '.$url."\r\n"; $command.='Connection: Close'."\r\n"; $command.="\r\n"; $flag=fwrite($fp,$command); if(!$flag) { fclose($fp); return -2; } stream_set_timeout($fp,$timeout); $tmp_ret_str=""; $flag=false; while(!feof($fp)) { $tmp_cur_line=fgets($fp,2048); if($flag) { $tmp_ret_str.=$tmp_cur_line; } if($tmp_cur_line=="\r\n") { $flag=true; } } fclose($fp); return $tmp_ret_str; }
/** * URL取得相应数据的函数 * * @param string $url 完整URL * @param int $timeout 超时时间 * @return string/errorno */ function get_url_contents($url,$timeout=10) { $command='wget --timeout '.$timeout.' -q -O- "'.$url.'"'; $tmp_ret_str=''; $fp=popen($command,"r"); if($fp==false) { return -1; } while(!feof($fp)) { $tmp_ret_str.=fgets($fp); } pclose($fp); return $tmp_ret_str; }
/** * 获取当前内存情况 * @return string */ function memory_usage($isEcho = 0) { $memUsage = memory_get_usage(); $unitArr = array("B", "K", "M", "G"); $used = @round($memUsage/pow(1024, ($i=floor(log($memUsage, 1024)))), 2)."".($unitArr[$i]); if($isEcho) { ee($used); } return $used; }
/** * Unwind the error handler to the built-in error handler. */ function unset_error_handler() { while (set_error_handler(create_function('$errno,$errstr', 'return false;'))) { // Unset the error handler we just set. restore_error_handler(); // Unset the previous error handler. restore_error_handler(); } // Restore the built-in error handler. restore_error_handler(); }
/** * 通过curl方式获取远程的数据 * @param string $url @notice--查询字符串--请求远程地址 GET方式请求的数据必须把相关数据封装成数组 * @param array $params 请求时所需要的参数 * @param string $method 请求的方法 * @param string $timeout超时时间 * @return 根据$json array string */ function http_request($url, $params=array(), $method='GET',$json=TRUE, $timeout = 3, $host_ip = NULL) { global $_CONFIG; $ch = curl_init(); $method = strtoupper($method); //Force Curl Request To Go To A Particular IP Address if (! is_null ( $host_ip )) { $urldata = parse_url ( $url ); // Ensure we have the query too, if there is any... if (! empty ( $urldata ['query'] )) $urldata ['path'] .= "?" . $urldata ['query']; // Specify the host (name) we want to fetch... $headers = array ( "Host: " . $urldata ['host'] ); curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers ); // create the connecting url (with the hostname replaced by IP) $url = $urldata ['scheme'] . "://" . $host_ip . $urldata ['path']; } switch ($method) { case 'GET': if(FALSE!==strpos($url,'?')) { $str_add = '&'; }else{ $str_add = '?'; } $url .= $str_add.http_build_query($params); curl_setopt($ch, CURLOPT_URL, $url); break; case 'POST': curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); break; default: break; } if(defined('ISDEV') && ISDEV) { curl_setopt ( $ch, CURLOPT_PROXY, "{$_CONFIG['proxy']['web']['host']}:{$_CONFIG['proxy']['web']['port']}" ); } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $content = curl_exec($ch); curl_close($ch); if($json) { return json_decode($content, true); } else { return $content; } }
/** * ping * @param unknown $host * @param number $timeout * @return Ambigous <number, boolean> */ function ping($host, $timeout = 1) { /* ICMP ping packet with a pre-calculated checksum */ $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost"; $socket = socket_create(AF_INET, SOCK_RAW, 1); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0)); socket_connect($socket, $host, null); $ts = microtime(true); socket_send($socket, $package, strLen($package), 0); if (socket_read($socket, 255)) $result = microtime(true) - $ts; else $result = false; socket_close($socket); return $result; }
/** * 随机并保留key
* http://php.net/manual/zh/function.shuffle.php */ function shuffle_assoc($list) { if (!is_array($list)) return $list; $keys = array_keys($list); shuffle($keys); $random = array(); foreach ($keys as $key) $random[$key] = $list[$key]; return $random; }
function curl_file_get_contents( $url ,$timeout=60, $curlHost='', $cookie='', $post='',$head='',$postJson='',$send_ref='' ) { $ch = curl_init($url) ; if( $timeout >= 1 ) { curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); } elseif( $timeout > 0 && $timeout < 1 ) { /** The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm. The solution is to disable signals using CURLOPT_NOSIGNAL. Here's an example script that requests itself causing a 10-second delay so you can test timeouts: http://php.net/manual/zh/function.curl-setopt.php#104597 */ curl_setopt($ch, CURLOPT_NOSIGNAL, 1); curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout*1000 ); } curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if( !empty($curlHost) && is_array($curlHost) ) { curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHost) ; } if( strlen($cookie) > 10 ) { curl_setopt($ch, CURLOPT_COOKIE, $cookie); } if( is_array($post) && count($post) > 0 ) { /** * 传递一个数组到CURLOPT_POSTFIELDS,cURL会把数据编码成 multipart/form-data,而然传递一个URL-encoded字符串时,数据会被编码成 application/x-www-form-urlencoded。 */ curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); } if( $head === 'yes' ) { curl_setopt($ch, CURLOPT_HEADER, 1); } if( strlen($postJson) > 3 ) { // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postJson); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($postJson) ) ); } if( strlen($send_ref) > 0 ) { curl_setopt($ch, CURLOPT_REFERER, $send_ref); } $str = curl_exec($ch); $error = curl_errno($ch); ee("errno = {$error}"); if( intval( $error ) != 0 ) { $msg = "errno_{$error};url={$url}"; ee($msg); } if ($str !== false) { curl_close($ch); return $str; } curl_close($ch); return "" ; }
/** * 一种常用的hash算法 * @param string $str * @return number */ function hash33($str) { if(empty($str)) return 0; $hash = 0; $seed = 5; $len = strlen($str); for ($i = 0; $i < $len; $i=$i+1) { $hash = ($hash << $seed) + $hash + ord($str{$i}); $hash = $hash & 0x7FFFFFFF; } return $hash; }