【论坛注册码购买】

QQ登录

只需一步,快速开始

查看: 1431|回复: 0

[[源码/编码]] PHP常用函数记录

[复制链接]

  离线 

UID1

威望:
0 个

魂币:
92711 个

热心:
13228 点

我的勋章
Wgsk作者认证 实名认证 发表于 2022-3-30 17:29:57 | 显示全部楼层 |阅读模式
PHP Access-Control-Allow-Origin跨域设置多个域名
  1. $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
  2. $allowOrigin = array(
  3.         'https://www.baidu.com/',
  4.         'https://www.google.com/'
  5. );
  6. if (in_array($origin, $allowOrigin)) {
  7.         header("Access-Control-Allow-Origin:".$origin);
  8. }
复制代码


Chevereto图床API调用的两种方法

测试可以用方法一,方法二才是最佳的选择,示例中的图床有效性自行测试。

#方法一:
  1. <script async src="//at9.cc/sdk/pup.js" data-url="https://at9.cc/upload" data-auto-insert="markdown-embed-full" data-palette="clear"></script>
复制代码

优点:引用JS后会自动在textarea标记显示上传按钮,简单直接,但是默认按钮排版不甚美观,可以使用以下自定义按钮解决。

缺点:点击按钮会跳出上传页面,多一个步骤且不是太美观。

优化:自定义按钮
  1. <button class="btn btn-default pull-right" style="margin-right: 5px;outline:none;" data-chevereto-pup-trigger data-chevereto-pup-id ='#newpost' data-target="#newpost"><i class="fa fa-picture-o"></i>  插入图片</button>
  2. <style>
  3. .btn-default {
  4.     color: #333;
  5.     background-color: #fff;
  6.     border-color: #ccc;
  7. }
  8. .btn-default:hover {
  9.     color: #333;
  10.     background-color: #d4d4d4;
  11.     border-color: #8c8c8c;
  12. }
  13. .btn {
  14.     display: inline-block;
  15.     padding: 6px 12px;
  16.     margin-bottom: 0;
  17.     font-size: 14px;
  18.     font-weight: 400;
  19.     line-height: 1.42857143;
  20.     text-align: center;
  21.     white-space: nowrap;
  22.     vertical-align: middle;
  23.     -ms-touch-action: manipulation;
  24.     touch-action: manipulation;
  25.     cursor: pointer;
  26.     -webkit-user-select: none;
  27.     -moz-user-select: none;
  28.     -ms-user-select: none;
  29.     user-select: none;
  30.     background-image: none;
  31.     border: 1px solid transparent;
  32.     border-radius: 4px;
  33. }
  34. .btn:active {
  35.     background-image: none;
  36.     outline: 0;
  37.     -webkit-box-shadow: inset 0 3px 5px rgba(0,0,0,.125);
  38.     box-shadow: inset 0 3px 5px rgba(0,0,0,.125);
  39. }
  40. </style>
复制代码


