目錄php
https://pan.baidu.com/s/18ZuQm5cx3ynQtQqcQgK0Vwhtml
header("Content-Type: text/html;charset=utf-8");
java
echo iconv('GB2312', 'UTF-8//IGNORE', $str); //將字符串的編碼從GB2312轉到UTF-8 //ignore的意思是忽略轉換時的錯誤,若是沒有ignore參數,全部該字符後面的字符串都沒法被保存。 iconv("UTF-8","GB2312//IGNORE",$data); print_r(iconv_get_encoding()); //獲得當前頁面編碼信息 // 轉碼 function gbk($str){return iconv('utf-8','gbk',$str);} function utf8($str){return iconv('gbk','utf-8',$str);}
function path_formate($str){ return str_replace('\\\\','\\',$str); }
方法一: define('BASE_PATH',rtrim(str_replace('\\','/',__DIR__).'/')); 方法二: define('BASE_DIR', rtrim(str_replace('\\', '/', dirname(__FILE__)),'/').'/');
function dump($var) { echo '<pre>'; print_r($var); echo '</pre>'; } function vp($var) { echo '<pre>'; var_dump($var); echo '</pre>'; } function dd($var) { echo '<pre>'; var_dump($var); echo '</pre>'; die; }
/** * 數據返回 * @param [int] $code [結果碼 200:正常/4**數據問題/5**服務器問題] * @param [string] $msg [返回的提示信息] * @param [array] $data [返回的數據] * @return [string] [最終的json數據] */ public function return_msg($code, $msg = '', $data = []) { /*********** 組合數據 ***********/ $return_data['code'] = $code; $return_data['msg'] = $msg; $return_data['data'] = $data; /*********** 返回信息並終止腳本 ***********/ echo json_encode($return_data,JSON_UNESCAPED_UNICODE); die; }
在公共的common.php中sql
//字符串截取而且超出顯示省略號 function subtext($text, $length) { if(mb_strlen($text, ‘utf8’) > $length) return mb_substr($text,0,$length,’utf8′).’ …’; return $text; }
在模版中調用則:
{$tops.title | subtext=18}thinkphp
在公共的common.php中json
//字符串截取 function cut_str($sourcestr,$cutlength) { $returnstr=''; $i=0; $n=0; $str_length=strlen($sourcestr);//字符串的字節數 while (($n<$cutlength) and ($i<=$str_length)) { $temp_str=substr($sourcestr,$i,1); $ascnum=Ord($temp_str);//獲得字符串中第$i位字符的ascii碼 if ($ascnum>=224) //若是ASCII位高與224, { $returnstr=$returnstr.substr($sourcestr,$i,3); //根據UTF-8編碼規範,將3個連續的字符計爲單個字符 $i=$i+3; //實際Byte計爲3 $n++; //字串長度計1 } elseif ($ascnum>=192) //若是ASCII位高與192, { $returnstr=$returnstr.substr($sourcestr,$i,2); //根據UTF-8編碼規範,將2個連續的字符計爲單個字符 $i=$i+2; //實際Byte計爲2 $n++; //字串長度計1 } elseif ($ascnum>=65 && $ascnum<=90) //若是是大寫字母, { $returnstr=$returnstr.substr($sourcestr,$i,1); $i=$i+1; //實際的Byte數仍計1個 $n++; //但考慮總體美觀,大寫字母計成一個高位字符 } else //其餘狀況下,包括小寫字母和半角標點符號, { $returnstr=$returnstr.substr($sourcestr,$i,1); $i=$i+1; //實際的Byte數計1個 $n=$n+0.5; //小寫字母和半角標點等與半個高位字符寬... } } if ($str_length>$i){ $returnstr = $returnstr . "...";//超過長度時在尾處加上省略號 } return $returnstr; }
在模版中調用則:
{$brand.brand_description|cut_str=###,10}api
/** * priceFormat * 格式處理 由分單位轉換成元(保留2爲小數) * * @access public * @param null * @since 1.0 * @price 錢數 * @price 保留小數點後幾位 * @return object */ if(!function_exists('priceFormat')) { function priceFormat($price,$decimals=2) { // number_format(須要轉換的數字,保留小數個數,小數點符號,每三位的分隔符) // echo number_format("1000000")."<br>"; //默認顯示:1,000,000 // echo number_format("1000000",2)."<br>";//默認顯示:1,000,000.00 // echo number_format("1000000",2,".",""); //自定義顯示:1000000.00 return number_format($price/100,$decimals); } }
function changestr($string){ if(!is_string($string)){ die('please input string.'); } if(strpos($string,'_')){ $stringArr=explode('_',$string); $str=''; foreach ($stringArr as $v){ $str .= ucfirst($v); } return $str; } }
/** * 對象 轉 數組 * * @param object $obj 對象 * @return array */ function object2array(&$object) { $object = json_decode( json_encode( $object),true); return $object; } /****對象轉json數組格式的字符串*****/ function obj2arr($object) { $json_object = json_encode($object); echo "<pre>"; var_dump($json_object);die; $arr = json_decode($json_object, 1); return $arr; } /****json轉數組*****/ /** * [json_to_arr description] json_to_arr 遍歷把json轉爲數組 * @param [type] $jsonstr [description] * @return boolean [description] */ //測試數據:$resp='{"jingdong_omnichannel_order_ship_update_responce":{"code":"0","result":"{\\"code\\":\\"400\\",\\"message\\":\\"系統異常:物流組件中爲已取消狀態\\",\\"success\\":false}"}}'; function json_to_arr2($jsonstr) { if (is_string($jsonstr)&&is_array(json_decode($jsonstr, true))) { $arr = json_decode($jsonstr, true); foreach ($arr as $k => $v) { if (is_array($v)) { foreach ($v as $kk=>$vv){ if(is_string($vv) && is_array(json_decode($vv, true))){ $arr[$k][$kk] = json_decode($vv, true); } } } if(is_string($v)&&is_sarray(json_decode($v,true))){ $arr[$k]=json_decode($v,true); } } return $arr; } else { die('This is not jsonString!'); } } /** * 數組 轉 對象 * * @param array $arr 數組 * @return object */ function array_to_object($arr) { if (gettype($arr) != 'array') { return; } foreach ($arr as $k => $v) { if (gettype($v) == 'array' || getType($v) == 'object') { $arr[$k] = (object)array_to_object($v); } } return (object)$arr; } $arr = array( 'name'=>'haima', 'age'=>32, 'gender'=>'nan' ); $a=(Object)($arr); //數組轉對象 echo '<pre>'; var_dump($a); $jsonstring=json_encode($array,JSON_UNESCAPED_UNICODE); //對象轉json字符串 不轉義中文漢字 echo '<pre>'; var_dump($jsonstring); $abj=json_decode($array); //json轉對象 $array=json_decode($array,true); //json轉數組 echo '<pre>'; $b=(Array)($a); //對象轉數組 var_dump($b);
/** * 強制類型轉換 * @param string $data * @param string $type * @return mixed */ private function typeCast(&$data, $type) { switch (strtolower($type)) { // 數組 case 'a': $data = (array) $data; break; // 數字 case 'd': $data = (int) $data; break; // 浮點 case 'f': $data = (float) $data; break; // 布爾 case 'b': $data = (boolean) $data; break; // 字符串 case 's': default: if (is_scalar($data)) { $data = (string) $data; } else { throw new \InvalidArgumentException('variable type error:' . gettype($data)); } } }
serialize() 把變量和它們的值編碼成文本
unserialize() 恢復原先變量數組
//數組/字符串均可以 file_put_contents( 'log.log', date('Y-m-d H:i:s',time()) .' ' . var_export($_REQUEST,true) . "\r\n", FILE_APPEND);
例: /www.wdmcake.com/data/log/日期/$file文件名服務器
/** *$str array/str 要寫入的內容 *$dir str 日期文件夾裏面的新建的文件夾名字 例如 /www.wdmcake.com/data/log/201806/sms_apiaas *$file string 文件的名字 例:send_log_20180628.log */ function wdmlog($str,$dir='log',$file='log') { if (!file_exists(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir)) { make_dir(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir); } $str = is_array($str) ? var_export($str,true):$str; file_put_contents(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir.'/' . $file .'_' . date('Ymd') . '.log', local_date('Y-m-d H:i:s') .' ' . $str . "\r\n", FILE_APPEND); }
function create_log($data,$merchant,$agency,$file='') { if(empty($merchant)) die("商戶code不可爲空"); if(empty($agency)) die("平臺code不可爲空"); $file_path = ROOT_PATH . 'logdata/'.$merchant.'/'.$agency; if(!is_dir($file_path)){ mkdir($file_path, 0777, true); } file_put_contents($file_path.'/'.$agency.'_' . $file . date('Ymd',time()) . '.log', date('Y-m-d H:i:s',time()) .' ' . var_export($data,true) . "\r\n", FILE_APPEND); }
/** * [slice description] 返回二維數組其中一段的數據 * @param [type] $arr [description] 傳二維關聯數組 * @param [type] $star [description] 截取的開始位置 * @param [type] $length [description] 截取的長度 * @param [type] $order [description] 0順序 -1倒序 * @param [type] $preserve [description] 保持索引關係 true - 保留鍵名 false - 默認。重置鍵名 * @return [type] [description] */ function slice($arr, $star, $length, $order = 0, $preserve = false) { foreach ($arr as $key => $value) { $arr[$key] = array_slice($value, $star, $length, $preserve); } if ($order) { return array_reverse($arr); } return $arr; }
例子:app
<?php header('Content-Type=text/html;charset:utf8'); $arr = array( [ 'id' => '1', 'name' => '李四', 'age' => '21', 'gender' => '男', ], [ 'id' => '2', 'name' => '王五', 'age' => '22', 'gender' => '男', ], ); echo '<pre>'; print_r(slice($arr, 0, 2)); //打印: // 打印結果: // Array // ( // [0] => Array // ( // [id] => 1 // [name] => 李四 // ) // [1] => Array // ( // [id] => 2 // [name] => 王五 // ) // )
$_SERVER['REMOTE_ADDR']
/** * 得到訪問的IP * Enter description here ... */ function getIP() { return isset($_SERVER["HTTP_X_FORWARDED_FOR"])?$_SERVER["HTTP_X_FORWARDED_FOR"] :(isset($_SERVER["HTTP_CLIENT_IP"])?$_SERVER["HTTP_CLIENT_IP"] :$_SERVER["REMOTE_ADDR"]); }
/** * 得到用戶的真實IP地址 * * @access public * @return string */ function real_ip() { static $realip = NULL; if ($realip !== NULL) { return $realip; } if (isset($_SERVER)) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); /* 取X-Forwarded-For中第一個非unknown的有效IP字符串 */ foreach ($arr AS $ip) { $ip = trim($ip); if ($ip != 'unknown') { $realip = $ip; break; } } } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $realip = $_SERVER['HTTP_CLIENT_IP']; } else { if (isset($_SERVER['REMOTE_ADDR'])) { $realip = $_SERVER['REMOTE_ADDR']; } else { $realip = '0.0.0.0'; } } } else { if (getenv('HTTP_X_FORWARDED_FOR')) { $realip = getenv('HTTP_X_FORWARDED_FOR'); } elseif (getenv('HTTP_CLIENT_IP')) { $realip = getenv('HTTP_CLIENT_IP'); } else { $realip = getenv('REMOTE_ADDR'); } } preg_match("/[\d\.]{7,15}/", $realip, $onlineip); $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0'; return $realip; }
/** * 檢測訪問的ip是否爲規定的容許的ip * Enter description here ... */ function check_ip(){ $ALLOWED_IP=array('192.168.2.*','127.0.0.1','192.168.2.49'); $IP=getIP(); $check_ip_arr= explode('.',$IP);//要檢測的ip拆分紅數組 #限制IP if(!in_array($IP,$ALLOWED_IP)) { foreach ($ALLOWED_IP as $val){ if(strpos($val,'*')!==false){//發現有*號替代符 $arr=array();// $arr=explode('.', $val); $bl=true;//用於記錄循環檢測中是否有匹配成功的 for($i=0;$i<4;$i++){ if($arr[$i]!='*'){//不等於* 就要進來檢測,若是爲*符號替代符就不檢查 if($arr[$i]!=$check_ip_arr[$i]){ $bl=false; break;//終止檢查本個ip 繼續檢查下一個ip } } }//end for if($bl){//若是是true則找到有一個匹配成功的就返回 return; die; } } }//end foreach header('HTTP/1.1 403 Forbidden'); echo "Access forbidden"; die; } }
function f_dirname($f_path){ return substr($f_path,0,strrpos($f_path,'\\')); }
define('CUR_API_PATH', rtrim(str_replace('\\', '/', dirname(__FILE__)),'/').'/');
/** * 隨機字符 * @param int $length 長度 * @param string $type 類型 * @param int $convert 轉換大小寫 1大寫 0小寫 * @return string */ function random($length=10, $type='letter', $convert=0) { $config = array( 'number'=>'1234567890', 'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789', 'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' ); if(!isset($config[$type])) $type = 'letter'; $string = $config[$type]; $code = ''; $strlen = strlen($string) -1; for($i = 0; $i < $length; $i++){ $code .= $string{mt_rand(0, $strlen)}; } if(!empty($convert)){ $code = ($convert > 0)? strtoupper($code) : strtolower($code); } return $code; }
/** * 檢查目標文件夾是否存在,若是不存在則自動建立該目錄 * * @access public * @param string folder 目錄路徑。不能使用相對於網站根目錄的URL * * @return bool */ function make_dir($folder) { $reval = false; if (!file_exists($folder)) { /* 若是目錄不存在則嘗試建立該目錄 */ @umask(0); /* 將目錄路徑拆分紅數組 */ preg_match_all('/([^\/]*)\/?/i', $folder, $atmp); /* 若是第一個字符爲/則看成物理路徑處理 */ $base = ($atmp[0][0] == '/') ? '/' : ''; /* 遍歷包含路徑信息的數組 */ foreach ($atmp[1] AS $val) { if ('' != $val) { $base .= $val; if ('..' == $val || '.' == $val) { /* 若是目錄爲.或者..則直接補/繼續下一個循環 */ $base .= '/'; continue; } } else { continue; } $base .= '/'; if (!file_exists($base)) { /* 嘗試建立目錄,若是建立失敗則繼續循環 */ if (@mkdir(rtrim($base, '/'), 0777)) { @chmod($base, 0777); $reval = true; } } } } else { /* 路徑已經存在。返回該路徑是否是一個目錄 */ $reval = is_dir($folder); } clearstatcache(); return $reval; }
function filetime($way,$char='m'){ date_default_timezone_set('PRC'); switch($char){ case 'c':$localtime = date('Y-m-d H:i:s',filectime($way)); break; case 'm':$localtime = date('Y-m-d H:i:s',filemtime($way)); break; case 'a':$localtime = date('Y-m-d H:i:s',fileatime($way)); break; } return $localtime; }
function suffixtype($f_path){ $info = pathinfo($f_path); $f_type = 'file'; switch(strtolower(@$info["extension"])){ case 'jpg':case 'jpeg':case 'gif': case 'png':case 'bmp':$f_type = 'image';break; case 'pl':case 'c':case 'cpp':case 'log':case 'asp':case 'php':case 'jsp':case 'txt':case 'xml':case 'html':case 'htm':case 'phtml':case 'jhtml':case 'java':case 'cfg':case 'ini': case 'text':case 'bat':$f_type = 'text';break; } return $f_type; }
/** * 檢查文件類型 * * @access public * @param string filename 文件名 * @param string realname 真實文件名 * @param string limit_ext_types 容許的文件類型 * @return string */ function check_file_type($filename, $realname = '', $limit_ext_types = '') { if ($realname) { $extname = strtolower(substr($realname, strrpos($realname, '.') + 1)); } else { $extname = strtolower(substr($filename, strrpos($filename, '.') + 1)); } if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false) { return ''; } $str = $format = ''; $file = @fopen($filename, 'rb'); if ($file) { $str = @fread($file, 0x400); // 讀取前 1024 個字節 @fclose($file); } else { if (stristr($filename, ROOT_PATH) === false) { if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' || $extname == 'xls' || $extname == 'txt' || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' || $extname == 'pdf' || $extname == 'rm' || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' || $extname == 'swf' || $extname == 'chm' || $extname == 'sql' || $extname == 'cert'|| $extname == 'pptx' || $extname == 'xlsx' || $extname == 'docx') { $format = $extname; } } else { return ''; } } if ($format == '' && strlen($str) >= 2 ) { if (substr($str, 0, 4) == 'MThd' && $extname != 'txt') { $format = 'mid'; } elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav') { $format = 'wav'; } elseif (substr($str ,0, 3) == "\xFF\xD8\xFF") { $format = 'jpg'; } elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt') { $format = 'gif'; } elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") { $format = 'png'; } elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt') { $format = 'bmp'; } elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt') { $format = 'swf'; } elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0") { // D0CF11E == DOCFILE == Microsoft Office Document if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc') { $format = 'doc'; } elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls') { $format = 'xls'; } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt') { $format = 'ppt'; } } elseif (substr($str ,0, 4) == "PK\x03\x04") { if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'docx') { $format = 'docx'; } elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xlsx') { $format = 'xlsx'; } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'pptx') { $format = 'pptx'; }else { $format = 'zip'; } } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt') { $format = 'rar'; } elseif (substr($str ,0, 4) == "\x25PDF") { $format = 'pdf'; } elseif (substr($str ,0, 3) == "\x30\x82\x0A") { $format = 'cert'; } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt') { $format = 'chm'; } elseif (substr($str ,0, 4) == "\x2ERMF") { $format = 'rm'; } elseif ($extname == 'sql') { $format = 'sql'; } elseif ($extname == 'txt') { $format = 'txt'; } } if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false) { $format = ''; } return $format; }
/** * 獲取文件後綴名,並判斷是否合法 * * @param string $file_name //是一個文件的路徑 * @param array $allow_type //須要的文件類型數組 * @return blob */ function get_file_suffix($file_name, $allow_type = array()) { $file_suffix = strtolower(array_pop(explode('.', $file_name))); if (empty($allow_type)) { return $file_suffix; } else { if (in_array($file_suffix, $allow_type)) { return true; } else { return false; } } }
function f_type($f_path){ return is_dir($f_path)?'dir':suffixtype($f_path); }
//計算文件或目錄字節大小 function bytesize_calc($f_path){ if(!is_dir($f_path)){ return sprintf("%u", filesize($f_path));} $bytesize = 0; $f_arr = scandir($f_path); $size = count($f_arr); for($i=0;$i<$size;$i++){ if('.'==$f_arr[$i]||'..'==$f_arr[$i])continue; $file_or_dir = $f_path.'/'.$f_arr[$i]; $bytesize += bytesize_calc($file_or_dir); } return $bytesize; } //得到文件大小 function f_size($f_path){ return size_formate(bytesize_calc($f_path)); }
$sms_result_data = $_GET; //用這種 $param = request()->param(); //thinkphp5接收消息 $sms_result_data1 = file_get_contents("php://input");
function _curl_get($urldata) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$urldata); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//不驗證SSL證書。 $data = curl_exec($ch); curl_close($ch); if ($data) return $data; else return false; }
若是是有圖片要上傳加下面用這行代碼
curl_file_create(ROOT_PATH.'public'.$value["goods_img"]);
/** * [post description] * @param [type] $url [請求的url] * @param string $post_data [請求的數據] * @param integer $timeout [請求超時時間] * @return [type] $Mix [混合數據json|array|obj] */ function post($url, $post_data = '', $timeout = 3000) { header("Content-type:text/html;charset=utf-8"); $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_POST, 1); curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_HEADER, false); $file_contents = curl_exec($ch); curl_close($ch); if ($content){ return $file_contents; }else{ return false; } }
若是是有圖片要上傳加下面用這行代碼
curl_file_create(ROOT_PATH.'public'.$value["goods_img"]);
/** * [_curl_post_get description] * 若是$data爲空轉爲get請求.https不驗證證書 * @param [type] $url [url] * @param array $data [要傳的數據] * @param integer $timeout [設置請求超時的時間] * @return [type] $Mix [混合數據json|array|obj] */ function _curl_post($url, $data = '',$timeout = 3000) { header("Content-type:text/html;charset=utf-8"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); //請求的url curl_setopt($ch, CURLOPT_HEADER, false); ////是否攜帶head頭信息 ture / error curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回數據仍是打印數據 0,直接輸出 1,返回 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //設置請求超時的時間 // https請求 不驗證證書和hosts方法: if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") //if (1 == strpos("$".$url, "https://")) //效果同上面 { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if(!empty($post_data)){ curl_setopt($ch, CURLOPT_POST,1); //設置post方式請求,若是不寫默認爲get方式 curl_setopt($ch, CURLOPT_POSTFIELDS,$data); //要傳遞的參數 } //發送請求 並接收數據賦值給$data $data = curl_exec($ch); //關閉請求資源 curl_close($ch); $content = iconv('gb2312', 'utf-8//IGNORE',$data); //修改字符編碼 if ($content) return $content; else return false; }
/** * curl訪問 * @author rainfer <81818832@qq.com> * @param string $url * @param string $type * @param boolean $data * @param string $err_msg * @param int $timeout * @param array $cert_info * @return string */ function go_curl($url, $type, $data = false, &$err_msg = null, $timeout = 20, $cert_info = array()) { $type = strtoupper($type); if ($type == 'GET' && is_array($data)) { $data = http_build_query($data); } $option = array(); if ( $type == 'POST' ) { $option[CURLOPT_POST] = 1; } if ($data) { if ($type == 'POST') { $option[CURLOPT_POSTFIELDS] = $data; } elseif ($type == 'GET') { $url = strpos($url, '?') !== false ? $url.'&'.$data : $url.'?'.$data; } } $option[CURLOPT_URL] = $url; $option[CURLOPT_FOLLOWLOCATION] = TRUE; $option[CURLOPT_MAXREDIRS] = 4; $option[CURLOPT_RETURNTRANSFER] = TRUE; $option[CURLOPT_TIMEOUT] = $timeout; //設置證書信息 if(!empty($cert_info) && !empty($cert_info['cert_file'])) { $option[CURLOPT_SSLCERT] = $cert_info['cert_file']; $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass']; $option[CURLOPT_SSLCERTTYPE] = $cert_info['cert_type']; } //設置CA if(!empty($cert_info['ca_file'])) { // 對認證證書來源的檢查,0表示阻止對證書的合法性的檢查。1須要設置CURLOPT_CAINFO $option[CURLOPT_SSL_VERIFYPEER] = 1; $option[CURLOPT_CAINFO] = $cert_info['ca_file']; } else { // 對認證證書來源的檢查,0表示阻止對證書的合法性的檢查。1須要設置CURLOPT_CAINFO $option[CURLOPT_SSL_VERIFYPEER] = 0; } $ch = curl_init(); curl_setopt_array($ch, $option); $response = curl_exec($ch); $curl_no = curl_errno($ch); $curl_err = curl_error($ch); curl_close($ch); // error_log if($curl_no > 0) { if($err_msg !== null) { $err_msg = '('.$curl_no.')'.$curl_err; } } return $response; }
//curl模擬post發送請求 function curl_sent($url, $postFields = null) { $header = array( // 'Content-Type: application/json', 'Content-Type: application/x-www-form-urlencoded' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // https 請求 if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if (is_array($postFields) && 0 < count($postFields)) { curl_setopt($ch, CURLOPT_POST, true); $postMultipart = false; foreach ($postFields as $k => $v) { if ('@' == substr($v, 0, 1)) { $postMultipart = true; break; } } unset($k, $v); if ($postMultipart) { curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields)); } } $reponse = curl_exec($ch); if (curl_errno($ch)) { throw new JosSdkException(curl_error($ch), 0); } else { $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (200 !== $httpStatusCode) { throw new JosSdkException($reponse, $httpStatusCode); } } curl_close($ch); return $reponse; }
方法四**:
public $connectTimeout = 0; public $readTimeout = 0; public function curl($url, $postFields = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if ($this->readTimeout) { curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout); } if ($this->connectTimeout) { curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout); } //https 請求 if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if (is_array($postFields) && 0 < count($postFields)) { $postBodyString = ""; $postMultipart = false; foreach ($postFields as $k => $v) { if("@" != substr($v, 0, 1))//判斷是否是文件上傳 { $postBodyString .= "$k=" . urlencode($v) . "&"; } else//文件上傳用multipart/form-data,不然用www-form-urlencoded { $postMultipart = true; } } unset($k, $v); curl_setopt($ch, CURLOPT_POST, true); if ($postMultipart) { curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1)); } } $reponse = curl_exec($ch); $reponse = iconv('gb2312', 'utf-8//IGNORE',$reponse); //修改字符編碼 create_log('第'.__LINE__.'行', 'wdm', 'jdomnic', 'curl'); create_log($reponse, 'wdm', 'jdomnic', 'curl'); if (curl_errno($ch)) { throw new Exception(curl_error($ch),0); } else { $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (200 !== $httpStatusCode) { throw new Exception($reponse,$httpStatusCode); } } curl_close($ch); return $reponse; }
//$param array function is_arraynull($param){ if(!is_array($param)){ return '0'; }else{ foreach ($param as $key => $value) { if($value!=''){ $ret = is_arraynull($value); }else{ return 1; } } } }
/** * 判斷是否傳入必要參數 * @param [type] $inter_param [description] * @param [type] $agency [description] * @param [type] $merchant [description] * @return [type] [description] */ function judge_parameter($param){ if(!isset($param['inter_param']) || !isset($param['agency']) || !isset($param['merchant'])){ return false; } if(empty($param['inter_param']) || empty($param['agency']) || empty($param['merchant'])){ return false; } return true; }