1、php代码库
https://www.nhooo.com/php/php-mysql-insert-query.html
https://www.runoob.com/php/php-oop.html
2、升阶部分
0、固定svg图标在右下角
<style>
.x_floating-btn {
position: fixed;
right: 25px;
top: 90%;
background-color: #fff;
color: #000;
padding: 5px 5px;
border-radius: 100%;
cursor: pointer;
z-index: 9999;
box-shadow: 2px 2px 8px rgba(0, 0, 0, .25);
display: flex
;
align-items: center;
}
*
</style>
<a href="../">
<div class="x_floating-btn">
<svg t="1741497419406" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2621" width="32" height="32"><path d="M0 0h1024v1024H0V0z" fill="#202425" opacity=".01" p-id="2622"></path><path d="M136.533333 375.466667h750.933334v546.133333a34.133333 34.133333 0 0 1-34.133334 34.133333H170.666667a34.133333 34.133333 0 0 1-34.133334-34.133333V375.466667z" fill="#11AA66" p-id="2623"></path><path d="M409.6 716.8a34.133333 34.133333 0 0 1 34.133333-34.133333h136.533334a34.133333 34.133333 0 0 1 34.133333 34.133333v238.933333h-204.8v-238.933333z" fill="#FFFFFF" p-id="2624"></path><path d="M493.056 80.896a34.133333 34.133333 0 0 1 37.888 0l446.122667 297.437867a17.066667 17.066667 0 0 1-9.4208 31.266133H56.32a17.066667 17.066667 0 0 1-9.454933-31.266133L493.056 80.896z" fill="#FFAA44" p-id="2625"></path></svg>
</div>
</a>
1、将一个数组按数组里面某个值排序
//在数组中取出你想要排序的值,例如你想要排序的值是 template_width
$template_width_arr=array_column($live_transcoding_task_list,"template_width");
//你就会得到 template_width的值为:
Array
(
[0] => 1920
[1] => 1280
[2] => 2560
[3] => 960
)
//然后这句话的值就是在这里面重新将按照上面的值去将数组2升序还是降序,
array_multisort($template_width_arr,SORT_DESC,$live_transcoding_task_list);
print_r($live_transcoding_task_list);
排序前的的
Array
(
[0] => Array
(
[template_id] => FHD
[template_name] => pdsFHD
[template_width] => 1920
[template_height] => 1080
[status] => finished
[stage] => stage_all)
[1] => Array
(
[template_id] => HD
[template_name] => pdsHD
[template_width] => 1280
[template_height] => 720
[status] => finished
[stage] => stage_all)
[2] => Array
(
[template_id] => QHD
[template_name] => pds2K
[template_width] => 2560
[template_height] => 1440
[status] => finished
[stage] => stage_all))
排序后的
Array
(
[0] => Array
(
[template_id] => QHD
[template_name] => pds2K
[template_width] => 2560
[template_height] => 1440
[status] => finished
[stage] => stage_all )
[1] => Array
(
[template_id] => FHD
[template_name] => pdsFHD
[template_width] => 1920
[template_height] => 1080
[status] => finished
[stage] => stage_all)
[2] => Array
(
[template_id] => HD
[template_name] => pdsHD
[template_width] => 1280
[template_height] => 720
[status] => finished
[stage] => stage_all))
1、iframe常用设置
<iframe allowfullscreen="true" allowtransparency="true" id="player" frameborder="0" src="" class="iframeStyle" style="display:none"></iframe>
document.getElementById('player').src=playerurl;
document.getElementById('player').style.display = 'block';
1、基础部分
function changeTypeName($action,$path, $oldTypaName, $newTypeName)
{
$path = "glob://$path/*";
$files = new DirectoryIterator($path);
foreach ($files as $file) {
$fileRealPath = $file->getRealPath(); //文件绝对路径
if($action){
$compressCssFileRealPath = str_replace("$oldTypaName", "$newTypeName", $fileRealPath);
}else{
$compressCssFileRealPath = str_replace(".$oldTypaName", ".$newTypeName", $fileRealPath);
}
rename($fileRealPath, $compressCssFileRealPath);
}
}
//$action:1 指定文件改名字和后缀名 0:改所有文件的后缀名
0)、打开网页所用时间
$startTime = microtime(true);
$endTime = microtime(true);
echo sprintf("use time: %.3f s".PHP_EOL, $endTime - $startTime);
1)、从一个url字符串获取相关参数的值,常用函数(parse_url)
<?php
$url = "https://testurl.com/test/1234?email=abc@test.com&name=sarah";
$components = parse_url($url);
parse_str($components['query'], $results);
print_r($results);
?>
输出:
Array
(
[email] => abc@test.com
[name] => sarah
)
substr_count() 函数计算子串在字符串中出现的次数。
2)、从一个字符串取出一个数字
https://www.kuwo.cn/play_detail/228908
preg_match_all('!d+!', $_GET['url'], $matches);
Array
(
[0] => Array
(
[0] => 228908
)
)
3)、禁用基础按键来做安全
<script type="text/javascript">
window.onload = function(){
document.onkeydown = function (){
var e = window.event || arguments[0];
//F12
if(e.keyCode == 123){
return false;
//Ctrl+Shift+I
}else if((e.ctrlKey) && (e.shiftKey) && (e.keyCode == 73)){
return false;
//Shift+F10
}else if((e.shiftKey) && (e.keyCode == 121)){
return false;
//Ctrl+U
}else if((e.ctrlKey) && (e.keyCode == 85)){
return false;
}
};
document.oncontextmenu = function (){
return false;
}
}
</script>
第二种有问题 后面再研究
<!--安全2开始-->
<script type="text/javascript">
//判断F12审查元素
function fuckyou() {
window.close(); //关闭当前窗口(防抽)
window.location = "https://nbjx.cc"; //将当前窗口跳转置空白页
}
function ck() {
console.profile();
console.profileEnd();
//我们判断一下profiles里面有没有东西,如果有,肯定有人按F12了,没错!!
if(console.clear) {
console.clear()
};
if(typeof console.profiles == "object") {
return console.profiles.length > 0;
}
}
function hehe() {
alert(1);
if((window.console && (console.firebug || console.table && /firebug/i.test(console.table()))) || (typeof opera == 'object' && typeof opera.postError == 'function' && console.profile.length > 0)) {
fuckyou();
}
if(typeof console.profiles == "object" && console.profiles.length > 0) {
fuckyou();
}
}
hehe();
window.onresize = function() {
if((window.outerHeight - window.innerHeight) > 200)
//判断当前窗口内页高度和窗口高度,如果差值大于200,那么呵呵
fuckyou();
}
</script>
4)、设备判断
<!--设备判断-->
<script type="text/javascript">
function browserRedirect() {
var sUserAgent= navigator.userAgent.toLowerCase();
var bIsIpad= sUserAgent.match(/ipad/i) == "ipad";
var bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os";
var bIsMidp= sUserAgent.match(/midp/i) == "midp";
var bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
var bIsUc= sUserAgent.match(/ucweb/i) == "ucweb";
var bIsAndroid= sUserAgent.match(/android/i) == "android";
var bIsCE= sUserAgent.match(/windows ce/i) == "windows ce";
var bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile";
var iurl = window.location.href;
var surl = iurl.substring(iurl.lastIndexOf('/'));
if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
window.location.href= '../user/login';
} else {
}
}
browserRedirect();
</script>
5@
http://wpa.qq.com/msgrd?v=3&uin=xxxx&site=qq&menu=yes
1、数值型处理
1. 取整
// 丢弃小数部分,保留整数部分
parseInt(7/2) // 3
2. 向上取整
// 向上取整,有小数就整数部分加1
Math.ceil(7/2) // 4
3. 向下取整
// 向下取整,丢弃小数部分
Math.floor(7/2) // 3
4. 四舍五入
// 四舍五入
Math.round(7/2) // 3
5、取余
// 1. 取余
7%2 // 1
6、随机数
$duankou=rand(1009,9999);
2、字符型处理
1、字符串截取、大小写判断
$content=mb_substr($content[0], 0, 16, 'utf-8');
# 将下面链接截取 ddgHAce6QJV和63dd4ed6c394f65c9a394f06bc35beda7fe50633
//https://www.aliyundrive.com/s/ddgHAce6QJV/folder/63ddb73317f8243a53004b8fac47d6ec5b4fc72d/file_id/63dd4ed6c394f65c9a394f06bc35beda7fe50633
$begin = strpos($enurl, "s/");
$end = strpos($enurl, "/folder/");
$share_id = substr($enurl, $begin + 2, $end - $begin - 2);
$begin = strpos($enurl, "/file_id/");
$end = strpos($enurl, "lder/");
$file_id = substr($enurl, $begin + 9);
$url=$share_id."|".$file_id; //ddgHAce6QJV|63dd4ed6c394f65c9a394f06bc35beda7fe50633
strcmp()函数:该函数进行字符串之间的比较, 在比较的时候,区分大小写.
$back = strcmp($a,$b);
if($back>0)
echo '$a大于$b';
elseif($back<0)
echo '$a小于$b';
else
echo '$a等于$b';
?>
输出结果:
$a大于$b
————————————————
2.strcasecmp():该函数同strcmp函数基本一致,但是该函数在比较的时候,不区分大小写.
<?php
$val1 = "Hello";
$val2 = "hello";
if(strcasecmp($val1,$val2)==0)
echo '$val1和$val2相同(忽略字符串的大小写)';
?>
输出结果:
$val1和$val2相同(忽略字符串的大小写)
2、将字符串分割成数组,将数组转成字符串 并且用,号连接
#将字符串分割成数组
$daoyanstr='米洛·文堤米利亚,曼迪·摩尔,斯特林·K·布朗,苏珊·卡莉奇·沃森,克丽丝·梅斯,贾斯汀·哈特雷,克里斯·沙利文,迈克尔·安格拉诺,亚利桑德拉·布莱肯瑞吉,洛根·施罗耶';
$dydata=explode(',',$daoyanstr);
# 将数组转成字符串 并且用,号连接
$dydata=Array
(
[0] => 米洛·文堤米利亚
[1] => 曼迪·摩尔
[2] => 斯特林·K·布朗
[3] => 苏珊·卡莉奇·沃森
[4] => 克丽丝·梅斯
[5] => 贾斯汀·哈特雷
[6] => 克里斯·沙利文
[7] => 迈克尔·安格拉诺
[8] => 亚利桑德拉·布莱肯瑞吉
[9] => 洛根·施罗耶
)
$daoyanstr = implode(",",$dydata);
# 并且用,号连接
$daoyanstr=米洛·文堤米利亚,曼迪·摩尔,斯特林·K·布朗,苏珊·卡莉奇·沃森,克丽丝·梅斯,贾斯汀·哈特雷,克里斯·沙利文,迈克尔·安格拉诺,亚利桑德拉·布莱肯瑞吉,洛根·施罗耶
3、定义常量
define('DB_HOST','localhost');//数据库连接地址,默认:localhost或127.0.0.1
4、获取当前访问域名
define('ZHUYUMING',$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']);//当前域名
5、获取最后出现的字符索引号
$str='1122/3344/5566';
$final=strrpos($str,'/');//final得出的第十个字符 也就是final=9
$filenames=substr($str,$final + 1); //得出结果是:5566
$filename=explode(".",$filenames)[0].".txt";
* )、循环函数:For ,Foreach ,While,do While,Switch,IF
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
elseif ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
$favcolor="red";
switch ($favcolor)
{
case "red":
echo "你喜欢的颜色是红色!";
break;
case "blue":
echo "你喜欢的颜色是蓝色!";
break;
case "green":
echo "你喜欢的颜色是绿色!";
break;
default:
echo "你喜欢的颜色不是 红, 蓝, 或绿色!";
}
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br>";
$i++;
}
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
foreach ($array as $value)
{
要执行代码;
}
foreach ($array as $key => $value)
{
要执行代码;
}
0)、数组遍历,删除,添加,打乱,排序,遍历,合并
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
// 检查键
var_dump(array_key_exists('name', $data)); // bool(true)
var_dump(array_key_exists('Tom', $data)); // bool(false)
// 两种方式 用键删除或用索引删除
// unset($data['age']);
array_splice($data, 1, 1);
// 通过值删除
$newData = array_diff($data, ['Tom', 'pku']);
# 打乱
sort() - 对数组进行升序排列
rsort() - 对数组进行降序排列
asort() - 根据关联数组的值,对数组进行升序排列
ksort() - 根据关联数组的键,对数组进行升序排列
arsort() - 根据关联数组的值,对数组进行降序排列
krsort() - 根据关联数组的键,对数组进行降序排列
shuffle() 随机打乱数组
array_merge(arr1,arr2,,,)函数 多个数组合并
1)、魔术变量常用
# 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。
echo __FILE__;// /www/wwwroot/pachong.com/include/1.php
# 文件中的当前行号。
echo __LINE__;//19 这段代码出现再那行
echo '该文件位于 " ' . __DIR__ . ' " ';// 该文件位于 " /www/wwwroot/pachong.com/include "
function test() {
echo '函数名为:' . __FUNCTION__ ;
}
test();// 函数名是:test
echo '该类的类名为:' . __CLASS__ . "<br>";
echo '该代码所在的函数名为:' . __FUNCTION__ ;
2)、超级全局变量
PHP 超级全局变量
PHP中预定义了几个超级全局变量(superglobals) ,这意味着它们在一个脚本的全部作用域中都可用。 你不需要特别说明,就可以在函数及类中使用。
PHP 超级全局变量列表:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
本章节我们将讲解几个常用的超级全局变量,其余变量我们在接下来几个章节会介绍到。
PHP $GLOBALS
$GLOBALS 是PHP的一个超级全局变量组,在一个PHP脚本的全部作用域中都可以访问。
$GLOBALS 是一个包含了全部变量的全局组合数组。变量的名字就是数组的键。
以下实例介绍了如何使用超级全局变量 $GLOBALS:
实例
<?php
$x = 75;
$y = 25;
function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
3)、PHP Cookie
Cookie是一个小型文本文件,可让您在用户计算机上存储少量数据(最大4KB左右)。它们通常用于跟踪诸如用户名之类的信息,当用户下次访问网站时,网站可以检索该信息以显示特定个性化页面。
提示:每次浏览器向服务器请求页面时,cookie中的所有数据都会自动发送到请求内的服务器。
setcookie(name, value, expire, path, domain, secure);
该setcookie()函数的参数具有以下含义:
参数 描述
name Cookie的名称。
value Cookie的值。由于此值存储在用户的计算机上,因此请勿存储敏感信息。
expires UNIX时间戳格式的过期日期。 在此时间之后,cookie将变得不可访问。 默认值为0
path 在服务器上指定cookie可用的路径。如果设置为/,则cookie将在整个域中可用。
domain 指定可用于其Cookie的域,例如:www.nhooo.com。
secure 该字段(如果存在)表示仅当存在安全的HTTPS连接时才发送cookie。
下面是一个使用setcookie()函数创建名为userName的cookie并为其赋值John Carter的示例。 同时指定cookie过期时间为30天(30 days * 24 hours * 60 min * 60 sec)。
<?php
//设置Cookie
setcookie("username", "John Carter", time()+30*24*60*60);
?>
<?php
//访问单个Cookie值
echo $_COOKIE["username"];
?>
<?php
//验证是否设置了cookie
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
} else{
echo "Welcome Guest!";
}
?>
<?php
//删除cookie
setcookie("username", "", time()-3600);
?>
3)、PHP Session
尽管您可以使用Cookie存储数据,但是它存在一些安全问题。 由于cookie存储在用户计算机上,因此攻击者可以轻松地修改cookie内容,以在您的应用程序中插入可能有害的数据,从而可能破坏您的应用程序。
此外,每次浏览器向服务器请求URL时,网站的所有cookie数据都会在请求中自动发送到服务器。 这意味着如果您在用户系统上存储了5个Cookie,每个Cookie的大小为4KB,则浏览器需要在用户每次查看页面时上传20KB的数据,这可能会影响您站点的性能。
您可以通过使用PHP session来解决这两个问题。 PHP session将数据存储在服务器而不是用户的计算机上。 在基于会话的环境中,每个用户都是通过称为会话标识符或SID的唯一编号来标识的。 此唯一的会话ID用于将每个用户与自己在服务器上的信息(例如电子邮件,帖子等)链接起来。
提示:session ID是由PHP引擎随机生成的,几乎无法猜测。此外,由于会话数据存储在服务器上,因此不必随每个浏览器请求一起发送。
开始 Session
在将任何信息存储在会话变量中之前,必须首先启动Session。要开始新的Session,只需调用PHP session_start()函数。它将创建一个新会话并为用户生成一个唯一的Session ID。
下面示例中的PHP代码只是开始一个新Session。
<?php
//开始 session
session_start();
?>
session_start()函数首先通过查找会话ID的存在来检查会话是否已经存在。如果找到一个会话,即会话已经启动,则设置会话变量,如果没有,则通过创建新的会话ID来启动新会话。
注意:您必须session_start()在页面的开头(即在浏览器中脚本生成的任何输出之前)调用该函数,就像在使用setcookie()函数设置cookie时一样。
存储和访问Session数据
您可以将所有会话数据作为键值对存储在$_SESSION[]超全局数组中。可以在会话的生存期内访问存储的数据。看以下脚本,该脚本创建一个新会话并注册两个会话变量。
<?php
//正在启动会话
session_start();
//存储会话数据
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";
?>
要访问我们在上一个示例中从同一Web域的任何其他页面上设置的会话数据,只需调用session_start()即可重新创建会话,然后将相应的键传递给$_SESSION关联数组。
<?php
//正在启动会话
session_start();
//访问会话数据
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];
?>
<?php
//启动会话
session_start();
//正在删除会话数据
if(isset($_SESSION["lastname"])){
unset($_SESSION["lastname"]);
}
?>
但是,要完全销毁会话,只需调用session_destroy()函数。该函数不需要任何参数,一次调用会销毁所有会话数据。
<?php
//启动会话
session_start();
//销毁会话
session_destroy();
?>
3)、PHP Cookie
123
2、判断链接失效与否
<?php
$pageDocument = @file_get_contents('http://101.33.205.8:6671/');
if ($pageDocument === false) {
echo "该链接已失效";
}else{
echo '该链接正常';
}
3、响应码302|301地址获取|curl函数
```
<?php
function get_redirect_url($url){
$header = get_headers($url, 1);
if (strpos($header[0], '301') !== false || strpos($header[0], '302') !== false) {
if(is_array($header['location'])) {
return $header['location'][count($header['location'])-1];
}else{
return $header['location'];
}
}else {
return $url;
}
}
function httpget($url) {
$curl = curl_init();
//1.初始化,创建一个新cURL资源
$UserAgent = 'Mozilla/6.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36';
curl_setopt($curl, CURLOPT_URL, $url);
//2.设置URL curl_setopt($ch, CURLOPT_URL, "http://www.lampbrother.net/");
// 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
//在发起连接前等待的时间,如果设置为0,则无限等待。
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//设定是否显示头信息
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//启用时会将服务器服务器返回的"Location: "放在header中递归的返回给服务器,设置可以302跳转
curl_setopt($curl, CURLOPT_REFERER, "http://www.gov.com");
//构造来路
curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
//gzip压缩内容
$data = curl_exec($curl);
// 抓取URL并把它传递给浏览器
curl_close($curl);
return $data;
}
function xianlu ($xianlu,$xl){
global $arr;
$fh = httpget($xianlu);
$jx = json_decode($fh, true);
$code = $jx["code"];
if($code==200 && strpos($jx["url"],'=') == true){//第三个接口解析成功
$arr = array(
'code' => $jx["code"],
'url' => $jx["url"],
'type' =>$jx["type"],
'success' =>$jx["success"],
'msg' =>"安逸直解系统".$xl,
'title' =>"官网:http://ayjx.wchulian.com.cn/",
);
return $arr;
}else{//第三个接口解析失败
return 0;
}
}
$jxurl ="https://jx.mmkv.cn/json.php?url=".$_GET['url'];
$arr=xianlu ($jxurl,"线路二");
if($arr==0){
}else{
$newurl = get_redirect_url($arr['url']);
if(strpos($newurl,'http') !== false){
}else{
$newurl="http:".$newurl;
}
$arr['url']=$newurl;
}
echo json_encode($arr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?>
```
4、得到请求者IP
function getIP()
{
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;
}
4.1文件存在、删除、复制、重命名
$file=$configinfo->guanjiemulu."/jiekoufile.php";
if(file_exists($file)){//文件存在
unlink($file); //删除文件
$copy=false;
$suijishu=rand(1,500);
$newfile = $configinfo->guanjiemulu."/config/jiekoufile".suijishu.".php";
if(copy($file, $newfile)){//文件复制
$copy=true;
}
}
//重命名 $configinfo->guanjiemulu.'/config'是目录
changeTypeName(1,$configinfo->guanjiemulu.'/config', 'jiekoufile.php', 'jiekoufile'.$suijishu.'.php');
5、获取应用包名
$itynz1=$_SERVER['HTTP_X_REQUESTED_WITH']=="com.laowang.yunshop";
6、首拼算法
```
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<?php
function getfirstchar($s0){ //获取单个汉字拼音首字母。注意:此处不要纠结。汉字拼音是没有以U和V开头的
$fchar = ord($s0{0});
if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
$s1 = iconv("UTF-8","gb2312", $s0);
$s2 = iconv("gb2312","UTF-8", $s1);
if($s2 == $s0){$s = $s1;}else{$s = $s0;}
$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
if($asc >= -20319 and $asc <= -20284) return "A";
if($asc >= -20283 and $asc <= -19776) return "B";
if($asc >= -19775 and $asc <= -19219) return "C";
if($asc >= -19218 and $asc <= -18711) return "D";
if($asc >= -18710 and $asc <= -18527) return "E";
if($asc >= -18526 and $asc <= -18240) return "F";
if($asc >= -18239 and $asc <= -17923) return "G";
if($asc >= -17922 and $asc <= -17418) return "H";
if($asc >= -17922 and $asc <= -17418) return "I";
if($asc >= -17417 and $asc <= -16475) return "J";
if($asc >= -16474 and $asc <= -16213) return "K";
if($asc >= -16212 and $asc <= -15641) return "L";
if($asc >= -15640 and $asc <= -15166) return "M";
if($asc >= -15165 and $asc <= -14923) return "N";
if($asc >= -14922 and $asc <= -14915) return "O";
if($asc >= -14914 and $asc <= -14631) return "P";
if($asc >= -14630 and $asc <= -14150) return "Q";
if($asc >= -14149 and $asc <= -14091) return "R";
if($asc >= -14090 and $asc <= -13319) return "S";
if($asc >= -13318 and $asc <= -12839) return "T";
if($asc >= -12838 and $asc <= -12557) return "W";
if($asc >= -12556 and $asc <= -11848) return "X";
if($asc >= -11847 and $asc <= -11056) return "Y";
if($asc >= -11055 and $asc <= -10247) return "Z";
return NULL;
//return $s0;
}
function pinyin_long($zh){ //获取整条字符串汉字拼音首字母
$hz=$zh;
$ret = "";
$s1 = iconv("UTF-8","gb2312", $zh);
$s2 = iconv("gb2312","UTF-8", $s1);
if($s2 == $zh){$zh = $s1;}
for($i = 0; $i < strlen($zh); $i++){
$s1 = substr($zh,$i,1);
$p = ord($s1);
if($p > 160){
$s2 = substr($zh,$i++,2);
$ret .= getfirstchar($s2);
}else{
$ret .= $s1;
}
}
return "汉字:".$hz.",首拼:".$ret;
}
echo pinyin_long('斗罗大陆');
?>
```
7、跨域设置
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin');
header('content-type:application/json');
或者
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, token, platform' always;
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,HEAD,OPTIONS' always;
if ($request_method = OPTIONS ) {
return 200;
}
8、模拟Post请求
<?php
/**
$url="https://api.aliyundrive.com/token/refresh";
$body = array("refresh_token"=>"7947dfb97d46493297531987940779f9");//
$header = array("Content-Type:application/json; charset=utf-8", "Content-Length:52", "Accept-Encoding:gzip, deflate, br");
$client = new Client();
$request = $client->request('POST',$url,['headers'=>$header,'verify' => false,'timeout' => 600,'json' => $body]);
$http_status = $request->getStatusCode(); // 响应状态码
$response = $request->getBody()->getContents(); //响应内容
print_r($response);
*/
require_once('config.php');
$url="https://api.aliyundrive.com/token/refresh";
$body = array("refresh_token"=>TOKEN);//
$header = array("Content-Type:application/json; charset=utf-8", "Content-Length:52", "Accept-Encoding:gzip");
$result = curlPost($url, $body, 5, $header, 'json');
$jx = json_decode($result, true);
if($jx['refresh_token']!=null && $jx['user_name']!=null && strlen($jx['refresh_token'])>20){
$str='<?php
define("ALIYUNMA","'.$jx['refresh_token'].'");';
file_put_contents('refresh_token.php',$str );
echo "refresh_token生成成功(账号正常)";
}else{
echo "refresh_token生成失败 (请检测账号|请重新登录账号赋值token)";
}
exit;
$url="https://api.aliyundrive.com/token/refresh";
$body = array("refresh_token"=>TOKEN);//
$header = array("Content-Type:application/json; charset=utf-8", "Content-Length:52", "Accept-Encoding:gzip");
$result = curlPost($url, $body, 5, $header, 'json');
function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "") {
$header = empty($header) ? '' : $header;
//支持json数据数据提交
if($data_type == 'json'){
$post_string = json_encode($post_data);
}elseif($data_type == 'array') {
$post_string = $post_data;
}elseif(is_array($post_data)){
$post_string = http_build_query($post_data, '', '&');
}
$ch = curl_init(); // 启动一个CURL会话
curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查 // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
// curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36');
curl_setopt($ch, CURLOPT_REFERER, 'https://www.aliyundrive.com/');
curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); // Post提交的数据包
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // 设置超时限制防止死循环
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_ENCODING, '');//解决网页乱码问题 很重要
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
// 打印请求的header信息
// $a = curl_getinfo($ch);
// var_dump($a);
$data = curl_exec($ch); //运行 curl,请求网页并返回结果
curl_close($ch); //关闭 curl
return $data;
}
function httpget($url,$time) {
$ip = rand_ip();
$header = array('X-FORWARDED-FOR:'.$ip,'CLIENT-IP:'.$ip);
//$header = array('X-FORWARDED-FOR:150.138.236.146','CLIENT-IP:150.138.236.146');
$curl = curl_init();
//1.初始化,创建一个新cURL资源
$UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36';
curl_setopt($curl, CURLOPT_URL, $url);
//2.设置URL curl_setopt($ch, CURLOPT_URL, "http://www.lampbrother.net/");
// 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_TIMEOUT, $time);
//在发起连接前等待的时间,如果设置为0,则无限等待。
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//设定是否显示头信息
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//启用时会将服务器服务器返回的"Location: "放在header中递归的返回给服务器,设置可以302跳转
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//IP
curl_setopt($curl, CURLOPT_REFERER, $url); //来路
//构造来路
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
//gzip压缩内容
$data = curl_exec($curl);
// 抓取URL并把它传递给浏览器
curl_close($curl);
return $data;
}
function rand_ip() { //模拟随机IP传输
$ip_long = array(
array('607649792', '608174079'), //36.56.0.0-36.63.255.255
array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
array('-569376768', '-564133889') //222.16.0.0-222.95.255.255
);
$rand_key = mt_rand(0, 9);
$ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
return $ip;
}
?>
8.2、非常完美的Post请求,可以知道responseHeader,以及请求的Header
public function postcurl($url, $post=0, $referer=0, $cookie=0, $responseheader=0, $ua=0, $nobody=0, $addheader=0)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$httpheader[] = "Accept: */*";
if($addheader){
$httpheader = array_merge($httpheader, $addheader);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
if ($post) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
if ($responseheader) {
curl_setopt($ch, CURLOPT_HEADER, true); //返回response头部信息
/*
HTTP/1.1 200
Date: Fri, 29 Sep 2023 00:58:25 GMT
Content-Type: text/html;charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Access-Control-Allow-Origin: http://noteyd.chaoxing.com;
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: X-Requested-With
Access-Control-Max-Age: 3600
Set-Cookie: route=296402a7cd970841220a338d7a62edb8; Path=/
Referrer-Policy: unsafe-url
Origin-Agent-Cluster: ?0
Content-Encoding: gzip
*/
//TRUE 时追踪句柄的请求字符串,从 PHP 5.1.3 开始可用。这个很关键,就是允许你查看请求header
//怎么查看自己的请求header --》echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
}
if ($cookie) {
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
if($referer){
curl_setopt($ch, CURLOPT_REFERER, $referer);
}
if ($ua) {
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
}
else {
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
}
if ($nobody) {
curl_setopt($ch, CURLOPT_NOBODY, 1);
}
curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret = curl_exec($ch);
//官方文档描述是“发送请求的字符串”,其实就是请求的header。这个就是直接查看请求header,因为上面允许查看
// echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
curl_close($ch);
return $ret;
}
8、模拟GET请求
function httpget($url, $timeout = 15)
{
$ip= rand_ip();
$duankou=rand(1009,9999);
$ch = curl_init(); //初始化 curl
curl_setopt($ch, CURLOPT_URL, $url); //要访问网页 URL 地址
curl_setopt($ch, CURLOPT_NOBODY, false); //设定是否输出页面内容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而非直接输出到屏幕上
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, false); //连接超时时间,设置为 0,则无限等待
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //数据传输的最大允许时间超时,设为一小时
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); //HTTP验证方法
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不检查 SSL 证书来源
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不检查 证书中 SSL 加密算法是否存在
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //跟踪爬取重定向页面
curl_setopt($ch, CURLOPT_AUTOREFERER, true); //当Location:重定向时,自动设置header中的Referer:信息
curl_setopt($ch, CURLOPT_ENCODING, ''); //解决网页乱码问题
curl_setopt($ch, CURLOPT_REFERER, $ip.':'.$duankou);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
$httpheaders = array();
$httpheaders[] = "CLIENT-IP: $ip:$duankou";
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
$data = curl_exec($ch); //运行 curl,请求网页并返回结果
curl_close($ch); //关闭 curl
// echo $data;
return $data;
}
8.1、httpget获取数据以及获取该链接响应的状态码200 404 403 501
$zt=1:获取网页数据代码
$zt=2:该链接的响应状态码
function Curl($url, $zt)
{
$ch = curl_init();
$user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:' . Rand_IP(), 'CLIENT-IP:' . Rand_IP()));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_NOBODY, false);
//构造来路
curl_setopt($ch, CURLOPT_REFERER, "");
//构造来路
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
$temp = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);//获取http返回状态码code 例如200 400
curl_close($ch);
if ($zt == 1) {
return $temp;
} elseif ($zt == 2) {
return $httpCode;
}
}
9、请求授权代码(基础php形式)
require_once('Cryptrc4.php');
// 缓存授权 授权开始-授权开始-授权开
function logPhpAuthorization()
{
// print_r($_SERVER);
$redis = new Redis(); //实例化redis
$redis->connect('127.0.0.1', 6379); //连接
if(isset($_GET['cleanredis']) && $_GET['cleanredis']=="cleanredis"){
$redis->set('alyrediskey', null, 3600 * 24 * 2);
$redis->set('alyredis', null, 3600 * 24 * 2);
if(isset($_GET['domain']) && $_GET['domain']=="domain"){
echo("CACHE清理成功ec");
}else{
exit("CACHE清理成功ex");
}
}
$rc4 = new Cryptrc4();
$rc4 -> setKey('xxxx');//Rc4密钥
//授权开始
$Num = rand(0, 2);
$arrdata = array(
"xxxx",
"xxx",
"xxxxx",
);
$sqdomian=$arrdata[$Num];
$baotaxsmdata = $redis->get('alyrediskey');
$random=rand(0, 4000);
// echo $random.$baotaxsmdata;
if($random > 3950){
$baotaxsmdata="kongkong";
}
// $baotaxsmdata="kongkong";
if($baotaxsmdata!="alyredisdata"){
$httphost = $redis->get('alyredis');
$guanwang="xxx";
if(empty($httphost)){//判断数据是否存在
$httphost=httpget($sqdomian,5);
$jiami_urls=explode(',',$httphost);
$guanwang=$jiami_urls[1];
$domain = $rc4->decrypt($jiami_urls[0]);
$redis->set('alyredis', $httphost, 3600 * 24 * 2);
}else{
$jiami_urls=explode(',',$httphost);
$guanwang=$jiami_urls[1];
$domain = $rc4->decrypt($jiami_urls[0]);
}
$REQUESTURI=$_SERVER['DOCUMENT_URI'];
if(strpos($REQUESTURI,"/")!==false){
$REQUESTURI=str_replace("/","",$REQUESTURI);
}
if(isset($_GET['cleanredis']) && $_GET['cleanredis']=="cleanredis"){
if(isset($_GET['domain']) && $_GET['domain']=="domain"){
exit( $domain);
}
}
$domianUrl=$domain."/home/index/sqconf?act=sqapiSearchUrl&free=aliyunpanalgorithm&requesturl=$REQUESTURI&url=".$_SERVER['HTTP_HOST'];
// echo $domianUrl;
$urlData = @json_decode(httpget($domianUrl,5),TRUE);
// print_r($urlData);
$jiexiflag=false;
if (!is_array($urlData)){
$realip = $_SERVER["HTTP_HOST"];
if(strpos($realip,'xxxx') !== false){
$jiexiflag=true;
// echo "isarray";
$redis->set('alyrediskey', "alyredisdata", 3600 * 24*7);
}
else{
exit("<center>1xxxx</center>");
}
}
if(!$jiexiflag){
if ($urlData['code']==200&&$urlData['shouquan']=='shouquan'){
if($urlData['codeid']=='siteUse'){
echo htmlspecialchars_decode($urlData['msg']);
}else if($urlData['codeid']=='siteNoUse'){
exit(htmlspecialchars_decode($urlData['msg']));
}else{
$redis->set('alyrediskey', "alyredisdata", 3600 * 24*3);
}
}else{
exit(htmlspecialchars_decode($urlData['msg']));
}
}
//授权结束
}
}
logPhpAuthorization();
//缓存授权 授权结束-授权结束-授权结束
10、将字符串或者其他写入文件
file_put_contents("config.php","<?php
define('TOKEN','".$jx['token']."');
?>
");
11、redis连接(基础php)
$redis = new Redis(); //实例化redis
$redis->connect('127.0.0.1', 6379); //连接
$alyhostkey = $redis->get('alyhostkey');
$redis->set('alydatakey', "alydatavalue", 3600 * 24*7);
12、获取文件名 | 文件重命名
$REQUESTURI=$_SERVER['DOCUMENT_URI'];
if(strpos($REQUESTURI,"/")!==false){
$REQUESTURI=str_replace("/","",$REQUESTURI);
}
//重命名 $configinfo->guanjiemulu.'/config'是目录
changeTypeName(1,$configinfo->guanjiemulu.'/config', 'jiekoufile.php', 'jiekoufile'.$suijishu.'.php');
13、判断字符串存在
if(strpos($_GET['url'],'xueren.tv') !== false){}
14、将字符串输出成json
exit(json_encode($arr,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));//返回缓存json,不执行下面代码
15、输出404
header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
16、mysql数据库的连接
$_config = require_once($_SERVER["DOCUMENT_ROOT"] . "/dmku/config.inc.php");
$conn = mysqli_connect($_config['数据库']['地址'], $_config['数据库']['用户名'], $_config['数据库']['密码'], $_config['数据库']['名称']);
$ip=$_SERVER['REMOTE_ADDR'];
#查询数据
$sql = "select * from danmaku_playip where ip='$ip' ORDER BY id DESC";
$qapi = mysqli_query($conn, $sql);
$ipinfo = mysqli_fetch_assoc($qapi);
if($ipinfo['state']=="0"){
echo "禁用";
}
# 插入数据
$sql = "INSERT INTO `danmaku_userjiexi` (`id`,`title` ,`url` ,`newurl` ,`state` ,`intime`,`ip`)VALUES (NULL, '$title' , '$url', '$newurl', '0', '$time','$ip')";
$conn->query($sql);
17、将文件删除|写入
删除文件
$filename = '../apiuser.json';
unlink($filename);
写入文件
$json_string=json_encode($_SERVER);
file_put_contents($filename, $json_string);
if(strpos($xianlu,":5244")!==false){
$urldata=explode('&url=',$xianlu)[1];
$urldata=str_replace(' ','%20',$urldata);
$urldata=str_replace('+','%2B',$urldata);
file_put_contents($filename, $json_string);
$arr = array('code' => 200, 'url' =>$urldata, 'type' => 'm3u8', 'success' => '1');
return $arr;
}
18、switch功能
function error($type,$yzm){
switch ($type) {
case 'rixianzhi':
$json = [
'code' => 200,
'url' => $yzm['rixianzhivideo'],
'msg' => "日限制功能"
];
break;
case 'jiexishibai':
$json = [
'code' => 200,
'url' => $yzm['shibaivideo'],
'msg' => "解析视频失败"
];
break;
case 'heimingdan':
$json = [
'code' => 200,
'url' => $yzm['fangdaovideo'],
'msg' => "未经授权无法使用"
];
break;
default:
// code...
break;
}
return $json;
}
19、黑名单IP授权(in_array)
$ip = $_SERVER['REMOTE_ADDR'];
$zdfdhost = explode("|", '43.136.107.141|43.136.107.142|203.168.20.225');
if (in_array($ip, $zdfdhost) ) {//in_array:$ip是否是存在数组$zdfdhost中?
echo "该数据存在该数组中";;//将授权功能关闭
}else{
echo "该数据不存在该数组中";
}
$urlArr = explode("//", $_SERVER["HTTP_REFERER"])[1];
$host = explode("/", $urlArr)[0];
$host = explode(":", $host)[0];
$fdhost = explode(",", $yzm["fdhost"]);
$localhost = explode(":", $_SERVER["HTTP_HOST"])[0];
$fdhost[] = $localhost;
if ($yzm["blank_referer"] == "on") {
$fdhost[] = "";
}
define('AuthoriZation',0);//数据库名称
define('IPS',"101.33.205.8|101.33.205.9|117.61.106.32|43.136.107.141");//|隔开
//授权代码
if(AuthoriZation){
$serverIp=$_SERVER['REMOTE_ADDR'];
$serverIpS=explode('|',IPS);
if (!in_array($serverIp, $serverIpS) ) {
header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
exit;
}
}
//授权结束
//若来源referer是空的 开启空referer则成功跳过授权
//然后就根据调用者IP=$_SERVER['REMOTE_ADDR']
//某个站点来源IP =$_SERVER['HTTP_REFERER']
//只要符合授权IP 就成功跳过授权
function checkRefere($conf){
$baomings = explode("|", $conf["zdfdhost"]);//获取后台授权的包名
$baoming=$_SERVER['HTTP_X_REQUESTED_WITH'];//获取请求者应用包名
$enableUseDesign=false;
if (in_array($baoming, $baomings) ) {
$enableUseDesign=true;
}
if ($conf["fdhost_on"] == "on") {
if ($conf["blank_referer"] == "on") {
if(empty($_SERVER['HTTP_REFERER'])){
$enableUseDesign=true;
}
}
//IP授权
$fdhost = $_SERVER['REMOTE_ADDR'];
$fdhosts = explode("|", $conf["fdhost"]);
//来源访问授权
$referers = $_SERVER['HTTP_REFERER'];
$referers=explode('/player',$referers)[0];
$referers=explode(':',$referers);
$referer=str_replace('//','',$referers[1]);
if( in_array($referer, $fdhosts) ){
$enableUseDesign=true;
}
if( in_array($fdhost, $fdhosts) ){
$enableUseDesign=true;
}
if (!$enableUseDesign) {
exit("你调用者IP,和来源IP都不符合授权条件");
}
}
}
20、常见正则表达式 PHP
if (preg_match('/v.qq.com/x/cover/(.*)/(.*?).html/',$url,$r)) {
}
Array
(
[0] => v.qq.com/x/cover/mzc00200c16fwl5/y0046hozbd5.html
[1] => mzc00200c16fwl5
[2] => y0046hozbd5
)
if(PROXYSERVERKG && !empty(PROXYSERVERKG)){
curl_setopt($curl, CURLOPT_PROXY, '27.156.109.44:64256');
}
一、校验数字的表达式
数字:^[0-9]*$
n位的数字:^d{n}$
至少n位的数字:^d{n,}$
m-n位的数字:^d{m,n}$
零和非零开头的数字:^(0|[1-9][0-9]*)$
非零开头的最多带两位小数的数字:^([1-9][0-9]*)+(.[0-9]{1,2})?$
带1-2位小数的正数或负数:^(-)?d+(.d{1,2})?$
正数、负数、和小数:^(-|+)?d+(.d+)?$
有两位小数的正实数:^[0-9]+(.[0-9]{2})?$
有1~3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$
非零的正整数:^[1-9]d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^+?[1-9][0-9]*$
非零的负整数:^-[1-9][]0-9"*$ 或 ^-[1-9]d*$
非负整数:^d+$ 或 ^[1-9]d*|0$
非正整数:^-[1-9]d*|0$ 或 ^((-d+)|(0+))$
二、校验字符的表达式
汉字:^[u4e00-u9fa5]{0,}$
英文和数字:^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$
长度为3-20的所有字符:^.{3,20}$
由26个英文字母组成的字符串:^[A-Za-z]+$
由26个大写英文字母组成的字符串:^[A-Z]+$
由26个小写英文字母组成的字符串:^[a-z]+$
由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$
由数字、26个英文字母或者下划线组成的字符串:^w+$ 或 ^w{3,20}$
中文、英文、数字包括下划线:^[u4E00-u9FA5A-Za-z0-9_]+$
中文、英文、数字但不包括下划线等符号:^[u4E00-u9FA5A-Za-z0-9]+$ 或 ^[u4E00-u9FA5A-Za-z0-9]{2,20}$
可以输入含有^%&',;=?$"等字符:[^%&',;=?$x22]+
禁止输入含有~的字符:[^~x22]+
三、特殊需求表达式
Email地址:^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$
域名:[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?
InternetURL:[a-zA-z]+://[^s]* 或 ^http://([w-]+.)+[w-]+(/[w-./?%&=]*)?$
手机号码:^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])d{8}$
电话号码("XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX):^((d{3,4}-)|d{3.4}-)?d{7,8}$
国内电话号码(0511-4405222、021-87888822):d{3}-d{8}|d{4}-d{7}
身份证号:
15或18位身份证:^d{15}|d{18}$
15位身份证:^[1-9]d{7}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])d{3}$
18位身份证:^[1-9]d{5}[1-9]d{3}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])d{4}$
短身份证号码(数字、字母x结尾):^([0-9]){7,18}(x|X)?$ 或 ^d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$
帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线):^[a-zA-Z]w{5,17}$
强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间):^(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$
日期格式:^d{4}-d{1,2}-d{1,2}
一年的12个月(01~09和1~12):^(0?[1-9]|1[0-2])$
一个月的31天(01~09和1~31):^((0?[1-9])|((1|2)[0-9])|30|31)$
中文字符的正则表达式:[u4e00-u9fa5]
空白行的正则表达式:ns*r (可以用来删除空白行)
HTML标记的正则表达式:<(S*?)[^>]*>.*?</1>|<.*? /> (网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力)
首尾空白字符的正则表达式:^s*|s*$或(^s*)|(s*$) (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式)
腾讯QQ号:[1-9][0-9]{4,} (腾讯QQ号从10000开始)
中国邮政编码:[1-9]d{5}(?!d) (中国邮政编码为6位数字)
IP地址:d+.d+.d+.d+ (提取IP地址时有用)
21、个常用正则表达式速查表
1、校验数字的表达式
- 数字:
^[0-9]*$
- n位的数字:
^d{n}$
- 至少n位的数字:
^d{n,}$
- m-n位的数字:
^d{m,n}$
- 零和非零开头的数字:
^(0|[1-9][0-9]*)$
- 非零开头的最多带两位小数的数字:
^([1-9][0-9]*)+(.[0-9]{1,2})?$
- 带1-2位小数的正数或负数:
^(-)?d+(.d{1,2})?$
- 正数、负数、和小数:
^(-|+)?d+(.d+)?$
- 有两位小数的正实数:
^[0-9]+(.[0-9]{2})?$
- 有1~3位小数的正实数:
^[0-9]+(.[0-9]{1,3})?$
- 非零的正整数:
^[1-9]d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^+?[1-9][0-9]*$
- 非零的负整数:
^-[1-9][]0-9"*$ 或 ^-[1-9]d*$
- 非负整数:
^d+$ 或 ^[1-9]d*|0$
- 非正整数:
^-[1-9]d*|0$ 或 ^((-d+)|(0+))$
- 非负浮点数:
^d+(.d+)?$ 或 ^[1-9]d*.d*|0.d*[1-9]d*|0?.0+|0$
- 非正浮点数:
^((-d+(.d+)?)|(0+(.0+)?))$ 或 ^(-([1-9]d*.d*|0.d*[1-9]d*))|0?.0+|0$
- 正浮点数:
^[1-9]d*.d*|0.d*[1-9]d*$ 或 ^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$
- 负浮点数:
^-([1-9]d*.d*|0.d*[1-9]d*)$ 或 ^(-(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*)))$
- 浮点数:
^(-?d+)(.d+)?$ 或 ^-?([1-9]d*.d*|0.d*[1-9]d*|0?.0+|0)$
2、校验字符的表达式
- 汉字:
^[u4e00-u9fa5]{0,}$
- 英文和数字:
^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$
- 长度为3-20的所有字符:
^.{3,20}$
- 由26个英文字母组成的字符串:
^[A-Za-z]+$
- 由26个大写英文字母组成的字符串:
^[A-Z]+$
- 由26个小写英文字母组成的字符串:
^[a-z]+$
- 由数字和26个英文字母组成的字符串:
^[A-Za-z0-9]+$
- 由数字、26个英文字母或者下划线组成的字符串:
^w+$ 或 ^w{3,20}
- 中文、英文、数字包括下划线:
^[u4E00-u9FA5A-Za-z0-9_]+$
- 中文、英文、数字但不包括下划线等符号:
^[u4E00-u9FA5A-Za-z0-9]+$ 或 ^[u4E00-u9FA5A-Za-z0-9]{2,20}$
- 可以输入含有
^%&',;=?$"
等字符:[^%&',;=?$x22]+
- 禁止输入含有~的字符
[^~x22]+
3、其它:
.*
匹配除 n
以外的任何字符。
/[u4E00-u9FA5]/
汉字
/[uFF00-uFFFF]/
全角符号
/[u0000-u00FF]/
半角符号
4、特殊需求表达式
- Email地址:
^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$
- 域名:
[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?
- InternetURL:
[a-zA-z]+://[^s]* 或 ^http://([w-]+.)+[w-]+(/[w-./?%&=]*)?$
- 手机号码:
^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])d{8}$
- 电话号码("XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX):
^((d{3,4}-)|d{3.4}-)?d{7,8}$
- 国内电话号码(0511-4405222、021-87888822):
d{3}-d{8}|d{4}-d{7}
- 身份证号(15位、18位数字):
^d{15}|d{18}$
- 短身份证号码(数字、字母x结尾):
^([0-9]){7,18}(x|X)?$ 或 ^d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$
- 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):
^[a-zA-Z][a-zA-Z0-9_]{4,15}$
- 密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线):
^[a-zA-Z]w{5,17}$
- 强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间):
^(?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$
- 日期格式:
^d{4}-d{1,2}-d{1,2}
- 一年的12个月(01~09和1~12):
^(0?[1-9]|1[0-2])$
- 一个月的31天(01~09和1~31):
^((0?[1-9])|((1|2)[0-9])|30|31)$
5、钱的输入格式:
1.有四种钱的表示形式我们可以接受:"10000.00" 和 "10,000.00", 和没有 "分" 的 "10000" 和 "10,000":^[1-9][0-9]*$
2.这表示任意一个不以0开头的数字,但是,这也意味着一个字符"0"不通过,所以我们采用下面的形式:^(0|[1-9][0-9]*)$
3.一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号:^(0|-?[1-9][0-9]*)$
4.这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分:^[0-9]+(.[0-9]+)?$
5.必须说明的是,小数点后面至少应该有1位数,所以"10."是不通过的,但是 "10" 和 "10.2" 是通过的:^[0-9]+(.[0-9]{2})?$
6.这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样:^[0-9]+(.[0-9]{1,2})?$
7.这样就允许用户只写一位小数.下面我们该考虑数字中的逗号了,我们可以这样:^[0-9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$
8.1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须:^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$
备注:这就是最终结果了,别忘了
+
可以用*
替代如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里
- xml文件:
^([a-zA-Z]+-?)+[a-zA-Z0-9]+.[x|X][m|M][l|L]$
- 中文字符的正则表达式:
[u4e00-u9fa5]
- 双字节字符:
[^x00-xff]
(包括汉字在内,可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)) - 空白行的正则表达式:
ns*r
(可以用来删除空白行) - HTML标记的正则表达式:
<(S*?)[^>]*>.*?</1>|<.*? />
(网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力) - 首尾空白字符的正则表达式:
^s*|s*$或(^s*)|(s*$)
(可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式) - 腾讯QQ号:
[1-9][0-9]{4,}
(腾讯QQ号从10000开始) - 中国邮政编码:
[1-9]d{5}(?!d)
(中国邮政编码为6位数字) - IP地址:
d+.d+.d+.d+
(提取IP地址时有用) - IP地址:
((?:(?:25[0-5]|2[0-4]d|[01]?d?d).){3}(?:25[0-5]|2[0-4]d|[01]?d?d))
- IP-v4地址:
b(?:(?: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]?)b
(提取IP地址时有用) - 校验IP-v6地址:
(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))
- 子网掩码:
((?:(?:25[0-5]|2[0-4]d|[01]?d?d).){3}(?:25[0-5]|2[0-4]d|[01]?d?d))
- 校验日期:
^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$
(“yyyy-mm-dd“ 格式的日期校验,已考虑平闰年。) - 抽取注释:
<!--(.*?)-->
- 查找CSS属性:
^s*[a-zA-Z-]+s*[:]{1}s[a-zA-Z0-9s.#]+[;]{1}
- 提取页面超链接:
(<as*(?!.*brel=)[^>]*)(href="https?://)((?!(?:(?:www.)?'.implode('|(?:www.)?', $follow_list).'))[^" rel="external nofollow" ]+)"((?!.*brel=)[^>]*)(?:[^>]*)>
- 提取网页图片:
< *[img][^>]*[src] *= *["']{0,1}([^"' >]*)
- 提取网页颜色代码:
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
- 文件扩展名效验:
^([a-zA-Z]:|)([^]+)*[^/:*?"<>|]+.txt(l)?$
- 判断IE版本:
^.*MSIE [5-8](?:.[0-9]+)?(?!.*Trident/[5-9].0).*$
6、附表:
22、php的client(use GuzzleHttpClient;)函数自带curl(POST)
public function getToken()
{
$cachekey = md5('aliyundrive_access_token'.$this->refresh_token);
$token = $this->cache->get($cachekey);
if($token) return $token;
$logindata = [
'refresh_token' => $this->refresh_token,
'grant_type' => 'refresh_token'
];
$client = new Client();
$request = $client->request('POST','https://auth.aliyundrive.com/v2/account/token',['verify' => false,'timeout' => 60,'json' => $logindata]);
$http_status = $request->getStatusCode(); // 响应状态码
$response = $request->getBody()->getContents(); //响应内容
if($http_status==200){
$userinfo = json_decode($response,true);
$this->userinfo = $userinfo;
$this->access_token = $userinfo['access_token'];
$expires_in = (int)$userinfo['expires_in'] - 200;
$this->cache->set($cachekey,$userinfo['access_token'], $expires_in);
$this->cache->set(md5($this->userkey.$this->refresh_token),$userinfo);
return $userinfo['access_token'];
}
return '';
}
public function http($url,$data=[])
{
$token = $this->getToken();
$headers = [
'authorization' => 'Bearer '.$token,
'referer' => 'https://www.aliyundrive.com/',
'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
];
$client = new Client();
$request = $client->request('POST',$url,['headers'=>$headers,'verify' => false,'timeout' => 60,'json' => $data]);
$http_status = $request->getStatusCode(); // 响应状态码
$response = $request->getBody()->getContents(); //响应内容
if($http_status==200){
$redata = json_decode($response,true);
return $redata;
}
return false;
}
23、文件存在和配置判断
if(file_exists(__DIR__ . '/../config.php')){
$config = include(__DIR__ . '/../config.php');
$this->m3u8cachepath = $config['m3u8cachepath']??'m3u8';
$this->is_cachem3u8 = $config['is_cachem3u8']??false;
$this->tsm3u8file = $config['m3u8readfile']??'ts.php';
$this->is_m3u8auth = $config['is_m3u8auth']??true;
// $this->is_keepm3u8 = $config['is_keepm3u8']??false;
}else{
exit('配置缺失');
}
//重命名 $configinfo->guanjiemulu.'/config'是目录
changeTypeName(1,$configinfo->guanjiemulu.'/config', 'jiekoufile.php', 'jiekoufile'.$suijishu.'.php');
24、数组遍历For foreach
foreach ($info as $key => $row) {
$list[] = [
'name'=>$row['name'],
'file_id'=>$row['file_id'],
'url'=>'/player/?url='.$this->pre_name.$drive_id.'.'.$row['file_id']
];
}
for ($i = 1; $i <= 100; $i++) {
$sum *= $i;
}
25、php基础文件调用php类
<?php
namespace qmyz;
use qmyzFileCache;
use qmyzAliyun;
class Jiexi
{
...
}?>
use qmyzJiexi;
$urlkey = isset($_GET['url'])?$_GET['url']:'';
if($urlkey){
(new jiexi())->jx();
}else{
echo json_encode(['code'=>404,'msg'=>'fail']);
}
26、php基础爬虫
//记录解析次数
// $_SERVER['PHP_SELF'];///jiekou/2.php
$str='1/2/3/4/jiekou/2.php';
//strrpos 获取以某字符最后出现的索引
$final=strrpos($str,'/');
$filenames=substr($str,$final + 1);
$filename=explode(".",$filenames)[0].".txt";
echo $filename;
$final=strrpos($_SERVER['PHP_SELF'],'/');
$filenames=substr($_SERVER['PHP_SELF'],$final + 1);
$filename=explode(".",$filenames)[0].".txt";
if(!file_exists($filename)){
$info="1|"."1|".date('Y-m-d H:i:s',time());
file_put_contents($filename, $info);
}else{
$fileContent=file_get_contents($filename);
$fileContents=explode('|',$fileContent);
$jintian=strtotime(date('Y-m-d',time()));
$filetime=strtotime($fileContents[2]);
if($filetime>=$jintian){
$allcount=$fileContents[0] + 1;
$todaycount=$fileContents[1] + 1;
$time=date('Y-m-d H:i:s',time());
$info=$allcount.'|'.$todaycount.'|'.$time;
file_put_contents($filename, $info);
}else{
$allcount=$fileContents[0] + 1;
$todaycount=1;
$time=date('Y-m-d H:i:s',time());
$info=$allcount.'|'.$todaycount.'|'.$time;
file_put_contents($filename, $info);
}
}
header('Content-type:text/json'); //这句话就是为了获取网页的源码 而不是代码的渲染
define('QYPATH', 'aylzhc/');//缓存文件夹
if (!is_dir('aylzhc/')) mkdir('aylzhc/');//创建目录
$DATA=curlget($jiexi,8);
preg_match('/"url": "(.*)",/',$DATA,$newurl);
preg_match('/"time": "(.*)",/',$DATA,$newtime);
preg_match('/"key": "(.*)",/',$DATA,$newkey);
<?php
Snoopy.class.php下载:https://bokeimages.oss-cn-hangzhou.aliyuncs.com/bokeimages/Snoopy.class.php
include 'Snoopy.class.php';
function httpget($url) {
$curl = curl_init();
//1.初始化,创建一个新cURL资源
$UserAgent = 'Mozilla/6.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36';
curl_setopt($curl, CURLOPT_URL, $url);
//2.设置URL curl_setopt($ch, CURLOPT_URL, "http://www.lampbrother.net/");
// 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
//在发起连接前等待的时间,如果设置为0,则无限等待。
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//设定是否显示头信息
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//启用时会将服务器服务器返回的"Location: "放在header中递归的返回给服务器,设置可以302跳转
curl_setopt($curl, CURLOPT_REFERER, "http://www.gov.com");
//构造来路
curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
//gzip压缩内容
$data = curl_exec($curl);
// 抓取URL并把它传递给浏览器
curl_close($curl);
return $data;
}
function xianlu ($xianlu,$xl){
global $arr;
$str = httpget($xianlu);
$a = substr($str,strpos($str,'(')+1);
$cost = substr($a,0,strpos($a,')'));
$jx = json_decode($cost, true);
$jx=$jx['result'];
if($jx["ad_info"]['nation']!=null || $jx["ad_info"]['province']!=null){
$arr = array(
'code' => 200,
'ip' => $jx["ip"],
'lat' =>$jx["location"]['lat'],
'lng' =>$jx["location"]['lng'],
'nation' =>$jx["ad_info"]['nation'],
'province' =>$jx["ad_info"]['province'],
'city' =>$jx["ad_info"]['city'],
'district' =>$jx["ad_info"]['district'],
'address' =>$jx["ad_info"]['nation'].$jx["ad_info"]['province'].$jx["ad_info"]['city'].$jx["ad_info"]['district'],
'msg' =>"安逸定位系统",
'title' =>"官网:http://dw.wchulian.com.cn/",
);
}else{
$arr = array(
'code' => 404,
'ip' => $_GET['ip'],
'msg' =>"安逸定位系统",
'title' =>"官网:http://dw.wchulian.com.cn/",
);
}
return $arr;
}
function getIP(){
global $ip;
if(getenv("HTTP_CLIENT_IP"))
$ip=getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR"))
$ip=getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR"))
$ip=getenv("REMOTE_ADDR");
else $ip="NULL";
return $ip;
}
if($_GET['ip']==null){
$ip=getIP();
}else{
$ip=$_GET['ip'];
}
$snoopy->fetchText("https://m.ip138.com/iplookup.asp?ip=".$ip."&action=2");
$str=$snoopy->results;
$str= strstr($str, '您查询的IP');
$infotwo = substr($str,0,strrpos($str ,"更多参考"));
$a = substr($infotwo,strpos($str,'IP')+5);
$ip = substr($a,0,strpos($a,'ASN'));
$addr = substr($infotwo,strpos($str,'归属地')+9);
/*
$ip=$_GET['ip'];
$snoopy->fetchText("https://ip.hao86.com/$ip/");
$str=$snoopy->results;
// echo $str;
$str= strstr($str, '地理定位');
$infotwo = substr($str,0,strrpos($str ,"操作系统"));
$weizhi=explode('定位',$infotwo)[1];
*/
$arr = array(
'code' => 200,
'ip' => $_GET['ip'],
'address' =>$addr,
'msg' =>"安逸定位系统线路2",
'title' =>"官网:http://dw.wchulian.com.cn/",
);
echo json_encode($arr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?>
27、IP接口
IP文件和爬虫文件下载:
https://bokeimages.oss-cn-hangzhou.aliyuncs.com/bokeimages/ips_w5aKes.tar.gz
https://apis.map.qq.com/ws/location/v1/ip?callback=window._JSONP_callback.JSONP9424&ip=101.33.205.8&key=TKUBZ-D24AF-GJ4JY-JDVM2-IBYKK-KEBCU&output=jsonp&t=1610783153333
https://api.kieng.cn/ipgeography?ip=101.33.205.8
http://api.k780.com/?app=ip.get&ip=101.33.205.8&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
https://m.ip138.com/iplookup.asp?ip=
28、php文件代码错误忽略提示
error_reporting(0)
29、将unicode(u4e2du56fd==中国)转义成中文
public function unicodeString($str, $encoding=null) {
return preg_replace_callback('/u([0-9a-fA-F]{4})/u',
create_function('$match', 'return
mb_convert_encoding(pack("H*", $match[1]), "utf-8", "UTF-16BE");'), $str);
}
//将数组转义成json字符串 然后再将unicode转义成中文
$info=$this->unicodeString(json_encode($cache));
file_put_contents("typeinfo.json", $info);
30、将数组对象转义成json字符串,在将json字符串转义成json对象 或者数组
<?php
// 定义一个将unicdeo转义成中文的办法
function unicodeDecode($unicode_str){
$json = '{"str":"'.$unicode_str.'"}';
$arr = json_decode($json,true);
if(empty($arr)) return '';
return $arr['str'];
}
// 定义一个将中文转义成unicode的办法
function UnicodeEncode($str){
preg_match_all('/./u',$str,$matches);
$unicodeStr = "";
foreach($matches[0] as $m){
//拼接
$unicodeStr .= "&#".base_convert(bin2hex(iconv('UTF-8',"UCS-4",$m)),16,10);
}
return $unicodeStr;
}
// 定义一个将unicode转义成中文的办法
function unicode2Chinese($str)
{
return preg_replace_callback("#u([0-9a-f]{4})#i",
function ($r) {return iconv('UCS-2BE', 'UTF-8', pack('H4', $r[1]));},
$str);
}
//定义一个数组
$arr = array('code' => 200,
'url' => "http://www.baidu.com",
'type' =>'m3u8',
'msg' =>"解析失败");
//将数组转义成json字符串
$json_str=json_encode($arr);
//将json字符串(本质就是字符串 无非就是json格式的字符串罢了) 写入文件中
$info=unicode2Chinese($json_str);
file_put_contents("typeinfo.json", $info);
//获取文件中的json字符串
$jsonStr=file_get_contents("typeinfo.json");
//将获得的json字符串转义成json对象
$json_object=json_decode($jsonStr);
/* $json_object= stdClass Object
(
[code] => 200
[type] => m3u8
[url] => http://www.baidu.com
[msg] => 解析失败
)*/
//将获得的json字符串转义成数组对象
$json_arr=json_decode($jsonStr,true);
/* $json_arr=Array
(
[code] => 200
[type] => m3u8
[url] => http://www.baidu.com
[msg] => 解析失败
)*/
//判断它是不是数组对象
if(is_array($json_object)){
echo "是数组";
}else{
echo "不是数组";
}
31、中文转义unicode unicode转义成中文
<?php
// 定义一个将unicdeo转义成中文的办法
function unicodeDecode($unicode_str){
$json = '{"str":"'.$unicode_str.'"}';
$arr = json_decode($json,true);
if(empty($arr)) return '';
return $arr['str'];
}
// 定义一个将中文转义成unicode的办法
function UnicodeEncode($str){
preg_match_all('/./u',$str,$matches);
$unicodeStr = "";
foreach($matches[0] as $m){
//拼接
$unicodeStr .= "&#".base_convert(bin2hex(iconv('UTF-8',"UCS-4",$m)),16,10);
}
return $unicodeStr;
}
// 定义一个将unicode转义成中文的办法
function unicode2Chinese($str)
{
return preg_replace_callback("#u([0-9a-f]{4})#i",
function ($r) {return iconv('UCS-2BE', 'UTF-8', pack('H4', $r[1]));},
$str);
}
32、普通网页端转json接口
<?php
header('Content-type:text/json');//如果没这句话 输出将是而可视化网站
define('QYPATH', 'aylzhc/');//缓存文件夹
if (!is_dir('aylzhc/')) mkdir('aylzhc/');
$jiexi="https://lf.iwebs.ml/?url=".$_REQUEST['url'].'&next=//www.panghuys.com';
$DATA=curlget($jiexi,8);
preg_match('/"url": "(.*)",/',$DATA,$newurl);
preg_match('/"time": "(.*)",/',$DATA,$newtime);
preg_match('/"key": "(.*)",/',$DATA,$newkey);
$url="https://lf.iwebs.ml/api_config.php";
$body = array("url"=>$newurl[1],"time"=>$newtime[1],"key"=>$newkey[1]);//
$header = array( "Origin:https://lf.iwebs.ml/", "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36");
$result = curlPost($url, $body, 5, $header, 'array');
$arr = json_decode($result, true);
if(!($arr['code']==200 && strpos($arr['url'],"http")!==false)){
$xarr = array(
'code' => 201,
'url' => $_GET["url"],
);
exit(json_encode($xarr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
if(strpos($_GET['url'],"index.m3u8")!==false){
$arr=putContent($_GET['url'],$jx,QYPATH);
}
exit(json_encode($arr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
function putContent($url,$jx,$path){
$m3u8data=curlget($jx['url'],8);
if(strlen($m3u8data) < 666){
return ['code' =>'404','msg' =>'该链接内容为空或者异常内容'];
}
$ep_file= $path.md5($url).'.m3u8';
file_put_contents($ep_file,$url);
$zurl = 'http://'.$_SERVER['HTTP_HOST'].'/qiepian/'.$ep_file;//生成缓存后的连接
$arr['url']=$zurl;
$arr['code']=200;
$arr['ylurl']=$url;
return $arr;
}
function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "") {
$header = empty($header) ? '' : $header;
//支持json数据数据提交
if($data_type == 'json'){
$post_string = json_encode($post_data);
}elseif($data_type == 'array') {
$post_string = $post_data;
}elseif(is_array($post_data)){
$post_string = http_build_query($post_data, '', '&');
}
$ch = curl_init(); // 启动一个CURL会话
curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查 // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
// curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36');
curl_setopt($ch, CURLOPT_REFERER, 'https://lf.iwebs.ml/');
curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); // Post提交的数据包
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // 设置超时限制防止死循环
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_ENCODING, '');//解决网页乱码问题 很重要
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
// 打印请求的header信息
$a = curl_getinfo($ch);
$data = curl_exec($ch); //运行 curl,请求网页并返回结果
curl_close($ch); //关闭 curl
return $data;
}
function curlget($url, $timeout =15)
{
$header = array(
"X-FORWARDED-FOR:".rand_ip(),
"CLIENT-IP:".rand_ip(),
"X-Real-IP:".rand_ip(),
"referer: https://lf.iwebs.ml",//模拟来路访问
"Connection: Keep-Alive",//可持久连接、连接重用。。。避免了重新建立连接
"User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36",
"Accept: application/json, text/javascript, */*; q=0.01",
"Accept-Language: zh-CN,zh;q=0.9",
);
$ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36';
$ch = curl_init(); //初始化 curl
curl_setopt($ch, CURLOPT_URL, $url); //要访问网页 URL 地址
curl_setopt($ch, CURLOPT_NOBODY, false); //设定是否输出页面内容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而非直接输出到屏幕上
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10); //连接超时时间,设置为 0,则无限等待
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //数据传输的最大允许时间超时,设为一小时
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); //HTTP验证方法
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不检查 SSL 证书来源
curl_setopt($ch, CURLOPT_USERAGENT, $ua); // 伪造ua
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不检查 证书中 SSL 加密算法是否存在
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //跟踪爬取重定向页面
curl_setopt($ch, CURLOPT_AUTOREFERER, true); //当Location:重定向时,自动设置header中的Referer:信息
curl_setopt($ch, CURLOPT_ENCODING, ''); //解决网页乱码问题
curl_setopt($ch, CURLOPT_REFERER, 'https://json.xdys.vip');
//curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_HEADER,0); //显示头部数据为1 不显示为0
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); //强制使用IPV4协议解析域名
$httpheaders = array();
$httpheaders[] = "Origin:http://{$_SERVER['HTTP_HOST']}"; //模拟浏览器CORS跨域请求
$httpheaders[] = "Content-Type: application/json; charset=utf-8";
$httpheaders[] = "CLIENT-IP: {$_SERVER['HTTP_CLIENT_IP']}";
$httpheaders[] = "X-FORWARDED-FOR: {$_SERVER['HTTP_X_FORWARDED_FOR']}";
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
$data = curl_exec($ch); //运行 curl,请求网页并返回结果
curl_close($ch); //关闭 curl
return $data;
}
function rand_ip(){
$ip_long = array(
array('607649792', '608174079'), //36.56.0.0-36.63.255.255
array('975044608', '977272831'), //58.30.0.0-58.63.255.255
array('999751680', '999784447'), //59.151.0.0-59.151.127.255
array('1019346944', '1019478015'), //60.194.0.0-60.195.255.255
array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
array('1947009024', '1947074559'), //116.13.0.0-116.13.255.255
array('1987051520', '1988034559'), //118.112.0.0-118.126.255.255
array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
);
$rand_key = mt_rand(0, 14);
$huoduan_ip= long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
return $huoduan_ip;
}
33、每日调用写入文件,以php文件名创建txt文件,在获取该文件内容 在该这个内容 在写入
// 1、创建以php名字来创建php名字的txt为文件
$final=strrpos($_SERVER['PHP_SELF'],'/');
$filenames=substr($_SERVER['PHP_SELF'],$final + 1);
$filename=explode(".",$filenames)[0].".txt";
//2、判断该文件是否存在,不存在则创建
if(!file_exists($filename)){
$info="1-".date('Y-m-d H:i:s',time());
file_put_contents($filename, $info);
}else{
//3、非初次获取该数据 在调用加入 在写入文件
$counttime=file_get_contents($filename);
$count=explode('-',$counttime)[0];
$num=$count + 1;
$time=date('Y-m-d H:i:s',time());
$info=$num.'-'.$time;
file_put_contents($filename, $info);
}
33、统计功能
<?php
//首先你要有读写文件的权限
//本程序可以直接运行,第一次报错
require $_SERVER["DOCUMENT_ROOT"] . "/player/adminml.php";
if($zhiqu_ML=="adminml"){
define('ADMIN',ADMIN_MULU);//软件使用正版版本
}else{
define('ADMIN',ADMIN_MULU);//软件使用正版版本
if(strpos($_SERVER['REQUEST_URI'],"/muiplayer/")!==false || strpos($_SERVER['REQUEST_URI'],"/airplayer/")!==false
|| strpos($_SERVER['REQUEST_URI'],"/yplayer/")!==false){
$online_log = "../count.dat"; //保存人数的文件,
$allonline_log = "../allcount.dat"; //保存人数的文件,
}else{
$online_log = "count.dat"; //保存人数的文件,
$allonline_log = "allcount.dat"; //保存人数的文件,
}
$timeout = 86400; //30秒内没动作者,认为掉线
$entries = file($online_log);
$allentries = file($allonline_log);
$temp = array();
$tempall = array();
$yuanlaishuju = array();
$yuanlaishuju_all = array();
for ($j = 0; $j < count($allentries); $j++) {
$entry_all = explode(",", trim($allentries[$j]));
if (($entry_all[0] != $_SERVER['REMOTE_ADDR'])) {
array_push($tempall, $entry_all[0] . "," . $entry_all[1] .",".$entry_all[2]. "n"); //取出其他浏览者的信息,并去掉超时者,保存进$temp
}
if($entry_all[0] == $_SERVER['REMOTE_ADDR']){
$yuanlaishuju_all=$entry_all;
}
}
for ($i = 0; $i < count($entries); $i++) {
$entry = explode(",", trim($entries[$i]));
// $cishu=$entry[2] ;
if (($entry[0] != $_SERVER['REMOTE_ADDR']) && ($entry[1] > time())) {
array_push($temp, $entry[0] . "," . $entry[1] .",".$entry[2]. "n"); //取出其他浏览者的信息,并去掉超时者,保存进$temp
}
if($entry[0] == $_SERVER['REMOTE_ADDR'] && ($entry[1] > time())){
$yuanlaishuju=$entry;
}
}
//每天次数统计
//更新浏览者的时间 取自己 这样两者就==其他人+自己的 组成的数组
if($yuanlaishuju[0]==$_SERVER['REMOTE_ADDR']){
$cishu=$yuanlaishuju[2] + 1;
array_push($temp, $_SERVER['REMOTE_ADDR'] . "," . $yuanlaishuju[1] .",".$cishu. "n");
}else{
array_push($temp, $_SERVER['REMOTE_ADDR'] . "," . (time() + ($timeout)) .",1". "n"); //更新浏览者的时间 取自己 这样两者就==其他人+自己的 组成的数组
}
//所有次数统计
if($yuanlaishuju_all[0]==$_SERVER['REMOTE_ADDR']){
$cishu=$yuanlaishuju_all[2] + 1;
array_push($tempall, $_SERVER['REMOTE_ADDR'] . "," . time() .",".$cishu. "n");
}else{
array_push($tempall, $_SERVER['REMOTE_ADDR'] . "," . (time() + ($timeout)) .",1". "n"); //更新浏览者的时间 取自己 这样两者就==其他人+自己的 组成的数组
}
$users_online = count($temp); //计算在线人数
$entries = implode("", $temp);
//写入文件
$fp = fopen($online_log, "w");
flock($fp, LOCK_EX); //flock() 不能在NFS以及其他的一些网络文件系统中正常工作
fputs($fp, $entries);
flock($fp, LOCK_UN);
fclose($fp);
$entries_all = implode("", $tempall);
//写入文件
$fp = fopen($allonline_log, "w");
flock($fp, LOCK_EX); //flock() 不能在NFS以及其他的一些网络文件系统中正常工作
fputs($fp, $entries_all);
flock($fp, LOCK_UN);
fclose($fp);
}
34、遍历一个文件夹内的文件和里面文件夹的文件
<?php
function my_dir($dir) {
$files = [];
$handle = opendir($dir);
print_r($handle);
if(@$handle = opendir($dir)) {
while(($file = readdir($handle)) !== false) {
if($file != ".." && $file != ".") {
if(is_dir($dir . "/" . $file)) { //如果是子文件夹,进行递归
$files[$file] = my_dir($dir . "/" . $file);
} else {
$files[] = $file;
}
}
}
closedir($handle);
}
return $files;
}
echo "<pre>";
print_r(my_dir("555"));
echo "</pre>";
Array
(
[666] => Array
(
[0] => 662.php
[1] => 661.php
)
[667] => 11.txt
[668] => 12.txt
[777] => Array
(
[0] => 772.php
[1] => 771.php
)
)
35、苹果cmsAPI入库:
echo "temp/cache/api/file.php";
print_r($cmsSend);
print_r($info);
exit;
$cmsSend['data'] = http_build_query($info['data']);
$data = Tool::send($cmsSend);
$json = json_decode($data, true);
cmsSend=temp/cache/con/file.phpArray
(
[url] => http://101.33.205.8:6671/anyipg/api.php/receive/vod?pass=4MALWTB3Y5TFVWHD
[mode] => POST
[data] => vod_name=%E6%88%98%E7%8B%BC2+&vod_sub=%E6%96%B0%E6%88%98%E7%8B%BC%2C%E6%96%B0%E6%88%98%E6%AD%BB%E6%B2%99%E5%9C%BA%2CWolf+Warriors+2&vod_pic=https%3A%2F%2Fimg9.doubanio.com%2Fview%2Fphoto%2Fs_ratio_poster%2Fpublic%2Fp2494701965.jpg&vod_year=2017&vod_lang=%E6%B1%89%E8%AF%AD%E6%99%AE%E9%80%9A%E8%AF%9D%2C%E8%8B%B1%E8%AF%AD&vod_area=%E4%B8%AD%E5%9B%BD%E5%A4%A7%E9%99%86&vod_total=&vod_class=%E5%8A%A8%E4%BD%9C%2C%E6%88%98%E4%BA%89&vod_tag=&vod_actor=%E5%90%B4%E4%BA%AC%2C%E5%BC%97%E5%85%B0%E5%85%8B%C2%B7%E6%A0%BC%E9%87%8C%E7%BD%97%2C%E5%90%B4%E5%88%9A%2C%E5%BC%A0%E7%BF%B0%2C%E5%8D%A2%E9%9D%96%E5%A7%97%2C%E4%B8%81%E6%B5%B7%E5%B3%B0%2C%E6%B7%B3%E4%BA%8E%E7%8F%8A%E7%8F%8A%2C%E4%BD%99%E7%94%B7%2C%E4%BA%8E%E8%B0%A6%2C%E7%9F%B3%E5%85%86%E7%90%AA%2C%E6%B5%B7%E8%92%82%C2%B7%E8%8E%AB%E5%B0%BC%E6%A2%85%E5%85%8B%2C%E5%A5%A5%E5%88%97%E6%A0%BC%C2%B7%E4%BA%9A%E5%8E%86%E5%B1%B1%E5%A4%A7%E7%BD%97%E7%BB%B4%E5%A5%87%2C%E8%89%BE%E4%BC%A6%C2%B7%E6%89%98%E5%B0%BC%2C%E8%B5%9B%E5%B0%94%C2%B7%E5%93%88%E9%87%8C%E6%96%AF%2C%E9%AB%98%E6%98%8E%2C%E7%8E%8B%E6%A3%AE%2C%E8%8B%87%E9%9D%92%2C%E7%A8%8B%E6%84%AB%2C%E5%BC%A0%E6%B0%B8%E8%BE%BE%2C%E9%83%AD%E7%A7%8B%E6%88%90%2C%E6%9D%9C%E5%BB%BA%E6%A1%A5%2C%E5%91%A8%E5%86%A0%E5%BB%B7%2C%E5%AE%89%C2%B7%E8%A9%B9%E5%A7%86%E6%96%AF%2C%E9%BB%9B%E5%AE%89%E5%A8%9C%C2%B7%E5%B8%8C%E6%8B%89%2C%E5%AD%99%E7%8E%87%E8%88%AA%2C%E5%BC%A0%E9%A6%A8%E6%9C%88%2C%E5%85%B3%E6%B5%B7%E9%BE%99%2C%E5%AE%89%E5%A6%AE%E5%A1%94%C2%B7%E6%96%AF%E5%9B%BE%E5%B0%94%E7%89%B9%2C%E7%89%B9%E9%9B%B7%E5%BC%97%C2%B7%E7%90%BC%E6%96%AF%2C%E5%A5%A5%E6%96%AF%E6%B1%80%C2%B7%E6%99%AE%E9%87%8C%E6%96%AF%E7%89%B9%2C%E5%85%8B%E8%8E%B1%C2%B7%E6%96%B9%E7%89%B9%E8%AF%BA%E7%89%B9%2C%E4%BF%9D%E7%BD%97%C2%B7%E8%89%BE%E5%8A%9B%E5%8D%A1%2C%E4%B8%B9%E5%B0%BC%E5%B0%94%C2%B7%E5%93%88%E6%A0%BC%E9%87%8C%E5%A4%AB%2C%E6%9D%8E%E9%95%87%E7%94%B7%2C%E5%BA%84%E5%B0%8F%E9%BE%99%2C%E9%99%88%E4%BA%91%E5%BF%97%2C%E8%82%AF%E5%B0%BC%E8%BF%AA&vod_director=%E5%90%B4%E4%BA%AC&vod_pubdate=2017-07-27&vod_writer=%E5%90%B4%E4%BA%AC%2C%E8%91%A3%E7%BE%A4%2C%E5%88%98%E6%AF%85&vod_douban_score=7.1&vod_duration=123&vod_content=%E7%94%B1%E4%BA%8E%E4%B8%80%E6%80%92%E6%9D%80%E5%AE%B3%E4%BA%86%E5%BC%BA%E6%8B%86%E7%89%BA%E7%89%B2%E6%88%98%E5%8F%8B%E6%88%BF%E5%AD%90%E7%9A%84%E6%81%B6%E9%9C%B8%EF%BC%8C%E5%B1%A1%E7%AB%8B%E5%8A%9F%E5%8B%8B%E7%9A%84%E5%86%B7%E9%94%8B%EF%BC%88%E5%90%B4%E4%BA%AC+%E9%A5%B0%EF%BC%89%E5%8F%97%E5%88%B0%E5%86%9B%E4%BA%8B%E6%B3%95%E5%BA%AD%E7%9A%84%E5%88%A4%E5%86%B3%E3%80%82%E5%9C%A8%E6%8A%BC%E6%9C%9F%E9%97%B4%EF%BC%8C%E4%BA%B2%E5%AF%86%E7%88%B1%E4%BA%BA%E9%BE%99%E5%B0%8F%E4%BA%91%E5%A3%AE%E7%83%88%E7%89%BA%E7%89%B2%E3%80%82%E5%87%BA%E7%8B%B1%E5%90%8E%EF%BC%8C%E5%86%B7%E9%94%8B%E8%BE%97%E8%BD%AC%E6%9D%A5%E5%88%B0%E9%9D%9E%E6%B4%B2%EF%BC%8C%E4%BB%96%E8%BE%97%E8%BD%AC%E5%90%84%E5%9C%B0%EF%BC%8C%E5%8F%AA%E4%B8%BA%E5%AF%BB%E6%89%BE%E6%9D%80%E5%AE%B3%E5%B0%8F%E4%BA%91%E7%9A%84%E5%87%B6%E6%89%8B%E3%80%82%E5%9C%A8%E6%AD%A4%E6%9C%9F%E9%97%B4%EF%BC%8C%E5%86%B7%E9%94%8B%E9%80%97%E7%95%99%E7%9A%84%E5%9B%BD%E5%AE%B6%E5%8F%91%E7%94%9F%E5%8F%9B%E4%B9%B1%EF%BC%8C%E5%8F%9B%E5%BE%92%E7%BA%A2%E5%B7%BE%E5%86%9B%E5%A4%A7%E5%BC%80%E6%9D%80%E6%88%92%EF%BC%8C%E8%A1%80%E6%B5%81%E6%88%90%E6%B2%B3%E3%80%82%E4%B8%AD%E5%9B%BD%E6%B4%BE%E5%87%BA%E6%B5%B7%E5%86%9B%E6%89%A7%E8%A1%8C%E6%92%A4%E4%BE%A8%E4%BB%BB%E5%8A%A1%EF%BC%8C%E6%9C%9F%E9%97%B4%E5%86%B7%E9%94%8B%E5%BE%97%E7%9F%A5%E6%9C%89%E4%B8%80%E4%BD%8D%E9%99%88%E5%8D%9A%E5%A3%AB%E8%A2%AB%E5%9B%B0%E5%9C%A8%E4%BA%94%E5%8D%81%E4%BA%94%E5%85%AC%E9%87%8C%E5%A4%96%E7%9A%84%E5%8C%BB%E9%99%A2%EF%BC%8C%E8%80%8C%E5%8F%9B%E5%86%9B%E5%88%99%E8%AF%95%E5%9B%BE%E6%8A%93%E4%BD%8F%E8%BF%99%E4%BD%8D%E5%8D%9A%E5%A3%AB%E3%80%82%E8%80%8C%E4%BB%8E%E5%8F%A6%E4%B8%80%E4%BD%8D%E5%8D%8E%E4%BE%A8%EF%BC%88%E4%BA%8E%E8%B0%A6+%E9%A5%B0%EF%BC%89%E5%8F%A3%E4%B8%AD%E5%BE%97%E7%9F%A5%EF%BC%8C%E6%9D%80%E5%AE%B3%E5%B0%8F%E4%BA%91%E7%9A%84%E5%87%B6%E6%89%8B%E6%AD%A3%E5%BE%85%E5%9C%A8%E8%BF%99%E4%B8%AA%E5%9B%BD%E5%AE%B6%E3%80%82++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++%E5%9C%A8%E6%97%A0%E6%B3%95%E5%BE%97%E5%88%B0%E6%B5%B7%E5%86%9B%E6%94%AF%E6%8F%B4%E7%9A%84%E6%83%85%E5%86%B5%E4%B8%8B%EF%BC%8C%E5%86%B7%E9%94%8B%E5%8F%AA%E8%BA%AB%E9%97%AF%E5%85%A5%E7%A1%9D%E7%83%9F%E5%9B%9B%E8%B5%B7%E7%9A%84%E6%88%98%E5%9C%BA%E3%80%82%E4%B8%8D%E5%B1%88%E4%B8%8D%E6%8C%A0%E7%9A%84%E6%88%98%E7%8B%BC%EF%BC%8C%E4%B8%8E%E5%86%B7%E9%85%B7%E6%97%A0%E6%83%85%E7%9A%84%E6%95%8C%E4%BA%BA%E5%B1%95%E5%BC%80%E6%82%AC%E6%AE%8A%E4%B9%8B%E6%88%98%E2%80%A6%E2%80%A6&vod_douban_id=26363254&vod_imdb_id=tt7131870&dburl=https%3A%2F%2Fmovie.douban.com%2Fsubject%2F26363254%2F&ylurl=http%3A%2F%2F43.136.107.141%3A6662%2Fdouban_id.php%3Fid%3D26363254&procedure=%E6%98%9F%E9%99%85%E5%AF%BC%E8%88%AAAPI%E7%A8%8B%E5%BA%8F&apiDomain=http%3A%2F%2F1.12.76.190%3A6645%2F&type_id=25&vod_play_from=nongmin&vod_play_url=%E5%AE%8C%E7%BE%8E%E4%B8%96%E7%95%8C_001_4K.mp4%24renrenmi-804381033d4fd0b8c42c6f0042387f4a167942b98634aa8fab26f7d61ad973ca9ced9f5849e65062ac635d7978cad6ee6d99181bdb103e140c8fd689e2f69857%23%E5%AE%8C%E7%BE%8E%E4%B8%96%E7%95%8C_002_4K.mp4%24renrenmi-804381033d4fd0b8c42c6f0042387f4a9482c287de0fd14f4cf3b2d531679c0151aa6d86f46c0e1121d64de584be9d7ff5ba8e6ad2bc2e830bf54c097bed9712&vod_remarks=&vod_serial=1&vod_points=1
)
info=Array
(
[code] => 200
[msg] => 获取成功
[data] => Array
(
[vod_name] => 战狼2
[vod_sub] => 新战狼,新战死沙场,Wolf Warriors 2
[vod_pic] => https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2494701965.jpg
[vod_year] => 2017
[vod_lang] => 汉语普通话,英语
[vod_area] => 中国大陆
[vod_total] =>
[vod_class] => 动作,战争
[vod_tag] =>
[vod_actor] => 吴京,弗兰克·格里罗,吴刚,张翰,卢靖姗,丁海峰,淳于珊珊,余男,于谦,石兆琪,海蒂·莫尼梅克,奥列格·亚历山大罗维奇,艾伦·托尼,赛尔·哈里斯,高明,王森,苇青,程愫,张永达,郭秋成,杜建桥,周冠廷,安·詹姆斯,黛安娜·希拉,孙率航,张馨月,关海龙,安妮塔·斯图尔特,特雷弗·琼斯,奥斯汀·普里斯特,克莱·方特诺特,保罗·艾力卡,丹尼尔·哈格里夫,李镇男,庄小龙,陈云志,肯尼迪
[vod_director] => 吴京
[vod_pubdate] => 2017-07-27
[vod_writer] => 吴京,董群,刘毅
[vod_douban_score] => 7.1
[vod_duration] => 123
[vod_content] => 由于一怒杀害了强拆牺牲战友房子的恶霸,屡立功勋的冷锋(吴京 饰)受到军事法庭的判决。在押期间,亲密爱人龙小云壮烈牺牲。出狱后,冷锋辗转来到非洲,他辗转各地,只为寻找杀害小云的凶手。在此期间,冷锋逗留的国家发生叛乱,叛徒红巾军大开杀戒,血流成河。中国派出海军执行撤侨任务,期间冷锋得知有一位陈博士被困在五十五公里外的医院,而叛军则试图抓住这位博士。而从另一位华侨(于谦 饰)口中得知,杀害小云的凶手正待在这个国家。 在无法得到海军支援的情况下,冷锋只身闯入硝烟四起的战场。不屈不挠的战狼,与冷酷无情的敌人展开悬殊之战……
[vod_douban_id] => 26363254
[vod_imdb_id] => tt7131870
[dburl] => https://movie.douban.com/subject/26363254/
[ylurl] => http://43.136.107.141:6662/douban_id.php?id=26363254
[procedure] => 星际导航API程序
[apiDomain] => http://1.12.76.190:6645/
[type_id] => 25
[vod_play_from] => nongmin
[vod_play_url] => 完美世界_001_4K.mp4$renrenmi-804381033d4fd0b8c42c6f0042387f4a167942b98634aa8fab26f7d61ad973ca9ced9f5849e65062ac635d7978cad6ee6d99181bdb103e140c8fd689e2f69857#完美世界_002_4K.mp4$renrenmi-804381033d4fd0b8c42c6f0042387f4a9482c287de0fd14f4cf3b2d531679c0151aa6d86f46c0e1121d64de584be9d7ff5ba8e6ad2bc2e830bf54c097bed9712
[vod_remarks] =>
[vod_serial] => 1
[vod_points] => 1
)
)
36、http_build_query方法详解(自动拼接生成URL参数字符串)
<?php
$data = array('foo'=>'航歌',
'baz'=>'111',
'cow'=>'222',
'php'=>'hypertext processor');
echo http_build_query($data);
?>
37、php的mysql脚本类 db.class.php
db.class.php下载地址:
https://bokeimages.oss-cn-hangzhou.aliyuncs.com/bokeimages/dbc.class.php
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/include/config.php';
require_once 'dbc.class.php';//引入数据库类
1、查询某个资源
$applist = Db::table("kami")->where(["id" => 1])->find();
$res_user = Db::table('user')->where(['pwd'=>md5($pwd),'appid'=>$appid],"(",")")->where('(user',$user)->whereOr(['email'=>$user,'phone'=>$user],")")->find();
2、查询某表所有资源
$goods_res = Db::table('user_logon')->where(['log_ip'=>'183.9.124.240'])->whereOr(['appid'=>'10003'])->order('id desc')->limit('0','5')->select();
3、更新资源
$addcode = Db::table('goods_order')->where(["id"=>"1"])->update(['name'=>'永name久name卡']);
$daili_up = Db::table('daili')->where('user',$app_res['return'])->update(['money'=>$daili_res['money']+$money]);
4、多表连接
$order_res = Db::table('user','as U')->field('U.*,UL.uid')->JOIN("user_logon","as UL",'UL.uid=UL.id')->limit('0','5')->select();
$order_res = Db::table('goods_order','as O')->field('O.*,U.name as uname,U.user,U.email,U.phone,G.type,G.amount')->JOIN("goods","as G",'O.gid=G.id')->JOIN("user",'as U','O.Uid=U.id')->limit('0','5')->select();
$res = Db::table('app_notice','as N')->field('N.*,A.name as appname')->JOIN('app','as A','N.appid=A.id')
->order('id desc')->limit($bnums,$ENUMS)->select();
$order_res = Db::table('user','as U')->field('U.*,A.*')->JOIN("user_logon","as UL",'UL.uid=UL.id')->JOIN("app","as A",'A.id=UL.appid')->limit('0','3')->select();
5、添加资源
$daili_log = Db::table('daili_sr_order')->add(["uid" => $app_res['return'],"order" =>$order,"time" =>time(),"name" =>'用户:'.$res_user['user'].'会员续费',"money" =>$money,"balance" =>$daili_res['money'] + $money]);
$add_res = Db::table('goods_order')->add(['order'=>$order,'uid'=>$res_user['id'],'gid'=>$gid,
'name'=>$res_goods['name'],'money'=>$res_goods['money'],'o_time'=>time(),'p_type'=>$way]);
6、资源个数
$nums=Db::table('user_logon')->where(['uid'=>$res_user['id']])->count();
$nums=Db::table('app_text')->count();
7、判断数据表是否存在
if(Db::table('app_text')->exist()){
}
38、另外的mysqli连接教程db.php
https://bokeimages.oss-cn-hangzhou.aliyuncs.com/bokeimages/db.php
函数 描述
mysqli_affected_rows() 返回前一次 MySQL 操作所影响的记录行数。
mysqli_autocommit() 打开或关闭自动提交数据库修改。
mysqli_change_user() 更改指定数据库连接的用户。
mysqli_character_set_name() 返回数据库连接的默认字符集。
mysqli_close() 关闭先前打开的数据库连接。
mysqli_commit() 提交当前事务。
mysqli_connect_errno() 返回上一次连接错误的错误代码。
mysqli_connect_error() 返回上一次连接错误的错误描述。
mysqli_connect() 打开一个到 MySQL 服务器的新的连接。
mysqli_data_seek() 调整结果指针到结果集中的一个任意行。
mysqli_debug() 执行调试操作。
mysqli_dump_debug_info() 转储调试信息到日志中。
mysqli_errno() 返回最近调用函数的最后一个错误代码。
mysqli_error_list() 返回最近调用函数的错误列表。
mysqli_error() 返回最近调用函数的最后一个错误描述。
mysqli_fetch_all() 从结果集中取得所有行作为关联数组,或数字数组,或二者兼有。
mysqli_fetch_array() 从结果集中取得一行作为关联数组,或数字数组,或二者兼有。
mysqli_fetch_assoc() 从结果集中取得一行作为关联数组。
mysqli_fetch_field_direct() 从结果集中取得某个单一字段的 meta-data,并作为对象返回。
mysqli_fetch_field() 从结果集中取得下一字段,并作为对象返回。
mysqli_fetch_fields() 返回结果中代表字段的对象的数组。
mysqli_fetch_lengths() 返回结果集中当前行的每个列的长度。
mysqli_fetch_object() 从结果集中取得当前行,并作为对象返回。
mysqli_fetch_row() 从结果集中取得一行,并作为枚举数组返回。
mysqli_field_count() 返回最近查询的列数。
mysqli_field_seek() 把结果集中的指针设置为指定字段的偏移量。
mysqli_field_tell() 返回结果集中的指针的位置。
mysqli_free_result() 释放结果内存。
mysqli_get_charset() 返回字符集对象。
mysqli_get_client_info() 返回 MySQL 客户端库版本。
mysqli_get_client_stats() 返回有关客户端每个进程的统计。
mysqli_get_client_version() 将 MySQL 客户端库版本作为整数返回。
mysqli_get_connection_stats() 返回有关客户端连接的统计。
mysqli_get_host_info() 返回 MySQL 服务器主机名和连接类型。
mysqli_get_proto_info() 返回 MySQL 协议版本。
mysqli_get_server_info() 返回 MySQL 服务器版本。
mysqli_get_server_version() 将 MySQL 服务器版本作为整数返回。
mysqli_info() 返回有关最近执行查询的信息。
mysqli_init() 初始化 MySQLi 并返回 mysqli_real_connect() 使用的资源。
mysqli_insert_id() 返回最后一个查询中自动生成的 ID。
mysql_kill() 请求服务器杀死一个 MySQL 线程。
mysqli_more_results() 检查一个多查询是否有更多的结果。
mysqli_multi_query() 执行一个或多个针对数据库的查询。
mysqli_next_result() 为 mysqli_multi_query() 准备下一个结果集。
mysqli_num_fields() 返回结果集中字段的数量。
mysqli_num_rows() 返回结果集中行的数量。
mysqli_options() 设置额外的连接选项,用于影响连接行为。
mysqli_ping() 进行一个服务器连接,如果连接已断开则尝试重新连接。
mysqli_prepare() 准备执行一个 SQL 语句。
mysqli_query() 执行某个针对数据库的查询。
mysqli_real_connect() 打开一个到 MySQL 服务器的新的链接。
mysqli_real_escape_string() 转义在 SQL 语句中使用的字符串中的特殊字符。
mysqli_real_query() 执行 SQL 查询
mysqli_reap_async_query() 返回异步查询的结果。
mysqli_refresh() 刷新表或缓存,或者重置复制服务器信息。
mysqli_rollback() 回滚数据库中的当前事务。
mysqli_select_db() 更改连接的默认数据库。
mysqli_set_charset() 设置默认客户端字符集。
mysqli_set_local_infile_default() 撤销用于 load local infile 命令的用户自定义句柄。
mysqli_set_local_infile_handler() 设置用于 LOAD DATA LOCAL INFILE 命令的回滚函数。
mysqli_sqlstate() 返回最后一个 MySQL 操作的 SQLSTATE 错误代码。
mysqli_ssl_set() 用于创建 SSL 安全连接。
mysqli_stat() 返回当前系统状态。
mysqli_stmt_init() 初始化声明并返回 mysqli_stmt_prepare() 使用的对象。
mysqli_store_result() 传输最后一个查询的结果集。
mysqli_thread_id() 返回当前连接的线程 ID。
mysqli_thread_safe() 返回是否将客户端库编译成 thread-safe。
mysqli_use_result() 从上次使用 mysqli_real_query() 执行的查询中初始化结果集的检索。
mysqli_warning_count() 返回连接中的最后一个查询的警告数量。
以上就是 MySQLi 函数的全部内容!
1、插入资源,返回插入资源的ID 如果插入数据失败 返回值=0
DB::connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, '3306');
$insertsql=" INSERT INTO `ruyicms`.`yyys_user_logon` (`id`, `uid`, `token`, `log_time`, `log_ip`, `log_in`, `last_t`, `appid`) VALUES (NULL, '2', '71276451a04bb048f646280fd1591', '1680533872', '112.64.62.115', '6ff53b53fd9bfb9c', '1122334755', '10003') ";
$typeresult=DB::queryinsertid($insertsql);
print_r($typeresult);//插入资源的ID
2、插入数据 | 更新数据 变动的函数 1:变动一行 0:变动0行 -1 :插入或者更新失败
DB::connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, '3306');
$updatesql =" UPDATE `ruyicms`.`yyys_user_logon` SET `last_t` = '1122334755' WHERE `yyys_user_logon`.`id` = 2 ";
$insertsql=" INSERT INTO `ruyicms`.`yyys_user_logon` (`id`, `uid`, `token`, `log_time`, `log_ip`, `log_in`, `last_t`, `appid`) VALUES (NULL, '2', '71276451a04bb048f646280fd1591', '1680533872', '112.64.62.115', '6ff53b53fd9bfb9c', '1122334755', '10003') ";
$typeresult=DB::queryline($insertsql);//变动行数
3、返回结果集是数组
$selectsqls='SELECT * FROM `yyys_user_logon` limit 0,5';
$results=DB::get_row_toarr($selectsqls);
4、结果集遍历
$selectsqls='SELECT * FROM `yyys_user_logon` limit 0,5';
$results=DB::query($selectsqls);
$results=mysqli_result Object ( [current_field] => 0 [field_count] => 8 [lengths] => [num_rows] => 3 [type] => 0 )
结果集总数 = $results->num_rows;
一行结果集有多少个字段名 = $results->field_count;
//直接遍历
foreach ($results as $key=>$value){
print_r($value);
echo '===<br>';
}
5、多结果查询和遍历
$selectsqls='SELECT * FROM `yyys_user_logon` limit 0,5';
$results=DB::query($selectsqls);
while($row=DB::fetch($results)){
print_r($row);
echo '<br>';
}
39、原始mysql函数和工具类使用教程
<?php
header('Content-type:text/json');
define('DB_HOST','localhost');//数据库连接地址,默认:localhost或127.0.0.1
define('DB_USER','ruyicms');//数据库账号
define('DB_PASSWD','ruyicms');//数据库密码
define('DB_NAME','ruyicms');//数据库名称
define('DB_PRE','yyys_');//数据库名称
define('DB_PORT',3306);//数据库名称
mysqli_query($link,$sql);
//如果是(DML)增、删、改,将返回布尔类型是否成功
//返回上一次操作时受影响的行数
mysqli_affected_rows($link);
//返回资源结果集中的行数
mysql_num_rows($result);
//返回资源结果集中的字段数
mysql_num_fields($result);
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT) or die("数据库连接失败!失败信息:");
mysqli_set_charset($conn,"utf8") or die("数据库编码集设置失败!");
$sql="select * from user";
$res = mysqli_query($conn,$sql);
mysqli_insert_id($conn); //执行插入语句是返回上次插入最新插入的主键ID
mysqli_fetch_array($res);//得到一行结果集
// 遍历结果集
while($row =mysqli_fetch_assoc($res)){
}
var_dump(mysqli_fetch_object($res));
var_dump(mysqli_fetch_row($res)); //返回索引数组
var_dump(mysqli_fetch_object($res)); //返回对象
var_dump(mysqli_fetch_fields($res)); //返回结果集中每一列的字段信息
mysqli_free_result($res); //释放查询资源结果集
mysqli_close($conn); //关闭数据库连接
40、PHP数据库mysql连接函数例子大全
<?php
function test(){
global $conn; //这样是就是声明$conn是成员变量,如果没有这句话,就是局部变量,就会出错
}
$host = 'localhost';
$user = 'root';
$password = '8438031100';
$database = 'Phpitem';
$port = '3306';
$connect = mysqli_connect($host, $user, $password, $database, $port) or die("连接数据库服务器失败!" . mysqli_errno());
if ($connect) {
echo '连接成功' . "<br>";
mysqli_query($connect, "set names utf8");
$result = mysqli_query($connect, "select * from student");
/*
$array1 = mysqli_fetch_array($result);//获取一行的数据
while ($array1) {//array1永远有值 永远为true
while ($$array = mysqli_fetch_array($result)) {
//当出现中文乱码的时候:务必设置数据库编码格式---->mysqli_query($conn, "set names utf8");就不会出现乱码了
echo $array1['uname'] . "<br>";
}这样子就死循环,必须$array = mysqli_fetch_array($result),它一行一行的遍历
}
//mysqli_fetch_row($result)---从结果集每次获取都能获取一行作为枚举数组----》下标只能是:数字
//mysqli_fetch_array($result)这个的数组下标可以是数字或者表的字段名(枚举数组和关联数组)
41、PHP爬虫神器QueryList+guzzlehttp
1、文档链接
http://www.querylist.cc/docs/guide/v4/content-filiter
http://www.querylist.cc/docs/guide/v3/http-more
https://guzzle-cn.readthedocs.io/zh_CN/latest/
https://phantomjs.org/examples
https://www.00996.cn/php/2999.html
https://github.com/jae-jae/QueryList-Community
https://github.com/jae-jae/QueryList
https://guzzle-cn.readthedocs.io/zh_CN/latest/
文档博客
https://toutiao.io/posts/z2z8m0/preview
http://www.zzvips.com/article/191892.html
2、安装包下载
https://bokeimages.oss-cn-hangzhou.aliyuncs.com/bokeimages/QueryListv4.zip
3、爬虫基础操作
0、HTTP客户端
QueuryList推荐使用GuzzleHttp
来作为HTTP客户端,它功能强大、使用简单、支持异步和并发请求,GuzzleHttp使用文档:http://guzzle-cn.readthedocs.io/zh_CN/latest/ 。当然,需要强调的是QueryList并不依赖任何一个HTTP客户端,你可以根据自己的喜好来选择HTTP客户端,如使用:file_get_contents
、curl
或其它第三方HTTP客户端包。
默认安装好QueryList之后就可以直接使用GuzzleHttp
了:
$client = new GuzzleHttpClient();
$res = $client->request('GET', 'https://www.baidu.com/s', [
'query' => ['wd' => 'QueryList'],
'headers' => [
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
'Accept-Encoding' => 'gzip, deflate, br',
]
]);
$html = (string)$res->getBody();
$data = QueryList::html($html)->find('h3')->texts();
QueryList内置的HTTP客户端
为方便使用,QueryList基于GuzzleHttp
封装了一些HTTP请求接口,并进行了简化,请求参数与GuzzleHttp
一致,在请求参数上有什么不明白的地方可以直接查看GuzzleHttp
文档。
目前封装的HTTP接口有:
get()
:GET 请求post()
:POST请求postJson()
:POST JSON请求multiGet()
:并发GET请求multiPost()
:并发POST请求
用法get()
方法和post()
方法用法和参数完全一致,且共享cookie。
$ql = QueryList::get('http://httpbin.org/get?param1=testvalue¶ms2=somevalue');
// 等价于
$ql->get('http://httpbin.org/get',[
'param1' => 'testvalue',
'params2' => 'somevalue'
]);
// 发送post请求
$ql = QueryList::post('http://httpbin.org/post',[
'param1' => 'testvalue',
'params2' => 'somevalue'
]);
自定义HTTP Header
$ql = QueryList::get('http://httpbin.org/get',[
'param1' => 'testvalue',
'params2' => 'somevalue'
],[
'headers' => [
'Referer' => 'https://querylist.cc/',
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz'],
// 携带cookie
'Cookie' => 'abc=111;xxx=222'
]
]);
更多高级参数还可以携带更多高级参数,如:设置超时时间、设置代理等。
$ql = QueryList::get('http://httpbin.org/get',[
'param1' => 'testvalue',
'params2' => 'somevalue'
],[
// 设置代理
'proxy' => 'http://222.141.11.17:8118',
//设置超时时间,单位:秒
'timeout' => 30,
'headers' => [
'Referer' => 'https://querylist.cc/',
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz'],
'Cookie' => 'abc=111;xxx=222'
]
]);
$ql->post('http://httpbin.org/post',[
'param1' => 'testvalue',
'params2' => 'somevalue'
],[
'proxy' => 'http://222.141.11.17:8118',
'timeout' => 30,
'headers' => [
'Referer' => 'https://querylist.cc/',
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz'],
'Cookie' => 'abc=111;xxx=222'
]
]);
使用 HTTP Cache
HTTP缓存功能基于PHP-Cache包,它支持多种缓存驱动,如:文件缓存、Redis缓存,MySQL缓存等,PHP-Cache文档:http://www.php-cache.com/en/latest/
合理的使用HTTP缓存功能可以避免频繁的去抓取内容未改变的页面,提高DOM解析效率,它会在第一次抓取页面HTML后,将页面HTML缓存下来,下一次再次抓取时直接从缓存中读取HTML内容
使用文件缓存驱动
// 缓存文件夹路径
$cache_path = __DIR__.'/temp/';
$ql = = QueryList::get($url,null,[
'cache' => $cache_path,
'cache_ttl' => 600 // 缓存有效时间,单位:秒,可以不设置缓存有效时间
]);
使用其它缓存驱动
以使用Predis缓存驱动为例,首先安装Predis缓存适配器
composer require cache/predis-adapter
使用Predis缓存驱动:
use CacheAdapterPredisPredisCachePool;
$client = new PredisClient('tcp:/127.0.0.1:6379');
$pool = new PredisCachePool($client);
$ql = = QueryList::get($url,null,[
'cache' => $pool,
'cache_ttl' => 600 // 缓存有效时间,单位:秒,可以不设置缓存有效时间
]);
并发请求(多线程请求)
简单用法,默认并发数为5
use GuzzleHttpPsr7Response;
use QLQueryList;
$urls = [
'https://github.com/trending/go?since=daily',
'https://github.com/trending/html?since=daily',
'https://github.com/trending/java?since=daily'
];
QueryList::multiGet($urls)
->success(function(QueryList $ql,Response $response, $index) use($urls){
echo 'Current url: '.$urls[$index]."rn";
$data = $ql->find('h3>a')->texts();
print_r($data->all());
})->send();
更高级的用法
use GuzzleHttpPsr7Response;
use QLQueryList;
$urls = [
'https://github.com/trending/go?since=daily',
'https://github.com/trending/html?since=daily',
'https://github.com/trending/java?since=daily'
];
$rules = [
'name' => ['h3>a','text'],
'desc' => ['.py-1','text']
];
$range = '.repo-list>li';
QueryList::rules($rules)
->range($range)
->multiGet($urls)
// 设置并发数为2
->concurrency(2)
// 设置GuzzleHttp的一些其他选项
->withOptions([
'timeout' => 60
])
// 设置HTTP Header
->withHeaders([
'User-Agent' => 'QueryList'
])
// HTTP success回调函数
->success(function (QueryList $ql, Response $response, $index){
$data = $ql->queryData();
print_r($data);
})
// HTTP error回调函数
->error(function (QueryList $ql, $reason, $index){
// ...
})
->send();
连贯操作
post
操作和get
操作是cookie共享的,意味着你可以先调用post()
方法登录,然后get()
方法就可以DOM解析所有登录后的页面。
$ql = QueryList::post('http://xxxx.com/login',[
'username' => 'admin',
'password' => '123456'
])->get('http://xxx.com/admin');
$ql->get('http://xxx.com/admin/page');
保存 Cookie 到本地
为避免重复登录,可以在第一次登录成功后保存 cookie 信息,方便下次直接使用。
下面演示 GuzzleHttp 保存 cookie 的方法,以下方法仅供参考:
1.第一步:模拟登录
use QLQueryList;
use GuzzleHttpCookieCookieJar;
$jar = new CookieJar();
$ql = QueryList::post('http://xxx.com/login', [
'username' => 'admin',
'password' => 'admin',
],[
'cookies' => $jar
]);
2.第二步:保存 cookie 到本地
$cookieArr = $jar->toArray();
file_put_contents('./xx_cookie.txt', json_encode($cookieArr));
3.第三步:使用保存在本地的 cookie
$cookieArr2 = file_get_contents('./xx_cookie.txt');
$cookieArr2 = json_decode($cookieArr2, true);
$jar2 = new CookieJar(false, $cookieArr2);
$ql2 = QueryList::get('http://xxx.com/admin/page',[],[
'cookies' => $jar2
]);
获取抓取到的HTML使用getHtml()
方法可以获取到get()
或post()
方法返回的HTML内容,通常用于调试打印验证抓取结果等场景
$ql = QueryList::get('http://httpbin.org/get?param1=testvalue');
echo $ql->getHtml();
捕获HTTP异常
如果遇到HTTP错误,如:404,500等,QueryList就会抛出HTTP异常,并终止程序。如果你不想出现HTTP异常时程序终止,可以自己捕获异常并处理,更多关于HTTP异常的细节:http://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html#id13。
use QLQueryList;
use GuzzleHttpExceptionRequestException;
try{
$ql = QueryList::get('https://www.sfasd34234324.com');
}catch(RequestException $e){
//print_r($e->getRequest());
echo 'Http Error';
}
获取HTTP响应头等信息
如果你想获取HTTP响应头,如响应状态码,QueryList内置的HTTP客户端屏蔽了这部分功能,请直接使用GuzzleHttp来实现。
use GuzzleHttpClient;
$client = new Client();
$response = $client->get('http://httpbin.org/get');
// 获取响应头部信息
$headers = $response->getHeaders();
print_r($headers);
自定义HTTP客户端
GuzzleHttp
是一款功能非常强大的HTTP客户端,你想要的功能它几乎都有;但如果你还是想使用自己熟悉的HTTP客户端如:curl
,那也是可以的:
function getHtml($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$html = getHtml('http://httpbin.org/get?param1=testvalue');
// 这种情况下允许你对HTML做一些额外的处理后,然后再把HTML传给QueryList对象
$html = str_replace('xxx','yyy',$html);
$ql = QueryList::html($html);
echo $ql->getHtml();
通过其他HTTP客户端获取源码,然后使用html()
方法来设置html,html()
方法除了可以接收一个完整的HTML网页外,还支持接收HTML片段:
$html = <<<STR
<div id="one">
<div class="two">
<a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片">
<img src="http://querylist.com/2.jpg" alt="这是图片2">
</div>
<span>其它的<b>一些</b>文本</span>
</div>
STR;
$ql = QueryList::html($html);
1、获取到quertlist爬虫对象
// 采集某页面的视频链接
$qllist = QueryList::get('https://v.xiangdao.me/vod-list-id-2-pg-1-order--by-time-class-0-year-0-letter--area--lang-.html',[],[
'headers' => [
'Referer' => 'https://v.xiangdao.me/',
'User-Agent' => 'Dalvik/2.1.0 (Linux; U; Android 10; PDHM00 Build/QKQ1.191222.002)',
]
]);
$rules = [
'listhref' => ['.resize_list>li>a','href'],
'listtitle' => ['.resize_list>li>a','title'],
'pic' => ['.resize_list>li>a>div>img','src'],
];
// 第二种
$qllist = QueryList::get('http://cms.querylist.cc/bizhi/453.html')
$qlplayer = QueryList::get($playerurl,[],[
'headers' => [
'Referer' => 'https://v.xiangdao.me/',
'User-Agent' => 'Dalvik/2.1.0 (Linux; U; Android 10; PDHM00 Build/QKQ1.191222.002)',
]
]);
2、从对象中获取url网页源代码
//获取html源码
$qllist->gethtml();
3、DOM解析列表,rules规则解析
// 定义DOM解析规则
$rules = [
// DOM解析文章标题
'title' => ['h1','text'],
// DOM解析文章作者
'author' => ['#author_baidu>strong','text'],
// DOM解析文章内容
'content' => ['.post_content','html']
];
<ul class="resize_list">
<li>
<a href="/vod-detail-id-40633.html" title="长月烬明">
<div class="pic" style=" height: 150px;">
<img src="https://pic3.58cdn.com.cn/nowater/webim/big/n_v27fdf239d856e4d3988967eafd291a325.jpg"
style=" height: 150px;"" data-echo="
https://pic3.58cdn.com.cn/nowater/webim/big/n_v27fdf239d856e4d3988967eafd291a325.jpg"style=
" height: 150px;""><span class=" sBg">
</span>
<span class="sBottom">
<span>更新至17集<em>0.0</em>
</span>
</span>
</div>
<span class="sTit">长月烬明</span>
<span class="sDes">主演:罗云熙 白鹿 陈都灵 邓为 孙珍妮 于波 耿業庭
黄馨瑶 郑国霖 黄海冰 李沛恩 刘敏 何中华 王一菲 肖顺尧 常鲁峰</span>
</a>
</li>
$rules = [
'listhref' => ['.resize_list>li>a','href'],// /vod-detail-id-40633.html
'listtitle' => ['.resize_list>li>a','title'],//长月烬明
'pic' => ['.resize_list>li>a>div>img','src'],
//https://pic3.58cdn.com.cn/nowater/webim/big/n_v27fdf239d856e4d3988967eafd291a325.jpg
];
$rt = $qllist->rules($rules)->query()->getData();
$listruledata=$rt->all();//播放类型 播放链接数据
$listruledata=Array
(
[0] => Array
( [listhref] => /vod-detail-id-40612.html
[listtitle] => 无间
[pic] => https://pic3.58cdn.com.cn/nowater/webim/big/n_v2da84df744cd64ffaa8c5a1c0f41643a7.jpg)
[1] => Array
( [listhref] => /vod-detail-id-40634.html
[listtitle] => 尘封十三载
[pic] => https://pic3.58cdn.com.cn/nowater/webim/big/n_v22205c5ae5a924212ac639ee9bff7760d.jpg)
)
## /vod-detail-id-40633.html
preg_match('/vod-detail-id-(.*).html/',$listruledata[0]['listhref'],$ids);
$vodId=$ids[1];//40633
<section class="mod mod0">
<div class="mod-media-page">
<section class="page-hd">
<a href="/vod-detail-id-40633.html" title="长月烬明">
<img src="https://pic3.58cdn.com.cn/nowater/webim/big/n_v27fdf239d856e4d3988967eafd291a325.jpg"
alt="长月烬明">
</a>
</section>
<section class="page-bd">
<h1 class="title">
<a href="/vod-detail-id-40633.html" title="长月烬明">长月烬明</a>
</h1>
<div class="desc_item">
<span>状态: </span>
<font size="2" color="red">更新至17集</font>
</div>
<div class="desc_item">
<span>主演: </span>
<a target='_blank' href='<a target=' _blank'
href='/index.php?m=vod-search-starring-%E7%BD%97%E4%BA%91%E7%86%99'>罗云熙</a>
</div>
<div class="desc_item">
<span>导演: </span>
<a target='_blank' href='<a target=' _blank' href='/index.php?m=vod-search-directed-%E9%9E%A0%E8%A7%89%E4%BA%AE'>鞠觉亮</a> </a>
</div>
<div class="desc_item">
<span>更新日期: </span>
<a target="_blank" href="">2023-04-12 18:58</a>
</div>
<div class="desc_item">
<span>年代: </span>
<a target='_blank' href='/index.php?m=vod-search-year-2023'>2023</a>
</div>
$rules = [
'title' => ['.page-hd>a','title'], //长月烬明
'beizhu' => ['.desc_item>font','text'],//更新至17集
'pic' => ['.page-hd>a>img','src'],
//https://pic3.58cdn.com.cn/nowater/webim/big/n_v27fdf239d856e4d3988967eafd291a325.jpg
//通过.desc_item解析出来的数据是一个数组 选择第2个数据
'zhuyan' => ['.desc_item:eq(1)','text'],// 主演: 罗云熙
//通过.desc_item解析出来的数据是一个数组 选择第3个数据
'daoyan' => ['.desc_item:eq(2)','text'],// 导演: 鞠觉亮
//通过.desc_item解析出来的数据是一个数组 选择第4个数据
'updatetime' => ['.desc_item:eq(3)','text'],// 更新日期: 2023-04-12 18:58
];
// 正则获取到数据
preg_match('/<span>年代:<em>(.*)人气/',$qldetail->gethtml(),$niandais);
//将字符串分割成数组
$niandais=explode('</em>',$niandais[1]);
//从获取的网页数据对象 移除标签 <em>xxx</em>只要是这个标签都不存在
$qllist->find('em')->remove();//去除em标签
$rules = [
'playerdata' => ['.main>.clearfix>script','text'],
'jianjie' => ['.detail-con','text'],
];
4、DOM解析单元素
4.1、获取第一张图片的链接地址
use QLQueryList;
$html = <<<STR
<div id="one">
<div class="two">
<a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片" abc="这是一个自定义属性">
<img class="second_pic" src="http://querylist.com/2.jpg" alt="这是图片2">
<a href="http://doc.querylist.cc">QueryList文档</a>
</div>
<span>其它的<b>一些</b>文本</span>
</div>
STR;
//这句话非常重要 也就是爬虫出一个标签 然后可以用html这个函数 继续对这个标签爬虫
$ql = QueryList::html($html);
$rt = [];
//获取第一张图片的链接地址
//下面四种写法完全等价
$rt[] = $ql->find('img')->attr('src');
$rt[] = $ql->find('img')->src;
$rt[] = $ql->find('img:eq(0)')->src;
$rt[] = $ql->find('img')->eq(0)->src;
/获取第一张图片的alt属性
$rt[] = $ql->find('img')->alt;
$rt[] = $ql->find('img')->attr('alt');
//获取第一张图片的abc属性,注意这里获取定义属性的写法与普通属性的写法是一样的
$rt[] = $ql->find('img')->abc;
$rt[] = $ql->find('img')->attr('abc');
$rt=Array
(
[0] => http://querylist.com/1.jpg
[1] => http://querylist.com/1.jpg
[2] => http://querylist.com/1.jpg
[3] => http://querylist.com/1.jpg
[4] => 这是图片
[5] => 这是一个自定义属性
)
4.2、获取第二张图片的属性
use QLQueryList;
$html = <<<STR
<div id="one">
<div class="two">
<a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片" abc="这是一个自定义属性">
<img class="second_pic" src="http://querylist.com/2.jpg" alt="这是图片2">
<a href="http://doc.querylist.cc">QueryList文档</a>
</div>
<span>其它的<b>一些</b>文本</span>
</div>
STR;
//这句话非常重要 也就是爬虫出一个标签 然后可以用html这个函数 继续对这个标签爬虫
$ql = QueryList::html($html);
$rt = [];
//获取第二张图片的alt属性
$rt[] = $ql->find('img')->eq(1)->alt;
//等价下面这句话
$rt[] = $ql->find('img:eq(1)')->alt;
//也等价下面这句话,通过class选择图片
$rt[] = $ql->find('.second_pic')->alt;
$rt=Array
(
[0] => 这是图片2
[1] => 这是图片2
[2] => 这是图片2
)
4.3、获取元素的所有属性
use QLQueryList;
$html = <<<STR
<div id="one">
<div class="two">
<a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片" abc="这是一个自定义属性">
<img class="second_pic" src="http://querylist.com/2.jpg" alt="这是图片2">
<a href="http://doc.querylist.cc">QueryList文档</a>
</div>
<span>其它的<b>一些</b>文本</span>
</div>
STR;
//这句话非常重要 也就是爬虫出一个标签 然后可以用html这个函数 继续对这个标签爬虫
$ql = QueryList::html($html);
$rt = [];
$rt[] = $ql->find('img:eq(0)')->attr('*');
$rt[] = $ql->find('a:eq(1)')->attr('*');
$rt=Array
(
[0] => Array
(
[src] => http://querylist.com/1.jpg
[alt] => 这是图片
[abc] => 这是一个自定义属性)
[1] => Array
(
[href] => http://doc.querylist.cc)
)
4.3、获取元素内的html内容或text内容
# 获取元素内的html内容或text内容
use QLQueryList;
$html = <<<STR
<div id="one">
<div class="two">
<a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片" abc="这是一个自定义属性">
<img class="second_pic" src="http://querylist.com/2.jpg" alt="这是图片2">
<a href="http://doc.querylist.cc">QueryList文档</a>
</div>
<span>其它的<b>一些</b>文本</span>
</div>
STR;
//这句话非常重要 也就是爬虫出一个标签 然后可以用html这个函数 继续对这个标签爬虫
$ql = QueryList::html($html);
$rt = [];
// 获取元素下的HTML内容
$rt[] = $ql->find('#one>.two')->html();
// 获取元素下的text内容
$rt[] = $ql->find('.two')->text();
$rt=Array
(
[0] => <a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片" abc="这是一个自定义属性">
<img src="http://querylist.com/2.jpg" alt="这是图片2">
<a href="http://doc.querylist.cc">QueryList文档</a>
[1] => QueryList官网
QueryList文档
)
4.4、获取多个元素的单个属性
# 获取多个元素的单个属性
use QLQueryList;
$html = <<<STR
<div id="one">
<div class="two">
<a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片" abc="这是一个自定义属性">
<img class="second_pic" src="http://querylist.com/2.jpg" alt="这是图片2">
<a href="http://doc.querylist.cc">QueryList文档</a>
</div>
<span>其它的<b>一些</b>文本</span>
</div>
STR;
//这句话非常重要 也就是爬虫出一个标签 然后可以用html这个函数 继续对这个标签爬虫
$ql = QueryList::html($html);
$data1 = $ql->find('.two img')->map(function($item){
return $item->alt;
});
// 等价下面这句话
$data2 = $ql->find('.two img')->attrs('alt');
print_r($data1->all());
print_r($data2->all());
Array
([0] => 这是图片
[1] => 这是图片2)
Array
([0] => 这是图片
[1] => 这是图片2)
4.5、获取多个元素的单个属性
# 获取多个元素的单个属性
use QLQueryList;
$html = <<<STR
<div id="one">
<div class="two">
<a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片" abc="这是一个自定义属性">
<img class="second_pic" src="http://querylist.com/2.jpg" alt="这是图片2">
<a href="http://doc.querylist.cc">QueryList文档</a>
</div>
<span>其它的<b>一些</b>文本</span>
</div>
STR;
//这句话非常重要 也就是爬虫出一个标签 然后可以用html这个函数 继续对这个标签爬虫
$ql = QueryList::html($html);
#获取选中元素的所有html内容和text内容
$texts = $ql->find('.two>a')->texts();
$htmls = $ql->find('#one span')->htmls();
print_r($texts->all());
print_r($htmls->all());
Array
(
[0] => QueryList官网
[1] => QueryList文档
)
Array
(
[0] => 其它的<b>一些</b>文本
)
4.6、单规则向rules规则转换
$rt = [];
// DOM解析文章标题
$rt['title'] = $ql->find('h1')->text();
// DOM解析文章作者
$rt['author'] = $ql->find('#author_baidu>strong')->text();
// DOM解析文章内容
$rt['content'] = $ql->find('.post_content')->html();
$rules = [
// DOM解析文章标题
'title' => ['h1','text'],
$rt['title'] = $ql->find('h1')->text();
// DOM解析文章作者
'author' => ['#author_baidu>strong','text'],
$rt['author'] = $ql->find('#author_baidu>strong')->text();
// DOM解析文章内容
'content' => ['.post_content','html']
$rt['content'] = $ql->find('.post_content')->html();
];
$rt = QueryList::get($url)->rules($rules)->query()->getData();
print_r($rt->all());
$rules = [
'规则名1' => ['选择器1','元素属性'],
'规则名2' => ['选择器2','元素属性'],
// ...
];
元素属性=text html src href title等
4.7、优化:queryData()方法等同于query()->getData()->all()
queryData() 语法糖
可能你会觉的列表DOM解析的语法有一点点繁琐,如:
$rt = QueryList::get($url)->rules($rules)->query()->getData();
print_r($rt->all());
QueryList V4.0.4版本新增了一个queryData()语法糖来简化这种操作:
$rt = QueryList::get($url)->rules($rules)->queryData();
print_r($rt);
queryData()方法等同于query()->getData()->all()
4.0、
5、从DOM解析内容中移除掉多余无用内容
5.1、基础移除数据库用remove
use QLQueryList;
$html =<<<STR
<div id="content">
<span class="tt">作者:xxx</span>
这是正文内容段落1.....
<span>这是正文内容段落2</span>
<p>这是正文内容段落3......</p>
<span>这是广告</span>
<p>这是版权声明!</p>
</div>
STR;
// DOM解析正文内容
$eles = QueryList::html($html)->find('#content');
// 选择正文内容中要移除的元素,并移除
$eles->find('.tt,span:last,p:last')->remove();
//.tt 移除: <span class="tt">作者:xxx</span>
//span:last移除: <span>这是广告</span>//有两个span标签 移除最后一个<span></span>
//p:last 移除: <p>这是版权声明!</p> //有两个p标签 移除最后一个<p></p>
//获取纯净的正文内容
$content = $eles->html();
print_r($content);
这是正文内容段落1.....
<span>这是正文内容段落2</span>
<p>这是正文内容段落3......</p>
5.2、用rules规则去移除数据(内容过滤选择器前面有-)
# 第二种用rules过滤内容
基础形态:
$rules = [
'规则名1' => ['选择器1','元素属性'],
'规则名2' => ['选择器2','元素属性'],
// ...
];
过滤形态:
$rules = [
'规则名1' => ['选择器1','元素属性','内容过滤选择器'],
'规则名2' => ['选择器2','元素属性','内容过滤选择器'],
// ...
];
# 内容过滤选择器参数不光可以定义要移除的内容还可以定义要保留的内容,多个值之间用空格隔开,有如下2条规则:
# 内容移除规则:选择器名前面添加减号(-),表示移除该标签以及标签内容。
# 内容保留规则:选择器名前面没有减号(-)(此时选择器只能为HTML标签名,不支持其他选择器),
# 当要DOM解析的[元素属性] 值为text时表示需要保留的HTML标签以及内容,为html时表示要过滤掉的HTML标签但保留内容。
# 内容移除规则:选择器名前面添加减号(-),表示移除该标签以及标签内容。
# 当要DOM解析的[元素属性] 值为text时表示需要保留的HTML标签以及内容,为html时表示要过滤掉的HTML标签但保留内容。
use QLQueryList;
$html =<<<STR
<div id="content">
<span class="tt">作者:xxx</span>
这是正文内容段落1.....
<span>这是正文内容段落2</span>
<p>这是正文内容段落3......</p>
<span>这是广告</span>
<p>这是版权声明!</p>
</div>
STR;
// DOM解析规则
$rules = [
//设置了内容过滤选择器
'content' => ['#content','html','-.tt -span:last -p:last']
];
等价于:$eles->find('.tt,span:last,p:last')->remove();
$rt = QueryList::rules($rules)->html($html)->query()->getData();
print_r($rt->all());
Array
(
[0] => Array
(
[content] => 这是正文内容段落1.....
<span>这是正文内容段落2</span>
<p>这是正文内容段落3......</p>
)
)
5.3、用rules规则去移除数据(内容过滤选择器前面没有-)
# 第二种用rules过滤内容
基础形态:
$rules = [
'规则名1' => ['选择器1','元素属性'],
'规则名2' => ['选择器2','元素属性'],
// ...
];
过滤形态:
$rules = [
'规则名1' => ['选择器1','元素属性','内容过滤选择器'],
'规则名2' => ['选择器2','元素属性','内容过滤选择器'],
// ...
];
# 内容过滤选择器参数不光可以定义要移除的内容还可以定义要保留的内容,多个值之间用空格隔开,有如下2条规则:
# 内容移除规则:选择器名前面添加减号(-),表示移除该标签以及标签内容。
# 内容保留规则:选择器名前面没有减号(-)(此时选择器只能为HTML标签名,不支持其他选择器),
# 当要DOM解析的[元素属性] 值为text时表示需要保留的HTML标签以及内容,为html时表示要过滤掉的HTML标签但保留内容。
# 内容保留规则:选择器名前面没有减号(-)(此时选择器只能为HTML标签名,不支持其他选择器),
# 当要DOM解析的[元素属性] 值为text时表示需要保留的HTML标签以及内容,为html时表示要过滤掉的HTML标签但保留内容。
use QLQueryList;
$html =<<<STR
<div id="content">
<span class="tt">作者:xxx</span>
这是正文内容段落1.....
<span>这是正文内容段落2</span>
<p>这是正文内容段落3......</p>
<a href="http://querylist.cc">QueryList官网</a>
<span>这是广告</span>
<p>这是版权声明!</p>
</div>
STR;
$rules = [
// 移除内容中所有的超链接,但保留超链接的内容,并移除内容中所有p标签,但保留p标签的内容
'content_html' => ['#content','html','a p'],
// 保留内容中的超链接,以及保留p标签及内容
'content_text' => ['#content','text','a p'],
];
$rt = QueryList::rules($rules)->html($html)->query()->getData();
print_r($rt->all());
Array
(
[0] => Array
(
[content_html] => <span class="tt">作者:xxx</span>
这是正文内容段落1.....
<span>这是正文内容段落2</span>
这是正文内容段落3......
QueryList官网
<span>这是广告</span>
这是版权声明!
[content_text] => 作者:xxx
这是正文内容段落1.....
这是正文内容段落2
<p>这是正文内容段落3......</p>
<a href="http://querylist.cc">QueryList官网</a>
这是广告
<p>这是版权声明!</p>
)
)
6、处理乱码(内容乱码是DOM解析过程中很常见的问题)
html =<<<STR
<div>
<p>这是内容</p>
</div>
STR;
$rule = [
'content' => ['div>p:last','text']
];
$data = QueryList::html($html)->rules($rule)
->encoding('UTF-8','GB2312')->query()->getData();
# 设置输入输出编码,并移除html头部
# 如果设置输入输出参数仍然无法解决乱码,那就使用 removeHead()方法移除html头部
$html =<<<STR
<div>
<p>这是内容</p>
</div>
STR;
$rule = [
'content' => ['div>p:last','text']
];
$data = QueryList::html($html)->rules($rule)
->removeHead()->query()->getData();
// 或者
$data = QueryList::html($html)->rules($rule)
->encoding('UTF-8','GB2312')->removeHead()->query()->getData();
# 自己手动转码页面,然后再把页面传给QueryList
$url = 'http://top.etao.com/level3.php?spm=0.0.0.0.Ql86zl&cat=16&show=focus&up=true&ad_id=&am_id=&cm_id=&pm_id=';
//手动转码
$html = iconv('GBK','UTF-8',file_get_contents($url));
$data = QueryList::html($html)->rules([
"text" => [".title a","text"]
])->query()->getData();
print_r($data);
6、处理DOM解析结果
QueryList引入了Laravel中Collection
集合对象,它提供了一个更具可读性的、更便于处理数组数据的封装。下面通过几个例子来说明它的用法,更多用法可以去查看Laravel文档。
$html =<<<STR
<div class="xx">
<img data-src="/path/to/1.jpg" alt="">
</div>
<div class="xx">
<img data-src="/path/to/2.jpg" alt="">
</div>
<div class="xx">
<img data-src="/path/to/3.jpg" alt="">
</div>
STR;
// 这句话非常实用 range('.xx') 也就是循环再这个class="xx" 进行这些规则采集数据
//range('.xx'):这句话的意思就是告诉范围给对象:范围再这里
/* <div class="xx">
<img data-src="/path/to/1.jpg" alt="">
</div>
这个是第一个范围 只要后面还有class="xx" 都会列为这个范围中
*/
$data = QueryList::html($html)->rules([
'image' => ['img','data-src']
])->range('.xx')->query()->getData(function($item){
return $item;
});
print_r($data->all());
Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
7、range('.xx')和QueryList::html($html)非常实用
# 获取多个元素的单个属性
use QLQueryList;
$html = <<<STR
<div id="one">
<div class="two">
<a href="http://querylist.cc">QueryList官网</a>
<img src="http://querylist.com/1.jpg" alt="这是图片" abc="这是一个自定义属性">
<img class="second_pic" src="http://querylist.com/2.jpg" alt="这是图片2">
<a href="http://doc.querylist.cc">QueryList文档</a>
</div>
<span>其它的<b>一些</b>文本</span>
</div>
STR;
//这句话非常重要 也就是爬虫出一个标签 然后可以用html这个函数 继续对这个标签爬虫
$ql = QueryList::html($html);
$html =<<<STR
<div class="xx">
<img data-src="/path/to/1.jpg" alt="">
</div>
<div class="xx">
<img data-src="/path/to/2.jpg" alt="">
</div>
<div class="xx">
<img data-src="/path/to/3.jpg" alt="">
</div>
STR;
// 这句话非常实用 range('.xx') 也就是循环再这个class="xx" 进行这些规则采集数据
//range('.xx'):这句话的意思就是告诉范围给对象:范围再这里
/* <div class="xx">
<img data-src="/path/to/1.jpg" alt="">
</div>
这个是第一个范围 只要后面还有class="xx" 都会列为这个范围中
*/
8、reverse()
方法将结果集倒序、选择多少条数据返回、过滤结果集的数据
8.1、只需要结果集前面几条数据
一开始:
Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
# 如果我们只想要前2条数据,其它数据都是多余的,那该怎么做呢?
# take() 方法返回给定数量项目的新集合,对最初的DOM解析结果data进行处理:
# 只要前面两条数据
$rt = $data->take(2)->all();
print_r($rt)=Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
)
8.2、只需要结果集最后几条数据
一开始:
Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
# 只要最后2条数据:
$rt = $data->take(-2)->all();
print_r($rt);
Array
(
[1] => Array
(
[image] => /path/to/2.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
8.3、 结果集翻转数据顺序
一开始:
Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
$rt = $data->reverse()->all();
print_r($rt)=Array
(
[2] => Array
(
[image] => /path/to/3.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
[0] => Array
(
[image] => /path/to/1.jpg
)
)
8.4、过滤结果集某个数据
filter()
方法用于按条件过滤数据,只保留满足条件的数据。
下面例子过滤掉图片路径为/path/to/2.jpg
的值。
一开始:
Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
$rt = $data->filter(function($item){
return $item['image'] != '/path/to/2.jpg';
})->all();
print_r($rt);
Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
8.5、很重要:path/to/1.jpg,为每个结果集前面增加一个链接 组成http://xxx.com/path/to/1.jpg
map() 方法遍历集合并将每一个值传入给定的回调。该回调可以任意修改项目并返回,从而形成新的被修改过项目的集合。下面遍历data并补全图片链接地址:
一开始:
Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
$rt = $data->map(function($item){
$item['image'] = 'http://xxx.com'.$item['image'];
return $item;
})->all();
print_r($rt);
Array
(
[0] => Array
(
[image] => http://xxx.com/path/to/1.jpg
)
[1] => Array
(
[image] => http://xxx.com/path/to/2.jpg
)
[2] => Array
(
[image] => http://xxx.com/path/to/3.jpg
)
)
8.6、连贯操作
Collection
对象的所有方法都是可以连贯操作的,比如下面操作,先翻转数数据顺序,然后补全图片链接,最后截取前2条数据:
一开始:
Array
(
[0] => Array
(
[image] => /path/to/1.jpg
)
[1] => Array
(
[image] => /path/to/2.jpg
)
[2] => Array
(
[image] => /path/to/3.jpg
)
)
$rt = $data->reverse()->map(function($item){
$item['image'] = 'http://xxx.com'.$item['image'];
return $item;
})->take(2)->all();
print_r($rt);
Array
(
[2] => Array
(
[image] => http://xxx.com/path/to/3.jpg
)
[1] => Array
(
[image] => http://xxx.com/path/to/2.jpg
)
)
42、curl普通请求
$startTime = microtime(true);
$chArr = [];
$optArr = [
CURLOPT_URL => 'http://www.httpbin.org/ip',
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
];
$result = [];
//创建多个curl资源并执行
for ($i=0; $i<10; $i++) {
$chArr[$i] = curl_init();
curl_setopt_array($chArr[$i], $optArr);
$result[$i] = curl_exec($chArr[$i]);
curl_close($chArr[$i]);
}
$endTime = microtime(true);
echo sprintf("use time: %.3f s".PHP_EOL, $endTime - $startTime);
use time: 6.080 s
43、curl_multi并发请求
$startTime = microtime(true);
$chArr = [];
$optArr = [
CURLOPT_URL => 'http://www.httpbin.org/ip',
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
];
$result = [];
//创建多个curl资源
for ($i=0; $i<10; $i++) {
$chArr[$i] = curl_init();
curl_setopt_array($chArr[$i], $optArr);
}
//创建批处理curl句柄
$mh = curl_multi_init();
//将单个curl句柄添加到批处理curl句柄中
foreach ($chArr as $ch) {
curl_multi_add_handle($mh, $ch);
}
//判断操作是否仍在执行的标识的引用
$active = null;
/**
* 本次循环第一次处理 $mh 批处理中的 $ch 句柄,并将 $mh 批处理的执行状态写入 $active,
* 当状态值等于 CURLM_CALL_MULTI_PERFORM 时,表明数据还在写入或读取中,执行循环,
* 当第一次 $ch 句柄的数据写入或读取成功后,状态值变为 CURLM_OK ,跳出本次循环,进入下面的大循环中。
*/
do {
//处理在批处理栈中的每一个句柄
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
/**
* 上面这段代码中,是可以直接使用 $active > 0 来作为 while 的条件,如下:
* do {
* $mrc = curl_multi_exec($mh, $active);
* } while ($active > 0);
* 此时如果整个批处理句柄没有全部执行完毕时,系统会不停的执行 curl_multi_exec 函数,从而导致系统CPU占用会很高,
* 因此一般不采用这种方案,可以通过 curl_multi_select 函数来达到没有需要读取的程序就阻塞住的目的。
*/
/**
* $active 为 true 时,即 $mh 批处理之中还有 $ch 句柄等待处理,
* $mrc == CURLM_OK,即上一次 $ch 句柄的读取或写入已经执行完毕。
*/
while ($active && $mrc == CURLM_OK) {
/**
* 程序进入阻塞状态,直到批处理中有活动连接(即 $mh 批处理中还有可执行的 $ch 句柄),
* 这样执行的好处是 $mh 批处理中的 $ch 句柄会在读取或写入数据结束后($mrc == CURLM_OK)进入阻塞阶段,
* 而不会在整个 $mh 批处理执行时不停地执行 curl_multi_exec 函数,白白浪费CPU资源。
*/
if (curl_multi_select($mh) != -1) {
//程序退出阻塞状态继续执行需要处理的 $ch 句柄
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
foreach ($chArr as $i=>$ch) {
//获取某个curl句柄的返回值
$result[$i] = curl_multi_getcontent($ch);
//移除批处理句柄中的某个句柄资源
curl_multi_remove_handle($mh, $ch);
}
//关闭一组curl句柄
curl_multi_close($mh);
$endTime = microtime(true);
echo sprintf("use time: %.3f s".PHP_EOL, $endTime - $startTime);
use time: 0.599 s
44、从一个文件txt随机获取一行(一言API)
<?php
// 存储数据的文件
$filename = __DIR__.'/data.dat';
//该文件所在目录:/www/wwwroot/shouquan.com/view/api/yiyan
# echo __DIR__;# /www/wwwroot/shouquan.com/view/api/yiyan
// 指定页面编码
header('Content-type: text/html; charset=utf-8');
if(!file_exists($filename)) {
die($filename . ' 数据文件不存在');
}
// 读取整个数据文件
$data = file_get_contents($filename);
// 按换行符分割成数组
$data = explode(PHP_EOL, $data);
// 随机获取一行索引
$result = $data[array_rand($data)];
// 去除多余的换行符(保险起见)
$result = str_replace(array("r","n","rn"), '', $result);
echo htmlspecialchars($result);
60、PHP 面向对象、关键词解释
类 − 定义了一件事物的抽象特点。类的定义包含了数据的形式以及对数据的操作。
对象 − 是类的实例。
成员变量 − 定义在类内部的变量。该变量的值对外是不可见的,但是可以通过成员函数访问,在类被实例化为对象后,该变量即可成为对象的属性。
成员函数 − 定义在类的内部,可用于访问对象的数据。
继承 − 继承性是子类自动共享父类数据结构和方法的机制,这是类之间的一种关系。在定义和实现一个类的时候,可以在一个已经存在的类的基础之上来进行,把这个已经存在的类所定义的内容作为自己的内容,并加入若干新的内容。
父类 − 一个类被其他类继承,可将该类称为父类,或基类,或超类。
子类 − 一个类继承其他类称为子类,也可称为派生类。
多态 − 多态性是指相同的函数或方法可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息可以产生不同的结果,这种现象称为多态性。
重载 − 简单说,就是函数或者方法有同样的名称,但是参数列表不相同的情形,这样的同名不同参数的函数或者方法之间,互相称之为重载函数或者方法。
抽象性 − 抽象性是指将具有一致的数据结构(属性)和行为(操作)的对象抽象成类。一个类就是这样一种抽象,它反映了与应用有关的重要性质,而忽略其他一些无关内容。任何类的划分都是主观的,但必须与具体的应用有关。
封装 − 封装是指将现实世界中存在的某个客体的属性与行为绑定在一起,并放置在一个逻辑单元内。
构造函数 − 主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中。
析构函数 − 析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。析构函数往往用来做"清理善后" 的工作(例如在建立对象时用new开辟了一片内存空间,应在退出前在析构函数中用delete释放)。
类使用 class 关键字后加上类名定义。
类名后的一对大括号({})内可以定义变量和方法。
类的变量使用 var 来声明, 变量也可以初始化值。
函数定义类似 PHP 函数的定义,但函数只能通过该类及其实例化的对象访问。
变量 $this 代表自身的对象。
构造函数
function __construct( $par1, $par2 ) {
$this->url = $par1;
$this->title = $par2;
}
PHP 面向对象
面向对象(Object-Oriented,简称 OO)是一种编程思想和方法,它将程序中的数据和操作数据的方法封装在一起,形成"对象",并通过对象之间的交互和消息传递来完成程序的功能。面向对象编程强调数据的封装、继承、多态和动态绑定等特性,使得程序具有更好的可扩展性、可维护性和可重用性。
在面向对象的程序设计(英语:Object-oriented programming,缩写:OOP)中,对象是一个由信息及对信息进行处理的描述所组成的整体,是对现实世界的抽象。
在现实世界里我们所面对的事情都是对象,如计算机、电视机、自行车等。
对象的主要三个特性:
对象的行为:对象可以执行的操作,比如:开灯,关灯就是行为。
对象的形态:对对象不同的行为是如何响应的,比如:颜色,尺寸,外型。
对象的表示:对象的表示就相当于身份证,具体区分在相同的行为与状态下有什么不同。
比如 Animal(动物) 是一个抽象类,我们可以具体到一只狗跟一只羊,而狗跟羊就是具体的对象,他们有颜色属性,可以写,可以跑等行为状态。
面向对象编程的三个主要特性:
封装(Encapsulation):指将对象的属性和方法封装在一起,使得外部无法直接访问和修改对象的内部状态。通过使用访问控制修饰符(public、private、protected)来限制属性和方法的访问权限,从而实现封装。
继承(Inheritance):指可以创建一个新的类,该类继承了父类的属性和方法,并且可以添加自己的属性和方法。通过继承,可以避免重复编写相似的代码,并且可以实现代码的重用。
多态(Polymorphism):指可以使用一个父类类型的变量来引用不同子类类型的对象,从而实现对不同对象的统一操作。多态可以使得代码更加灵活,具有更好的可扩展性和可维护性。在 PHP 中,多态可以通过实现接口(interface)和使用抽象类(abstract class)来实现。
面向对象内容
类 − 定义了一件事物的抽象特点。类的定义包含了数据的形式以及对数据的操作。
对象 − 是类的实例。
成员变量 − 定义在类内部的变量。该变量的值对外是不可见的,但是可以通过成员函数访问,在类被实例化为对象后,该变量即可成为对象的属性。
成员函数 − 定义在类的内部,可用于访问对象的数据。
继承 − 继承性是子类自动共享父类数据结构和方法的机制,这是类之间的一种关系。在定义和实现一个类的时候,可以在一个已经存在的类的基础之上来进行,把这个已经存在的类所定义的内容作为自己的内容,并加入若干新的内容。
父类 − 一个类被其他类继承,可将该类称为父类,或基类,或超类。
子类 − 一个类继承其他类称为子类,也可称为派生类。
多态 − 多态性是指相同的函数或方法可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息可以产生不同的结果,这种现象称为多态性。
重载 − 简单说,就是函数或者方法有同样的名称,但是参数列表不相同的情形,这样的同名不同参数的函数或者方法之间,互相称之为重载函数或者方法。
抽象性 − 抽象性是指将具有一致的数据结构(属性)和行为(操作)的对象抽象成类。一个类就是这样一种抽象,它反映了与应用有关的重要性质,而忽略其他一些无关内容。任何类的划分都是主观的,但必须与具体的应用有关。
封装 − 封装是指将现实世界中存在的某个客体的属性与行为绑定在一起,并放置在一个逻辑单元内。
构造函数 − 主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中。
析构函数 − 析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。析构函数往往用来做"清理善后" 的工作(例如在建立对象时用new开辟了一片内存空间,应在退出前在析构函数中用delete释放)。
下图中我们通过 Car 类 创建了三个对象:Mercedes, Bmw, 和 Audi。
$mercedes = new Car ();
$bmw = new Car ();
$audi = new Car ();
PHP 类定义
PHP 定义类通常语法格式如下:
<?php
class phpClass {
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}
?>
解析如下:
类使用 class 关键字后加上类名定义。
类名后的一对大括号({})内可以定义变量和方法。
类的变量使用 var 来声明, 变量也可以初始化值。
函数定义类似 PHP 函数的定义,但函数只能通过该类及其实例化的对象访问。
实例
<?php
class Site {
/* 成员变量 */
var $url;
var $title;
/* 成员函数 */
function setUrl($par){
$this->url = $par;
}
function getUrl(){
echo $this->url . PHP_EOL;
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title . PHP_EOL;
}
}
?>
变量 $this 代表自身的对象。
PHP_EOL 为换行符。
PHP 中创建对象
类创建后,我们可以使用 new 运算符来实例化该类的对象:
$runoob = new Site;
$taobao = new Site;
$google = new Site;
以上代码我们创建了三个对象,三个对象各自都是独立的,接下来我们来看看如何访问成员方法与成员变量。
调用成员方法
在实例化对象后,我们可以使用该对象调用成员方法,该对象的成员方法只能操作该对象的成员变量:
// 调用成员函数,设置标题和URL
$runoob->setTitle( "菜鸟教程" );
$taobao->setTitle( "淘宝" );
$google->setTitle( "Google 搜索" );
$runoob->setUrl( 'www.runoob.com' );
$taobao->setUrl( 'www.taobao.com' );
$google->setUrl( 'www.google.com' );
// 调用成员函数,获取标题和URL
$runoob->getTitle();
$taobao->getTitle();
$google->getTitle();
$runoob->getUrl();
$taobao->getUrl();
$google->getUrl();
完整代码如下:
实例
<?php
class Site {
/* 成员变量 */
var $url;
var $title;
/* 成员函数 */
function setUrl($par){
$this->url = $par;
}
function getUrl(){
echo $this->url . PHP_EOL;
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title . PHP_EOL;
}
}
$runoob = new Site;
$taobao = new Site;
$google = new Site;
// 调用成员函数,设置标题和URL
$runoob->setTitle( "菜鸟教程" );
$taobao->setTitle( "淘宝" );
$google->setTitle( "Google 搜索" );
$runoob->setUrl( 'www.runoob.com' );
$taobao->setUrl( 'www.taobao.com' );
$google->setUrl( 'www.google.com' );
// 调用成员函数,获取标题和URL
$runoob->getTitle();
$taobao->getTitle();
$google->getTitle();
$runoob->getUrl();
$taobao->getUrl();
$google->getUrl();
?>
运行实例 »
执行以上代码,输出结果为:
菜鸟教程
淘宝
Google 搜索
www.runoob.com
www.taobao.com
www.google.com
PHP 构造函数
构造函数是一种特殊的方法。主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,在创建对象的语句中与 new 运算符一起使用。
PHP 5 允许开发者在一个类中定义一个方法作为构造函数,语法格式如下:
void __construct ([ mixed $args [, $... ]] )
在上面的例子中我们就可以通过构造方法来初始化 $url 和 $title 变量:
function __construct( $par1, $par2 ) {
$this->url = $par1;
$this->title = $par2;
}
现在我们就不需要再调用 setTitle 和 setUrl 方法了:
实例
$runoob = new Site('www.runoob.com', '菜鸟教程');
$taobao = new Site('www.taobao.com', '淘宝');
$google = new Site('www.google.com', 'Google 搜索');
// 调用成员函数,获取标题和URL
$runoob->getTitle();
$taobao->getTitle();
$google->getTitle();
$runoob->getUrl();
$taobao->getUrl();
$google->getUrl();
运行实例 »
析构函数
析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。
PHP 5 引入了析构函数的概念,这类似于其它面向对象的语言,其语法格式如下:
void __destruct ( void )
实例
<?php
class MyDestructableClass {
function __construct() {
print "构造函数n";
$this->name = "MyDestructableClass";
}
function __destruct() {
print "销毁 " . $this->name . "n";
}
}
$obj = new MyDestructableClass();
?>
执行以上代码,输出结果为:
构造函数
销毁 MyDestructableClass
继承
PHP 使用关键字 extends 来继承一个类,PHP 不支持多继承,格式如下:
class Child extends Parent {
// 代码部分
}
实例
实例中 Child_Site 类继承了 Site 类,并扩展了功能:
<?php
// 子类扩展站点类别
class Child_Site extends Site {
var $category;
function setCate($par){
$this->category = $par;
}
function getCate(){
echo $this->category . PHP_EOL;
}
}
方法重写
如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
实例中重写了 getUrl 与 getTitle 方法:
function getUrl() {
echo $this->url . PHP_EOL;
return $this->url;
}
function getTitle(){
echo $this->title . PHP_EOL;
return $this->title;
}
访问控制
PHP 对属性或方法的访问控制,是通过在前面添加关键字 public(公有),protected(受保护)或 private(私有)来实现的。
public(公有):公有的类成员可以在任何地方被访问。
protected(受保护):受保护的类成员则可以被其自身以及其子类和父类访问。
private(私有):私有的类成员则只能被其定义所在的类访问。
属性的访问控制
类属性必须定义为公有,受保护,私有之一。如果用 var 定义,则被视为公有。
<?php
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // 这行能被正常执行
echo $obj->protected; // 这行会产生一个致命错误
echo $obj->private; // 这行也会产生一个致命错误
$obj->printHello(); // 输出 Public、Protected 和 Private
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// 可以对 public 和 protected 进行重定义,但 private 而不能
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // 这行能被正常执行
echo $obj2->private; // 未定义 private
echo $obj2->protected; // 这行会产生一个致命错误
$obj2->printHello(); // 输出 Public、Protected2 和 Undefined
?>
方法的访问控制
类中的方法可以被定义为公有,私有或受保护。如果没有设置这些关键字,则该方法默认为公有。
<?php
/**
* Define MyClass
*/
class MyClass
{
// 声明一个公有的构造函数
public function __construct() { }
// 声明一个公有的方法
public function MyPublic() { }
// 声明一个受保护的方法
protected function MyProtected() { }
// 声明一个私有的方法
private function MyPrivate() { }
// 此方法为公有
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); // 这行能被正常执行
$myclass->MyProtected(); // 这行会产生一个致命错误
$myclass->MyPrivate(); // 这行会产生一个致命错误
$myclass->Foo(); // 公有,受保护,私有都可以执行
/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// 此方法为公有
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // 这行会产生一个致命错误
}
}
$myclass2 = new MyClass2;
$myclass2->MyPublic(); // 这行能被正常执行
$myclass2->Foo2(); // 公有的和受保护的都可执行,但私有的不行
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublicn";
}
private function testPrivate() {
echo "Bar::testPrivaten";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublicn";
}
private function testPrivate() {
echo "Foo::testPrivaten";
}
}
$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>
接口
使用接口(interface),可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。
接口是通过 interface 关键字来定义的,就像定义一个标准的类一样,但其中定义所有的方法都是空的。
接口中定义的所有方法都必须是公有,这是接口的特性。
要实现一个接口,使用 implements 操作符。类中必须实现接口中定义的所有方法,否则会报一个致命错误。类可以实现多个接口,用逗号来分隔多个接口的名称。
<?php
// 声明一个'iTemplate'接口
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// 实现接口
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
常量
可以把在类中始终保持不变的值定义为常量。在定义和使用常量的时候不需要使用 $ 符号。
常量的值必须是一个定值,不能是变量,类属性,数学运算的结果或函数调用。
自 PHP 5.3.0 起,可以用一个变量来动态调用类。但该变量的值不能为关键字(如 self,parent 或 static)。
实例
<?php
class MyClass
{
const constant = '常量值';
function showConstant() {
echo self::constant . PHP_EOL;
}
}
echo MyClass::constant . PHP_EOL;
$classname = "MyClass";
echo $classname::constant . PHP_EOL; // 自 5.3.0 起
$class = new MyClass();
$class->showConstant();
echo $class::constant . PHP_EOL; // 自 PHP 5.3.0 起
?>
抽象类
任何一个类,如果它里面至少有一个方法是被声明为抽象的,那么这个类就必须被声明为抽象的。
定义为抽象的类不能被实例化。
被定义为抽象的方法只是声明了其调用方式(参数),不能定义其具体的功能实现。
继承一个抽象类的时候,子类必须定义父类中的所有抽象方法;另外,这些方法的访问控制必须和父类中一样(或者更为宽松)。例如某个抽象方法被声明为受保护的,那么子类中实现的方法就应该声明为受保护的或者公有的,而不能定义为私有的。
<?php
abstract class AbstractClass
{
// 强制要求子类定义这些方法
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// 普通方法(非抽象方法)
public function printOut() {
print $this->getValue() . PHP_EOL;
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
class ConcreteClass2 extends AbstractClass
{
public function getValue() {
return "ConcreteClass2";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass2";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') . PHP_EOL;
$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') . PHP_EOL;
?>
执行以上代码,输出结果为:
ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2
此外,子类方法可以包含父类抽象方法中不存在的可选参数。
例如,子类定义了一个可选参数,而父类抽象方法的声明里没有,则也是可以正常运行的。
<?php
abstract class AbstractClass
{
// 我们的抽象方法仅需要定义需要的参数
abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
// 我们的子类可以定义父类签名中不存在的可选参数
public function prefixName($name, $separator = ".") {
if ($name == "Pacman") {
$prefix = "Mr";
} elseif ($name == "Pacwoman") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$prefix}{$separator} {$name}";
}
}
$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "n";
echo $class->prefixName("Pacwoman"), "n";
?>
输出结果为:
Mr. Pacman
Mrs. Pacwoman
Static 关键字
声明类属性或方法为 static(静态),就可以不实例化类而直接访问。
静态属性不能通过一个类已实例化的对象来访问(但静态方法可以)。
由于静态方法不需要通过对象即可调用,所以伪变量 $this 在静态方法中不可用。
静态属性不可以由对象通过 -> 操作符来访问。
自 PHP 5.3.0 起,可以用一个变量来动态调用类。但该变量的值不能为关键字 self,parent 或 static。
<?php
class Foo {
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
print Foo::$my_static . PHP_EOL;
$foo = new Foo();
print $foo->staticValue() . PHP_EOL;
?>
执行以上程序,输出结果为:
foo
foo
Final 关键字
PHP 5 新增了一个 final 关键字。如果父类中的方法被声明为 final,则子类无法覆盖该方法。如果一个类被声明为 final,则不能被继承。
以下代码执行会报错:
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called" . PHP_EOL;
}
final public function moreTesting() {
echo "BaseClass::moreTesting() called" . PHP_EOL;
}
}
class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called" . PHP_EOL;
}
}
// 报错信息 Fatal error: Cannot override final method BaseClass::moreTesting()
?>
调用父类构造方法
PHP 不会在子类的构造方法中自动的调用父类的构造方法。要执行父类的构造方法,需要在子类的构造方法中调用 parent::__construct() 。
<?php
class BaseClass {
function __construct() {
print "BaseClass 类中构造方法" . PHP_EOL;
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct(); // 子类构造方法不能自动调用父类的构造方法
print "SubClass 类中构造方法" . PHP_EOL;
}
}
class OtherSubClass extends BaseClass {
// 继承 BaseClass 的构造方法
}
// 调用 BaseClass 构造方法
$obj = new BaseClass();
// 调用 BaseClass、SubClass 构造方法
$obj = new SubClass();
// 调用 BaseClass 构造方法
$obj = new OtherSubClass();
?>
执行以上程序,输出结果为:
BaseClass 类中构造方法
BaseClass 类中构造方法
SubClass 类中构造方法
BaseClass 类中构造方法
61、php-curl( $arr=curlget($jxurl,5); )函数接口-代码
<?php
$ip = $_SERVER["REMOTE_ADDR"];
$jxurl ='http://110.42.2.247:880/analysis/json/?uid=2100&my=abdrvyzBGQRTVWZ468&mgtv=app&url='.$_GET['url'];
echo $jxurl;
$arr=curlget($jxurl,5);
echo json_encode($arr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
function curlget($url, $timeout =15)
{
$header = array(
"X-FORWARDED-FOR:".rand_ip(),
"CLIENT-IP:".rand_ip(),
"X-Real-IP:".rand_ip(),
"Connection: Keep-Alive",//可持久连接、连接重用。。。避免了重新建立连接
"User-Agent:".$_SERVER['HTTP_USER_AGENT']."",
);
$ch = curl_init(); //初始化 curl
curl_setopt($ch, CURLOPT_URL, $url); //要访问网页 URL 地址
curl_setopt($ch, CURLOPT_NOBODY, false); //设定是否输出页面内容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而非直接输出到屏幕上
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10); //连接超时时间,设置为 0,则无限等待
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //数据传输的最大允许时间超时,设为一小时
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); //HTTP验证方法
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不检查 SSL 证书来源
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不检查 证书中 SSL 加密算法是否存在
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //跟踪爬取重定向页面
curl_setopt($ch, CURLOPT_AUTOREFERER, true); //当Location:重定向时,自动设置header中的Referer:信息
curl_setopt($ch, CURLOPT_ENCODING, ''); //解决网页乱码问题
//curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_HEADER,0); //显示头部数据为1 不显示为0
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); //强制使用IPV4协议解析域名
$data = curl_exec($ch); //运行 curl,请求网页并返回结果
curl_close($ch); //关闭 curl
echo $data;
return $data;
}
function rand_ip(){
$ip_long = array(
array('607649792', '608174079'), //36.56.0.0-36.63.255.255
array('975044608', '977272831'), //58.30.0.0-58.63.255.255
array('999751680', '999784447'), //59.151.0.0-59.151.127.255
array('1019346944', '1019478015'), //60.194.0.0-60.195.255.255
array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
array('1947009024', '1947074559'), //116.13.0.0-116.13.255.255
array('1987051520', '1988034559'), //118.112.0.0-118.126.255.255
array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
);
$rand_key = mt_rand(0, 14);
$huoduan_ip= long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
return $huoduan_ip;
}
function xianlu ($xianlu,$xl){
global $arr;
$fh = curlget($xianlu);
$jx = json_decode($fh, true);
return getjsondata($jx,$xl);
}
function getjsondata($jx,$xl){
if( (strpos($jx["url"],'.mp4') !== false && (strpos($jx["url"],'vkey') !== false) )
|| (strpos($jx["url"],'.m3u8') !== false && (strpos($jx["url"],'vkey') !== false) ) ){
$arr = array(
'code' => $jx["code"],
'url' => $jx["url"],
'type' =>"dplayer",
'title' =>"anyiyun",
'msg' =>"zuoancly",
);
return $arr;
}else{
$arr = array(
'code' => 201,
'url' => $_GET['url'],
'type' =>"dplayer",
'title' =>"anyiyun",
'msg' =>"zuoancly",
);
return $arr;
return 0;
}
}
?>
62、php--采集授权API代码
<?php
header('Content-Type:application/json');
// define('IPS',"101.33.205.8|101.33.205.9|117.61.106.32|43.136.107.141|182.43.40.14|116.209.240.118|175.178.27.43|520anyisk.wchulian.com.cn");//|隔开
// $serverIp=$_SERVER['REMOTE_ADDR'];
// $serverIpS=explode('|',IPS);
// if (!in_array($serverIp, $serverIpS) ) {
// header('HTTP/1.1 405 Not Found');
// header("status: 405 Not Found");
// exit;
// }
if($_SERVER['REMOTE_ADDR']=="");
$REQUESTURI=$_SERVER['REQUEST_URI'];
$apihm=explode('ac=',$REQUESTURI)[1];
$api='http://1.12.76.190:6652/api.php/provide/vod/from/tucheng?ac='.$apihm;
// file_put_contents('APi.txt', $api);
$fh = httpgeturl($api, 4);
$jx = json_decode($fh, true);
exit(json_encode($jx, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ;
function httpgeturl($url, $time) {
$curl = curl_init();
//1.初始化,创建一个新cURL资源
$UserAgent = 'Mozilla/6.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36';
curl_setopt($curl, CURLOPT_URL, $url);
//2.设置URL curl_setopt($ch, CURLOPT_URL, "http://www.lampbrother.net/");
// 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_TIMEOUT, 13);
//在发起连接前等待的时间,如果设置为0,则无限等待。
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//设定是否显示头信息
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//启用时会将服务器服务器返回的"Location: "放在header中递归的返回给服务器,设置可以302跳转
// curl_setopt($curl, CURLOPT_REFERER, "http://jx.wchulian.com.cn/");
//构造来路
curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
//gzip压缩内容
$data = curl_exec($curl);
// 抓取URL并把它传递给浏览器
curl_close($curl);
return $data;
}
63、PHP 万能httpcurl和内置代理
<?php
header("Content-Type: text/json;charset=utf-8");
function httpcurlPost($action,$method,$url, $post_data = array(), $timeout = 5, $header = "", $data_type = "") {
$time = time();
$orderno = "DT20230724162732qF7zemxz";
$secret = "d7e86886ba5dea709caf41a3e726cc08";
$txt="orderno=".$orderno.",secret=".$secret.",timestamp=".$time;
$sign = strtoupper(md5($txt));
$auth = 'sign='.$sign.'&orderno='.$orderno.'×tamp='.$time;
$ch = curl_init();
$header = array(
"Proxy-Authorization:".$auth,
);
//支持json数据数据提交
if($data_type == 'json'){
$post_string = json_encode($post_data);
}elseif($data_type == 'array') {
$post_string = $post_data;
}elseif(is_array($post_data)){
$post_string = http_build_query($post_data, '', '&');
}
$ch = curl_init(); // 启动一个CURL会话
curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查 // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
// curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
// curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
// curl_setopt($ch, CURLOPT_REFERER, 'https://www.aliyundrive.com/');
//动态并发产品代理设置为dtbf.xiongmaodaili.com:8089, 动态按量产品需将代理设置为dtan.xiongmaodaili.com:8088
curl_setopt($ch, CURLOPT_PROXY, "http://dtan.xiongmaodaili.com:8088");
if($method=="post"){
curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); // Post提交的数据包
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // 设置超时限制防止死循环
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
// curl_setopt($ch, CURLOPT_ENCODING, '');//解决网页乱码问题 很重要
curl_setopt($ch, CURLOPT_ENCODING, "gzip, deflate, sdch");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
if($action=="code" || $action=="header" ){
$data=curl_getinfo($ch);
}else{
$data = curl_exec($ch);//运行 curl,请求网页并返回结果
}
curl_close($ch); //关闭 curl
return $data;
}
$jxurl ='https://aly.dcd1.cn/dpp/?url='.$_GET['url'];
$vod_data=[];//[标签:地区]
$headers = [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'];
$text = httpcurlPost("data","get",$jxurl, $vod_data, 5, $headers, 'array');
preg_match('#"url":"(.*?)"#',$text,$urls);
preg_match('#"key":"(.*?)"#',$text,$keys);
preg_match('#"vkey":"(.*?)"#',$text,$vkeys);
preg_match('#"time":"(.*?)"#',$text,$times);
$vod_data['url']=$urls[1];
$vod_data['time']=$times[1];
$vod_data['key']=$keys[1];
$vod_data['vkey']=$vkeys[1];
$jxurlpost ='https://aly.dcd1.cn/dpp/api_config.php';
$data = httpcurlPost("data","post",$jxurlpost, $vod_data, 5, $headers, 'array');
$data_arr=json_decode($data,true);
if($data_arr['code']=="200" && strpos($data_arr['url'],"http")!==false ){
exit(json_encode($data_arr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}else{
$data_arr['code']="404";
$data_arr['url']=$_GET['url'];
$data_arr['msg']="解析失败";
exit(json_encode($data_arr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
64、Php加密和JS解密
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script>
function rc4(content, key, operation) {
const iv = CryptoJS.enc.Utf8.parse(key.substring(0, 16));
key = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(key).toString());
if (operation) {
return CryptoJS.RC4.decrypt(content, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8)
}
return CryptoJS.RC4.encrypt(content, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString()
}
console.log(rc4('hello world', '1234567890', false));
console.log(rc4('LJi8Ufyb3iu4PjQ=', '1234567890', true));
</script>
</body>
</html>
<?php
function rc4(string $content, string $key, $operation = false)
{
$key = md5($key);
if ($operation) {
return openssl_decrypt(base64_decode($content), 'rc4', $key, OPENSSL_RAW_DATA);
}
return base64_encode(openssl_encrypt($content, 'rc4', $key, OPENSSL_RAW_DATA));
}
var_dump(rc4('LJi8Ufyb3iu4PjQ=', '1234567890', true));
65、当字符串长度达到10个换行显示
function formatString($input,$changdu) {
$length = mb_strlen($input, 'UTF-8');
$output = '';
for ($i = 0; $i < $length; $i++) {
$output .= mb_substr($input, $i, 1, 'UTF-8');
if (($i + 1) % $changdu == 0 && $i != $length - 1) {
$output .= "n";
}
}
return $output;
}
<pre> <?php echo formatString($site['password'],7); ?> </pre>
版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!