#方法二(推荐):
  1. <script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js"></script>
  2. <input id="up_to_chevereto" type="file" accept="image/*" multiple="multiple"/>
  3. <label for="up_to_chevereto" id="up_img_label"><i class="fa fa-picture-o" aria-hidden="true"></i>上传图片</label>
  4. <p id="up_tips"></p>
  5. <style type="text/css">
  6. #up_to_chevereto {
  7.   display: none;
  8. }
  9. #up_img_label {
  10.   color: #fff;
  11.   background-color: #16a085;
  12.   border-radius: 5px;
  13.   display: inline-block;
  14.   padding: 5.2px;
  15. }
  16. </style>
  17. <script type="text/javascript">
  18. $('#up_to_chevereto').change(function() {
  19.   var result = '';
  20.   for (var i = 0; i < this.files.length; i++) {
  21.     var f=this.files[i];
  22.     var formData=new FormData();
  23.     formData.append('source',f);
  24.     $.ajax({
  25.         async:true,
  26.         crossDomain:true,
  27.         url:'https://at9.cc/api/1/upload/?key=19298e656196b40c8b6e87a3ac589f2c&format=json',
  28.         type : 'POST',
  29.         processData : false,
  30.         contentType : false,
  31.         data:formData,
  32.         beforeSend: function (xhr) {
  33.             $('#up_img_label').html('<i class="fa fa-spinner rotating" aria-hidden="true"></i> Uploading...');
  34.         },
  35.         success:function(res){
  36.             //console.log(res);
  37.             result = res;
  38.             console.log(result);
  39.             //alert(result);
  40.             $("#up_tips").html('<a href='+res.image.url+'><img src='+res.image.url+' alt='+res.image.title+'></img></a>');
  41.             $("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传');
  42.         },
  43.         error: function (){
  44.             $("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传');
  45.         }
  46.     });
  47.   }
  48. });
  49. </script>
复制代码


PHP判断文件夹是否存在,不存在自动创建

在生成或保存文件时我们经常会遇到文件夹不存在时报错的情况,使用以下方法即可解决

#判断文件夹是否存在,没有则新建
  1. //判断文件夹是否存在,没有则新建
  2. function path_exists($path){
  3.     if (!function_exists($path)) {
  4.         mkdirs($path);
  5.     }
  6. }
复制代码


#创建文件夹
  1. //创建文件夹
  2. function mkdirs($dir, $mode = 0777)
  3. {
  4.     if (is_dir($dir) || @mkdir($dir, $mode)) {
  5.         return true;
  6.     }
  7.     if (!mkdirs(dirname($dir), $mode)) {
  8.         return false;
  9.     }
  10.     return @mkdir($dir, $mode);
  11. }
复制代码

#使用方法:
  1. path_exists("Upload/user/images/");
复制代码



PHP 对接七牛的图片鉴黄、暴恐识别、政治敏感、广告图片识别API的简单例子
  1. <?php
  2. $ak = "这里填写你的 Access Key";
  3. $sk = "这里填写你的 Secret Key";
  4. function curl($url, $header = null, $data = null) {
  5.     if($header) {
  6.         $header = array_map(function ($k, $v) {
  7.             return "{$k}: {$v}";
  8.         }, array_keys($header), $header);
  9.     }
  10.     $curl = curl_init();
  11.     curl_setopt($curl, CURLOPT_URL, $url);
  12.     curl_setopt($curl, CURLOPT_HEADER, 0);
  13.     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  14.     curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  15.     if($data) {
  16.         curl_setopt($curl, CURLOPT_POST, 1);
  17.         curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data);
  18.     }
  19.     $result = curl_exec($curl);
  20.     return $result;
  21. }
  22. function ScanImage($img) {
  23.     global $ak, $sk;
  24.     $request_data = json_encode(Array(
  25.         'data' => Array(
  26.             'uri' => $img
  27.         ),
  28.         'params' => Array(
  29.             'scenes' => Array(
  30.                 'pulp', // 图片鉴黄
  31.                 'terror', // 暴恐识别
  32.                 'politician',  // 政治敏感
  33.                 'ads' // 政治敏感
  34.             )
  35.         )
  36.     ));
  37.     $sign_rawdata = "POST /v3/image/censor\nHost: ai.qiniuapi.com\nContent-Type: application/json\n\n{$request_data}";
  38.     $header = Array(
  39.         'Content-Type' => 'application/json',
  40.         'Authorization' => "Qiniu {$ak}:" . str_replace("+", "-", base64_encode(hash_hmac('sha1', $sign_rawdata, $sk, true)))
  41.     );
  42.     return curl("http://ai.qiniuapi.com/v3/image/censor", $header, $request_data);
  43. }
  44. $data = ScanImage("你想要识别的图片地址"); // 此处是图片地址
  45. $data = json_decode($data, true);
  46. print_r($data); // 输出返回的信息
复制代码


用于识别广告图片,对于需要监控广告的场景很合适。七牛的价格也不贵,一百张图片 0.085 元。点此注册


PHP加入一言功能
  1. function GetHitokoto(){
  2.     $url = 'https://v1.hitokoto.cn/?encode=json'; // 不限定内容类型
  3.     // $url = https://v1.hitokoto.cn/?encode=json&c=d'; // 限定内容类型
  4.     $ch = curl_init();  
  5.     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
  6.     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查 SSL 加密算法是否存在
  7.     curl_setopt($ch, CURLOPT_URL, $url);
  8.     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
  9.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  10.     curl_setopt($ch, CURLOPT_TIMEOUT, 6);
  11.     $response = curl_exec($ch);  
  12.     if($error=curl_error($ch)){  
  13.         return '欢迎来到轮回阁'; // 如果 6s 内,一言 API 调用失败则输出这个默认句子~
  14.     }  
  15.     curl_close($ch);
  16.     $array_data = json_decode($response,true);
  17.     $Emu_content = $array_data['hitokoto'].'----《'.$array_data['from'].'》'; // 输出格式:经典语句----《语句出处》
  18.     return $Emu_content;
  19. }
复制代码


调用时使用:
  1. <?php echo GetHitokoto(); ?>
复制代码


非激活标签时JS动态修改网站图标以及标题
  1. <!-- 图标标题变化 -->
  2. <script>
  3. const changeFavicon = link => {
  4. let $favicon = document.querySelector('link[rel="icon"]');
  5.             if ($favicon !== null) {
  6.             $favicon.href = link;
  7. } else {
  8.             $favicon = document.createElement("link");
  9.             $favicon.rel = "icon";
  10.             $favicon.href = link;
  11.             document.head.appendChild($favicon);
  12.         }
  13. };

  14. window.onfocus = function () {
  15.         let icon = "favicon.ico"; // 图片地址
  16.         changeFavicon(icon); // 动态修改网站图标
  17.         document.title = "轮回阁"; // 动态修改网站标题
  18. };
  19. window.onblur = function () {
  20.         let icon = "https://www.baidu.com/favicon.ico"; // 图片地址
  21.         changeFavicon(icon); // 动态修改网站图标
  22.         document.title = "百度一下,你就知道"; // 动态修改网站标题
  23. };
  24. </script>
  25. <!-- 图标标题变化End -->
复制代码


适合于上班摸鱼或网页游戏挂机时间伪装使用。


原生JS实现ajax发送post请求并获取返回信息
  1. <script>
  2. var oStr = '';
  3. var postData = {};
  4. var oAjax = null;
  5. //post提交的数据
  6. postData = {"name1":"value1","name2":"value2"};
  7. //这里需要将json数据转成post能够进行提交的字符串  name1=value1&name2=value2格式
  8. postData = (function(value){
  9.   for(var key in value){
  10.     oStr += key+"="+value[key]+"&";
  11.   };
  12.   return oStr;
  13. }(postData));
  14. //这里进行HTTP请求
  15. try{
  16.   oAjax = new XMLHttpRequest();
  17. }catch(e){
  18.   oAjax = new ActiveXObject("Microsoft.XMLHTTP");
  19. };
  20. //post方式打开文件
  21. oAjax.open('post','1.php?='+Math.random(),true);
  22. //post相比get方式提交多了个这个
  23. oAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  24. //post发送数据
  25. oAjax.send(postData);
  26. oAjax.onreadystatechange = function(){
  27.   //当状态为4的时候,执行以下操作
  28.   if(oAjax.readyState == 4){
  29.     try{
  30.       alert(oAjax.responseText);
  31.     }catch(e){
  32.       alert('你访问的页面出错了');
  33.     };
  34.   };
  35. };
  36. </script>
复制代码



JS根椐不同的省份跳转到不同的页面
  1. <script type="text/javascript" src="https://ip.ws.126.net/ipquery"></script><!--网易IP库-->
  2. <script>
  3. var province=localAddress.province;
  4. if(province.indexOf('广东省')  != -1 || province.indexOf('山东省')  != -1)){
  5.     window.location.href = '自定义跳转地址';
  6. }
  7. </script>
