本页记录在PHP学习过程中碰到的函数模块,留作记录,方便后续查找:
PHP不下载高效获取远程图片长宽信息
<?php // Retrieve JPEG width and height without downloading/reading entire image. function getjpegsize($img_loc) { $handle = fopen($img_loc, "rb") or die("Invalid file stream."); $new_block = NULL; if(!feof($handle)) { $new_block = fread($handle, 32); $i = 0; if($new_block[$i]=="\xFF" && $new_block[$i+1]=="\xD8" && $new_block[$i+2]=="\xFF" && $new_block[$i+3]=="\xE0") { $i += 4; if($new_block[$i+2]=="\x4A" && $new_block[$i+3]=="\x46" && $new_block[$i+4]=="\x49" && $new_block[$i+5]=="\x46" && $new_block[$i+6]=="\x00") { // Read block size and skip ahead to begin cycling through blocks in search of SOF marker $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]); $block_size = hexdec($block_size[1]); while(!feof($handle)) { $i += $block_size; $new_block .= fread($handle, $block_size); if($new_block[$i]=="\xFF") { // New block detected, check for SOF marker $sof_marker = array("\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF"); if(in_array($new_block[$i+1], $sof_marker)) { // SOF marker detected. Width and height information is contained in bytes 4-7 after this byte. $size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8]; $unpacked = unpack("H*", $size_data); $unpacked = $unpacked[1]; $height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]); $width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]); return array($width, $height); } else { // Skip block marker and read block size $i += 2; $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]); $block_size = hexdec($block_size[1]); } } else { return FALSE; } } } } } return FALSE; } ?>
PHP高效判断远程图片(文件)是否存在
<?php /*用PHP判断远程图片(文件)是否存在*/ function check_remote_file_exists($url) { $curl = curl_init($url); // 不取回数据 curl_setopt($curl, CURLOPT_NOBODY, true); // 抓取跳转后的内容 curl_setopt($curl, CURLOPT_FOLLOWLOCATION,1); // 发送请求 $result = curl_exec($curl); $found = false; // 如果请求没有发送失败 if ($result !== false) { // 再检查http响应码是否为200 $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); var_dump($statusCode); if ($statusCode == 200) { // $retcode >= 400 -> not found, $retcode = 200, found. $found = true; } } curl_close($curl); return $found; } $exists = check_remote_file_exists('https://browser2.qhimg.com/t018e9d29a90089728e.png'); if ($exists) { echo '存在'; } else { echo '不存在'; } $exists = check_remote_file_exists('https://browser2.qhimg.com/t018e9d29a90089728f.png'); if ($exists) { echo '存在'; } else { echo '不存在'; } exit; ?>
PHP Access-Control-Allow-Origin跨域设置多个域名
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : ''; $allowOrigin = array( 'https://www.baidu.com/', 'https://www.google.com/' ); if (in_array($origin, $allowOrigin)) { header("Access-Control-Allow-Origin:".$origin); }
Chevereto图床API调用的两种方法
测试可以用方法一,方法二才是最佳的选择,示例中的图床有效性自行测试。
方法一:
<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标记显示上传按钮,简单直接,但是默认按钮排版不甚美观,可以使用以下自定义按钮解决。
- 缺点:点击按钮会跳出上传页面,多一个步骤且不是太美观。
优化:自定义按钮
<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> <style> .btn-default { color: #333; background-color: #fff; border-color: #ccc; } .btn-default:hover { color: #333; background-color: #d4d4d4; border-color: #8c8c8c; } .btn { display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: 400; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; } .btn:active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 3px 5px rgba(0,0,0,.125); box-shadow: inset 0 3px 5px rgba(0,0,0,.125); } </style>
方法二(推荐):
<script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js"></script> <input id="up_to_chevereto" type="file" accept="image/*" multiple="multiple"/> <label for="up_to_chevereto" id="up_img_label"><i class="fa fa-picture-o" aria-hidden="true"></i>上传图片</label> <p id="up_tips"></p> <style type="text/css"> #up_to_chevereto { display: none; } #up_img_label { color: #fff; background-color: #16a085; border-radius: 5px; display: inline-block; padding: 5.2px; } </style> <script type="text/javascript"> $('#up_to_chevereto').change(function() { var result = ''; for (var i = 0; i < this.files.length; i++) { var f=this.files[i]; var formData=new FormData(); formData.append('source',f); $.ajax({ async:true, crossDomain:true, url:'https://at9.cc/api/1/upload/?key=19298e656196b40c8b6e87a3ac589f2c&format=json', type : 'POST', processData : false, contentType : false, data:formData, beforeSend: function (xhr) { $('#up_img_label').html('<i class="fa fa-spinner rotating" aria-hidden="true"></i> Uploading...'); }, success:function(res){ //console.log(res); result = res; console.log(result); //alert(result); $("#up_tips").html('<a href='+res.image.url+'><img src='+res.image.url+' alt='+res.image.title+'></img></a>'); $("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传'); }, error: function (){ $("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传'); } }); } }); </script>
PHP判断文件夹是否存在,不存在自动创建
在生成或保存文件时我们经常会遇到文件夹不存在时报错的情况,使用以下方法即可解决
判断文件夹是否存在,没有则新建
//判断文件夹是否存在,没有则新建 function path_exists($path){ if (!function_exists($path)) { mkdirs($path); } }
创建文件夹
//创建文件夹 function mkdirs($dir, $mode = 0777) { if (is_dir($dir) || @mkdir($dir, $mode)) { return true; } if (!mkdirs(dirname($dir), $mode)) { return false; } return @mkdir($dir, $mode); }
使用方法:
path_exists("Upload/user/images/");
PHP 对接七牛的图片鉴黄、暴恐识别、政治敏感、广告图片识别API的简单例子
<?php $ak = "这里填写你的 Access Key"; $sk = "这里填写你的 Secret Key"; function curl($url, $header = null, $data = null) { if($header) { $header = array_map(function ($k, $v) { return "{$k}: {$v}"; }, array_keys($header), $header); } $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); if($data) { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data); } $result = curl_exec($curl); return $result; } function ScanImage($img) { global $ak, $sk; $request_data = json_encode(Array( 'data' => Array( 'uri' => $img ), 'params' => Array( 'scenes' => Array( 'pulp', // 图片鉴黄 'terror', // 暴恐识别 'politician', // 政治敏感 'ads' // 政治敏感 ) ) )); $sign_rawdata = "POST /v3/image/censor\nHost: ai.qiniuapi.com\nContent-Type: application/json\n\n{$request_data}"; $header = Array( 'Content-Type' => 'application/json', 'Authorization' => "Qiniu {$ak}:" . str_replace("+", "-", base64_encode(hash_hmac('sha1', $sign_rawdata, $sk, true))) ); return curl("http://ai.qiniuapi.com/v3/image/censor", $header, $request_data); } $data = ScanImage("你想要识别的图片地址"); // 此处是图片地址 $data = json_decode($data, true); print_r($data); // 输出返回的信息
用于识别广告图片,对于需要监控广告的场景很合适。七牛的价格也不贵,一百张图片 0.085 元。点此注册
PHP加入一言功能
function GetHitokoto(){ $url = 'https://v1.hitokoto.cn/?encode=json'; // 不限定内容类型 // $url = https://v1.hitokoto.cn/?encode=json&c=d'; // 限定内容类型 $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查 SSL 加密算法是否存在 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 6); $response = curl_exec($ch); if($error=curl_error($ch)){ return '欢迎来到轮回阁'; // 如果 6s 内,一言 API 调用失败则输出这个默认句子~ } curl_close($ch); $array_data = json_decode($response,true); $Emu_content = $array_data['hitokoto'].'----《'.$array_data['from'].'》'; // 输出格式:经典语句----《语句出处》 return $Emu_content; }
调用时使用:
<?php echo GetHitokoto(); ?>
非激活标签时JS动态修改网站图标以及标题
<!-- 图标标题变化 --> <script> const changeFavicon = link => { let $favicon = document.querySelector('link[rel="icon"]'); if ($favicon !== null) { $favicon.href = link; } else { $favicon = document.createElement("link"); $favicon.rel = "icon"; $favicon.href = link; document.head.appendChild($favicon); } }; window.onfocus = function () { let icon = "favicon.ico"; // 图片地址 changeFavicon(icon); // 动态修改网站图标 document.title = "轮回阁"; // 动态修改网站标题 }; window.onblur = function () { let icon = "https://www.baidu.com/favicon.ico"; // 图片地址 changeFavicon(icon); // 动态修改网站图标 document.title = "百度一下,你就知道"; // 动态修改网站标题 }; </script> <!-- 图标标题变化End -->
适合于上班摸鱼或网页游戏挂机时间伪装使用。
原生JS实现ajax发送post请求并获取返回信息
<script> var oStr = ''; var postData = {}; var oAjax = null; //post提交的数据 postData = {"name1":"value1","name2":"value2"}; //这里需要将json数据转成post能够进行提交的字符串 name1=value1&name2=value2格式 postData = (function(value){ for(var key in value){ oStr += key+"="+value[key]+"&"; }; return oStr; }(postData)); //这里进行HTTP请求 try{ oAjax = new XMLHttpRequest(); }catch(e){ oAjax = new ActiveXObject("Microsoft.XMLHTTP"); }; //post方式打开文件 oAjax.open('post','1.php?='+Math.random(),true); //post相比get方式提交多了个这个 oAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //post发送数据 oAjax.send(postData); oAjax.onreadystatechange = function(){ //当状态为4的时候,执行以下操作 if(oAjax.readyState == 4){ try{ alert(oAjax.responseText); }catch(e){ alert('你访问的页面出错了'); }; }; }; </script>
JS根椐不同的省份跳转到不同的页面
<script type="text/javascript" src="https://ip.ws.126.net/ipquery"></script><!--网易IP库--> <script> var province=localAddress.province; if(province.indexOf('广东省') != -1 || province.indexOf('山东省') != -1)){ window.location.href = '自定义跳转地址'; } </script>
JS现10秒倒计时
<div class="box"> <h2>剩余时间:<span class="clock">10</span>秒</h2> </div> <script> var t = 10; var time = document.getElementsByClassName("clock")[0]; function fun() { t--; time.innerHTML = t; if(t <= 0) { // location.href = "https://www.baidu.com"; clearInterval(inter); } } var inter = setInterval("fun()", 1000); </script>
PHP图片转换二进制数
$image = "1.jpg"; //图片地址 $fp = fopen($image, 'rb'); $content = fread($fp, filesize($image)); //二进制数据
列出某指定目录下所有目录名,并将指定的文件复制到目录名下
function list_directory_content($dir){ if(is_dir($dir)){ if($handle = opendir($dir)){ while(($file = readdir($handle)) !== false){ if($file != '.' && $file != '..' && $file != '.htaccess'){ //echo '目录名:<a target="_blank" href="https://www.chenbo.info/u/'.$file.'/">'.$file.'</a>,路径:'.$dir.'/'.$file.'<br>'."\n"; $oldfile='/www/wwwroot/www.chenbo.info/oldfile.php'; //旧目录 $newfile = $dir.'/'.$file.'/newfile.php'; //新目录 $copyresult = copy($oldfile,$newfile); //拷贝到新目录 $newfilesize = filesize($newfile); if($copyresult || $oldfilesize = $newfilesize){ echo '路径:'.$dir.'/'.$file.'/,目录'.$file.'更新成功!<br>'."\n"; } } } closedir($handle); } } }
PHP获取referer判断来路防止非法访问
$fromurl = $_SERVER['HTTP_REFERER']; $refererUrl = parse_url($fromurl); $host = $refererUrl['host']; if(!isset($fromurl) || $host !="www.chenbo.info") { header("location: /"); //如果没有来路,或者来路不是本站,跳转到首页。 exit; }
构造参数采用 file_get_contents 函数以POST方式获取数据并返回结果
///构造提交POST $data = array( 'test'=>'bar', 'baz'=>'boom', 'site'=>'www.chenbo.info', 'name'=>'chenbo'); $data = http_build_query($data); $options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $data, 'timeout' => 60 // 超时时间(单位:s) ) ); $url = "http://www.chenbo.info/test.php"; $context = stream_context_create($options); $result = file_get_contents($url, false, $context);
PHP随机图片API本地图片版,页面直接输出图片
<?php $img_array = glob('images/*.{gif,jpg,png,jpeg,webp,bmp}', GLOB_BRACE); if(count($img_array) == 0) die('没找到图片文件。请先上传一些图片到 '.dirname(__FILE__).'/images/ 文件夹'); header('Content-Type: image/png'); echo(file_get_contents($img_array[array_rand($img_array)])); ?>
将图片保存到images目录下,自动读取images图片并输出。
PHP随机图片API远程图片版,页面直接输出图片
<?php $imgku=file('pic.txt'); showImg($imgku[array_rand($imgku)]); /* * php 页面直接输出图片 */ function showImg($img){ $img = trim($img); $info = getimagesize($img); $imgExt = image_type_to_extension($info[2], false); //获取文件后缀 $fun = "imagecreatefrom{$imgExt}"; $imgInfo = $fun($img); //1.由文件或 URL 创建一个新图象。如:imagecreatefrompng ( string $filename ) //$mime = $info['mime']; $mime = image_type_to_mime_type(exif_imagetype($img)); //获取图片的 MIME 类型 header('Content-Type:'.$mime); $quality = 100; if($imgExt == 'png') $quality = 9; //输出质量,JPEG格式(0-100),PNG格式(0-9) $getImgInfo = "image{$imgExt}"; $getImgInfo($imgInfo, null, $quality); //2.将图像输出到浏览器或文件。如: imagepng ( resource $image ) imagedestroy($imgInfo); } ?>
需安装GD库及exif扩展,php.ini中开启allow_url_fopen函数,读取同目录下pic.txt文件中的图片网址,每行一个图片地址。
COOKIE限制时间再次提交
if(isset($_COOKIE['submission_time'])) { $submissionTime = $_COOKIE['submission_time']; $currentTime = time(); $timePassed = ($currentTime - $submissionTime ) / 60 * 60; if($timePassed < 24 ) { echo "<div class='alert alert-warning'>You can record the sales after 24 hours! Please wait..</div>"; die(); } }else { $cookieName = 'submission_time'; $cokkieValue = time(); setcookie($cookieName, $cokkieValue, time() + (+60*60*24*30 ), "/"); }
判断字符串是否含有某分割符,若包含分割符,分割后输出全部分割后的值
if(strpos($qcont,',') === false){ echo "不包含,分割字段"; }else{ echo "包含,分割字段,下面进行切割并输出"; $qcontArr = explode(",", $qcont); $qcontcount = count($qcontArr); for ($i = 0; $i < $qcontcount; $i++) { if ($qcontArr[$i] == "") { continue; } echo $qcontArr[$i]; } }
对错误的详情进行格式化输出,记入log文件。
function slog($logs){ $toppath="log.htm"; $Ts=fopen($toppath,"a+"); fputs($Ts,$logs."\r\n"); fclose($Ts); }
使用file_get_contents() 发送GET、POST请求
1、【GET请求】
$data = array( 'name'=>'zhezhao','age'=>'23'); $query = http_build_query($data); $url = 'http://localhost/get.php';//这里一定要写完整的服务页面地址,否则php程序不会运行 $result = file_get_contents($url.'?'.$query);
2、【POST请求】
$data = array('user'=>'jiaxiaozi','passwd'=>'123456'); $requestBody = http_build_query($data); $context = stream_context_create(['http' => ['method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n"."Content-Length: " . mb_strlen($requestBody), 'content' => $requestBody]]); $response = file_get_contents('http://server.test.net/login', false, $context);
PHP获取当天是几号、周几
echo date('y').'</br>'; //当前年份 echo date('m').'</br>'; //当前月份 echo date('d').'</br>'; //当前日 echo date('s').'</br>'; //当前秒 echo date('w').'</br>'; //当前周几
打印结果显示为:
20
07
24
50
5
PHP给第三方接口POST或GET方式传输数据并得到返回值
function Post($url, $post = null) { $context = array(); if (is_array($post)) { ksort($post); $context['http'] = array ( 'timeout'=>60, 'method' => 'POST', 'content' => http_build_query($post, '', '&'), ); } return file_get_contents($url, false, stream_context_create($context)); } $data = array ( 'name' => 'test', 'email' => 'test@gmail.com', 'submit' => 'submit', ); echo Post('http://www.baidu.com', $data);
同一页面24小时之内之只能执行一次
define('TIME_OUT', 86400); //定义重复操作最短的允许时间,单位秒 @session_start(); $time = time(); if( isset($_SESSION['time']) ){ if( $time - $_SESSION['time'] <= TIME_OUT ){ echo '<script type=text/javascript>alert("在24小时内只能执行一次!");</script>'; exit(); } } $_SESSION['time'] = $time; echo "正常执行!";
PHP连接远程MSSQL函数:
已在如上环境安装后测试通过!
function mssql_user($username){ $host="远程服务器IP,MSSQL端口"; $dbname="数据库名称"; $user="数据库用户名"; $pass="数据库密码"; try { $dbh = new PDO("sqlsrv:Server=$host;Database=$dbname", $user, $pass); } catch(PDOException $e) { echo $e->getMessage(); exit; } $stmt = $dbh->prepare("SELECT XXX FROM XXX WHERE XXX = ".$username); $stmt->execute(); while ($row = $stmt->fetch()) { echo $row[0];//多个查询结果输出 //return $row[0]; 单一的结果可以直接用return } unset($dbh); unset($stmt); }
配置的sqlsrv扩展安装教程:https://www.chenbo.info/1637.html。
PHP时间戳和日期相互转换
获取当前日期时间的时间戳
echo time();
获取当前日期时间
echo date("Y/m/d H:i:s");
日期转换为时间戳
echo strtotime(date("Y/m/d"));
时间戳转换为日期
echo date('Y-m-d',time());
打印明天此时的时间戳
echo strtotime("+1 day");
当前时间:
echo date("Y-m-d H:i:s",time()) ;
指定时间:
echo date("Y-m-d H:i:s",strtotime("+1 day")) ;
下个星期此时的时间戳
echo strtotime("+1 week");
指定下星期几的PHP时间戳
echo strtotime("next Thursday");
指定下星期几的时间:
echo date("Y-m-d H:i:s",strtotime("next Thursday"));
指定上星期几的时间戳
echo strtotime("last Thursday");
指定本年的最后一个星期几的时间:
echo date("Y-m-d H:i:s",strtotime("last Thursday"));
截取指定两个字符之间的字符串
方法一
function cut($begin,$end,$str){ $b = mb_strpos($str,$begin) + mb_strlen($begin); $e = mb_strpos($str,$end) - $b; return mb_substr($str,$b,$e); }
方法二
function get_between($input, $start, $end) { $substr = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1)); return $substr; }
方法一当截取的是值为串的时候,会出现截取不到的情况用方法二尝试。
方法三:preg_match_all函数
preg_match_all('/<Epoch>(.*)<\/Epoch>/', $result, $matches); //print_r($matches); $resultapp = $matches[1][1];
方法一及方法二在截取长段字符串时,碰到过无法截取到的情况,用方法三解决。
调用SOHU API获取IP地址
//通过API获取IP地址 function getIP(){ $str = file_get_contents('https://pv.sohu.com/cityjson?ie=utf-8'); $ip = cut('cip": "','", "cid',$str); if($ip){ return $ip; } }
注:需配合上面 截取指定两个字符之间的字符串 函数一起使用
获取访问客户端的IP地址
function get_client_ip(){ static $realip; if (isset($_SERVER)){ if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){ $realip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if (isset($_SERVER["HTTP_CLIENT_IP"])) { $realip = $_SERVER["HTTP_CLIENT_IP"]; } else { $realip = $_SERVER["REMOTE_ADDR"]; } } else { if (getenv("HTTP_X_FORWARDED_FOR")){ $realip = getenv("HTTP_X_FORWARDED_FOR"); } else if (getenv("HTTP_CLIENT_IP")) { $realip = getenv("HTTP_CLIENT_IP"); } else { $realip = getenv("REMOTE_ADDR"); } } return $realip; }
特别说明:所有资源均无解压密码且可直接下载,若有会特别注明,部分回复可见内容仅为提供更多的下载点。