复制代码



JS现10秒倒计时
  1. <div class="box">
  2.     <h2>剩余时间:<span class="clock">10</span>秒</h2>
  3. </div>
  4. <script>
  5.         var t = 10;
  6.         var time = document.getElementsByClassName("clock")[0];

  7.         function fun() {
  8.                 t--;
  9.                 time.innerHTML = t;
  10.                 if(t <= 0) {
  11.                         // location.href = "https://www.baidu.com";
  12.                         clearInterval(inter);
  13.                 }
  14.         }
  15.         var inter = setInterval("fun()", 1000);
  16. </script>
复制代码



PHP图片转换二进制数
  1. $image   = "1.jpg"; //图片地址
  2. $fp      = fopen($image, 'rb');
  3. $content = fread($fp, filesize($image)); //二进制数据
复制代码



列出某指定目录下所有目录名,并将指定的文件复制到目录名下
  1. function list_directory_content($dir){
  2.   if(is_dir($dir)){
  3.    if($handle = opendir($dir)){
  4.     while(($file = readdir($handle)) !== false){
  5.      if($file != '.' && $file != '..' && $file != '.htaccess'){
  6.      //echo '目录名:<a target="_blank" href="https://www.chenbo.info/u/'.$file.'/">'.$file.'</a>,路径:'.$dir.'/'.$file.'<br>'."\n";
  7.      $oldfile='/www/wwwroot/www.chenbo.info/oldfile.php'; //旧目录
  8.      $newfile = $dir.'/'.$file.'/newfile.php'; //新目录
  9.      $copyresult = copy($oldfile,$newfile); //拷贝到新目录
  10.      $newfilesize = filesize($newfile);
  11.      if($copyresult || $oldfilesize = $newfilesize){
  12.         echo '路径:'.$dir.'/'.$file.'/,目录'.$file.'更新成功!<br>'."\n";
  13.      }
  14.      
  15.      }
  16.     }
  17.     closedir($handle);
  18.    }
  19.   }
  20. }
复制代码



PHP获取referer判断来路防止非法访问
  1. $fromurl = $_SERVER['HTTP_REFERER'];
  2. $refererUrl = parse_url($fromurl);
  3. $host = $refererUrl['host'];
  4. if(!isset($fromurl) || $host !="www.chenbo.info") {
  5.     header("location: /"); //如果没有来路,或者来路不是本站,跳转到首页。
  6.     exit;
  7. }
复制代码



构造参数采用 file_get_contents 函数以POST方式获取数据并返回结果
  1. ///构造提交POST
  2. $data = array(  
  3. 'test'=>'bar',   
  4. 'baz'=>'boom',   
  5. 'site'=>'www.chenbo.info',   
  6. 'name'=>'chenbo');   
  7.       
  8. $data = http_build_query($data);   

  9. $options = array(  
  10.     'http' => array(  
  11.     'method' => 'POST',  
  12.     'header' => 'Content-type:application/x-www-form-urlencoded',  
  13.     'content' => $data,
  14.     'timeout' => 60 // 超时时间(单位:s)
  15.     )  
  16. );  
  17.   
  18. $url = "http://www.chenbo.info/test.php";  
  19. $context = stream_context_create($options);  
  20. $result = file_get_contents($url, false, $context);
复制代码



PHP随机图片API本地图片版,页面直接输出图片
  1. <?php
  2. $img_array = glob('images/*.{gif,jpg,png,jpeg,webp,bmp}', GLOB_BRACE);
  3. if(count($img_array) == 0) die('没找到图片文件。请先上传一些图片到 '.dirname(__FILE__).'/images/ 文件夹');
  4. header('Content-Type: image/png');
  5. echo(file_get_contents($img_array[array_rand($img_array)]));
  6. ?>
复制代码

将图片保存到images目录下,自动读取images图片并输出



PHP随机图片API远程图片版,页面直接输出图片
  1. <?php
  2. $imgku=file('pic.txt');
  3. showImg($imgku[array_rand($imgku)]);

  4. /*
  5. * php 页面直接输出图片
  6. */
  7. function showImg($img){
  8.   $img = trim($img);
  9.   $info = getimagesize($img);
  10.   $imgExt = image_type_to_extension($info[2], false); //获取文件后缀
  11.   $fun = "imagecreatefrom{$imgExt}";
  12.   $imgInfo = $fun($img);         //1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename )
  13.   //$mime = $info['mime'];
  14.   $mime = image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型
  15.   header('Content-Type:'.$mime);
  16.   $quality = 100;
  17.   if($imgExt == 'png') $quality = 9;   //输出质量,JPEG格式(0-100),PNG格式(0-9)
  18.   $getImgInfo = "image{$imgExt}";
  19.   $getImgInfo($imgInfo, null, $quality); //2.将图像输出到浏览器或文件。如: imagepng ( resource $image )
  20.   imagedestroy($imgInfo);
  21. }
  22. ?>
复制代码
需安装GD库及exif扩展,php.ini中开启allow_url_fopen函数,读取同目录下pic.txt文件中的图片网址,每行一个图片地址。



COOKIE限制时间再次提交
  1. if(isset($_COOKIE['submission_time'])) {
  2.     $submissionTime =   $_COOKIE['submission_time'];
  3.     $currentTime    =   time();
  4.     $timePassed     =   ($currentTime - $submissionTime ) / 60 * 60;

  5.     if($timePassed < 24 ) {
  6.         echo "<div class='alert alert-warning'>You can record the sales after 24 hours! Please wait..</div>";
  7.         die();
  8.     }
  9. }else {
  10.         $cookieName     =   'submission_time';
  11.         $cokkieValue    =   time();
  12.         setcookie($cookieName, $cokkieValue, time() + (+60*60*24*30 ), "/");
  13. }
复制代码



判断字符串是否含有某分割符,若包含分割符,分割后输出全部分割后的值
  1. if(strpos($qcont,',') === false){
  2.               echo "不包含,分割字段";
  3. }else{
  4.               echo "包含,分割字段,下面进行切割并输出";
  5.         $qcontArr = explode(",", $qcont);
  6.               $qcontcount = count($qcontArr);
  7.             for ($i = 0; $i < $qcontcount; $i++) {
  8.                 if ($qcontArr[$i] == "") {
  9.                             continue;  
  10.                 }
  11.                 echo $qcontArr[$i];
  12.             }
  13. }
复制代码



对错误的详情进行格式化输出,记入log文件。
  1. function slog($logs){
  2.     $toppath="log.htm";
  3.     $Ts=fopen($toppath,"a+");
  4.     fputs($Ts,$logs."\r\n");
  5.     fclose($Ts);
  6. }
复制代码



使用file_get_contents() 发送GET、POST请求
#1、【GET请求】
  1. $data = array( 'name'=>'zhezhao','age'=>'23');
  2. $query = http_build_query($data);
  3. $url = 'http://localhost/get.php';//这里一定要写完整的服务页面地址,否则php程序不会运行
  4. $result = file_get_contents($url.'?'.$query);
复制代码


#2、【POST请求】
  1. $data = array('user'=>'jiaxiaozi','passwd'=>'123456');
  2. $requestBody = http_build_query($data);
  3. $context = stream_context_create(['http' => ['method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n"."Content-Length: " . mb_strlen($requestBody), 'content' => $requestBody]]);
  4. $response = file_get_contents('http://server.test.net/login', false, $context);
复制代码



PHP获取当天是几号、周几
  1. echo date('y').'</br>';    //当前年份
  2. echo date('m').'</br>';    //当前月份
  3. echo date('d').'</br>';    //当前日
  4. echo date('s').'</br>';    //当前秒
  5. echo date('w').'</br>';    //当前周几
复制代码

打印结果显示为:
20
07
24
50
5



PHP给第三方接口POST或GET方式传输数据并得到返回值
  1. function Post($url, $post = null)
  2. {
  3.      $context = array();
  4.      if (is_array($post))
  5.      {
  6.          ksort($post);
  7.           $context['http'] = array
  8.          (   
  9.               'timeout'=>60,
  10.              'method' => 'POST',
  11.              'content' => http_build_query($post, '', '&'),
  12.          );
  13.      }
  14.      return file_get_contents($url, false, stream_context_create($context));
  15. }

  16. $data = array
  17. (
  18.      'name' => 'test',
  19.      'email' => 'test@gmail.com',
  20.      'submit' => 'submit',
  21. );

  22. echo Post('http://www.baidu.com', $data);
复制代码



同一页面24小时之内之只能执行一次
  1. define('TIME_OUT', 86400); //定义重复操作最短的允许时间,单位秒
  2. @session_start();
  3. $time = time();
  4. if( isset($_SESSION['time']) ){
  5. if( $time - $_SESSION['time'] <= TIME_OUT ){
  6.     echo '<script type=text/javascript>alert("在24小时内只能执行一次!");</script>';
  7.     exit();
  8.     }
  9. }
  10. $_SESSION['time'] = $time;
  11. echo "正常执行!";
复制代码



PHP连接远程MSSQL函数:

已在如上环境安装后测试通过!
  1. function mssql_user($username){
  2.         $host="远程服务器IP,MSSQL端口";
  3.         $dbname="数据库名称";
  4.         $user="数据库用户名";
  5.         $pass="数据库密码";
  6.         try {
  7.             $dbh = new PDO("sqlsrv:Server=$host;Database=$dbname", $user, $pass);
  8.         } catch(PDOException $e) {
  9.             echo $e->getMessage();
  10.             exit;
  11.         }
  12.         $stmt = $dbh->prepare("SELECT XXX FROM XXX WHERE XXX = ".$username);
  13.         $stmt->execute();
  14.         while ($row = $stmt->fetch()) {
  15.                 echo $row[0];//多个查询结果输出
  16.                 //return $row[0]; 单一的结果可以直接用return
  17.         }
  18.         unset($dbh); unset($stmt);
  19. }
复制代码
配置的sqlsrv扩展安装教程:https://www.rr6w.com/thread-1540-1-1.html



PHP时间戳和日期相互转换

获取当前日期时间的时间戳
  1. echo time();
复制代码


获取当前日期时间
  1. echo date("Y/m/d H:i:s");
复制代码

日期转换为时间戳
  1. echo strtotime(date("Y/m/d"));
复制代码


时间戳转换为日期
  1. echo date('Y-m-d',time());
复制代码


打印明天此时的时间戳
  1. echo strtotime("+1 day");
复制代码


当前时间:
  1. echo date("Y-m-d H:i:s",time()) ;
复制代码

指定时间:
  1. echo date("Y-m-d H:i:s",strtotime("+1 day")) ;
复制代码


下个星期此时的时间戳
  1. echo strtotime("+1 week");
复制代码


指定下星期几的PHP时间戳
  1. echo strtotime("next Thursday");
复制代码


指定下星期几的时间:
  1. echo date("Y-m-d H:i:s",strtotime("next Thursday"));
复制代码


指定上星期几的时间戳
  1. echo strtotime("last Thursday");
复制代码


指定本年的最后一个星期几的时间:
  1. echo date("Y-m-d H:i:s",strtotime("last Thursday"));
复制代码



截取指定两个字符之间的字符串

#方法一
  1. function cut($begin,$end,$str){
  2.     $b = mb_strpos($str,$begin) + mb_strlen($begin);
  3.     $e = mb_strpos($str,$end) - $b;
  4.     return mb_substr($str,$b,$e);
  5. }
复制代码


#方法二
  1. function get_between($input, $start, $end) {
  2. $substr = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1));
  3. return $substr;
  4. }
复制代码

方法一当截取的是值为串的时候,会出现截取不到的情况用方法二尝试。

#方法三:preg_match_all函数
  1. preg_match_all('/<Epoch>(.*)<\/Epoch>/', $result, $matches);
  2. //print_r($matches);
  3. $resultapp = $matches[1][1];
复制代码
方法一及方法二在截取长段字符串时,碰到过无法截取到的情况,用方法三解决。



调用SOHU API获取IP地址
  1. //通过API获取IP地址
  2. function getIP(){
  3.             $str = file_get_contents('https://pv.sohu.com/cityjson?ie=utf-8');
  4.             $ip = cut('cip": "','", "cid',$str);
  5.             if($ip){
  6.                     return $ip;
  7.             }
  8. }
复制代码
注:需配合上面 截取指定两个字符之间的字符串 函数一起使用




获取访问客户端的IP地址
  1. function get_client_ip(){
  2.     static $realip;
  3.     if (isset($_SERVER)){
  4.     if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
  5.         $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  6.     } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
  7.         $realip = $_SERVER["HTTP_CLIENT_IP"];
  8.         } else {
  9.             $realip = $_SERVER["REMOTE_ADDR"];
  10.         }
  11.             } else {
  12.                 if (getenv("HTTP_X_FORWARDED_FOR")){
  13.                     $realip = getenv("HTTP_X_FORWARDED_FOR");
  14.             } else if (getenv("HTTP_CLIENT_IP")) {
  15.                 $realip = getenv("HTTP_CLIENT_IP");
  16.             } else {
  17.                 $realip = getenv("REMOTE_ADDR");
  18.             }
  19.         }
  20.     return $realip;
  21. }
复制代码



您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|小黑屋|魂影技术论坛 ( 浙ICP备16020365号-1 )|网站地图

GMT+8, 2024-4-19 11:18 , Processed in 0.077645 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.