php
Easul Lv6

常用函数

可以参考这里

http请求

折叠代码块PHP 复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
function httpRequest($url, $method, $headers, $body=NULL){
$ch = curl_init();

// 设置请求url
curl_setopt($ch, CURLOPT_URL, $url);
// 设置请求方法
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
// 设置请求体
switch ($method) {
case "POST":
if ($body != NULL){
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$bodyLength = strlen($body);
$headers[] = "content-length: $bodyLength";
}
default:
break;
}
// 设置请求头
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 返回文件流
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 设置数据编码
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
// 返回响应头,false为不返回
curl_setopt($ch, CURLOPT_HEADER, TRUE);
// 返回响应体
curl_setopt($ch, CURLOPT_NOBODY, FALSE);
// 连接结束后保存cookie信息到某个文件。
// curl_setopt($ch, CURLOPT_COOKIEJAR, "test.cookie");
// 请求时读取cookie信息的文件
// curl_setopt($ch, CURLOPT_COOKIEFILE, "test.cookie");
// 注意,毫秒超时一定要设置这个
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
// 超时毫秒,cURL 7.16.2中被加入。从PHP 5.2.3起可使用
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 300);
// 抓取https数据时设置如下两个选项,防止抓取失败
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
// 设置socks5代理
// curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
// curl_setopt($ch, CURLOPT_PROXY, PROXY_URL);
$resp = curl_exec($ch);

// 获取响应码
$respStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 获取响应头长度
$respHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
// 获取响应头
$respHeaders = substr($resp, 0, $respHeaderSize);
// 获取响应体
$respBody = substr($resp, $respHeaderSize);
// 错误码为0,则正常
curl_errno($ch);
curl_close($ch);

return array(
"status"=>$respStatus,
"headers"=> headerStrHandler($respHeaders),
"body"=>$respBody
);
}

function headerStrHandler($headerStr) {
$headerLines = explode("\n", $headerStr);
$headers = array();
foreach($headerLines as $headerLine) {
$header = explode(": ", $headerLine);
if (count($header) > 1) {
$headers[trim($header[0])] = trim($header[1]);
}
}
return $headers;
}

// 对于该链接http://localhost:3001/test.php?asdf=sadf&asd1=11#asd
// /test.php?asdf=sadf&asd1=11
// echo $_SERVER["REQUEST_URI"];
// 所有参数可以这样查看
// var_dump($_SERVER);
$url = "https://www.baidu.com";
$method = $_SERVER["REQUEST_METHOD"];
$headers = array();
foreach (getallheaders() as $key => $value) {
if (strtolower($key) == "accept") {
$headers["accept"] = $value;
}
if (strtolower($key) == "content-type") {
$headers[] = "content-type: $value";
}
}
$headers[] = "user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 UOS";
// 可以直接组装数据
// $body = "wd=hello&type=1";
// 也可以从文件流获取
$body = file_get_contents("php://input");

if ($method == "OPTIONS") {
http_response_code(200);
header("access-control-allow-headers: *");
header("access-control-allow-origin: *");
header("content-type: text/html");
die();
}

http_response_code(200);
header("access-control-allow-headers: *");
header("access-control-allow-origin: *");
header("content-type: application/json; charset=utf-8");
$response = httpRequest($url, $method, $headers, $body);

echo $response["body"];

连接MySQL的操作

面向过程的操作

折叠代码块PHP 复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
$databaseInfo = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'test'
);

$mysqlConnection = mysqli_connect(
$databaseInfo['host'],
$databaseInfo['username'],
$databaseInfo['password'],
$databaseInfo['database']
);

if (!$mysqlConnection) {
echo("connection failed");
return;
}

mysqli_set_charset($mysqlConnection,'utf8');

// 查询
$queryResult = mysqli_query($mysqlConnection, "select name from pre_forum_forum limit 1;");
// 获取结果集行数
$queryResultRows = mysqli_num_rows($queryResult);
$returnData = array();

for($i = 0; $i < $queryResultRows; $i++) {
$returnData[$i] = mysqli_fetch_array($queryResult, MYSQLI_NUM);
}
var_dump($returnData);

// 增删改
$sql = "delete from pre_forum_forum where fid = 39;";
$otherOperation = mysqli_query($mysqlConnection, $sql);
// 插入操作后获取到插入的行数
$operationRowId = mysqli_insert_id($mysqlConnection);
echo("operationRowId: ".$operationRowId);

// 关闭数据库连接
mysqli_close($mysqlConnection);
?>

面向对象的操作

可以参考这里

折叠代码块PHP 复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

// 检查连接
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$city = "Amersfoort";

// 创建一个预编译 SQL 语句
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
// 对于参数占位符进行参数值绑定
// 第一个参数用于指定后边多个绑定数据的类型
// s是字符串,d是双精度,i表示整数,b表示blob
$stmt->bind_param("s", $city);
// 执行查询
$stmt->execute();

// 如果是增删改则不需要store_result,bind_result,fetch
// 将数据存到内存
$stmt->store_result();
// 获取执行的行数
$numRows = $stmt->num_rows;
for($i = 0; $i < $numRows; $i++) {
// 将查询结果绑定到变量,如果有多列值可以绑定多个变量
$stmt->bind_result($district);
// 获取查询结果值,只获取一行
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
}

// 关掉语句对象
$stmt->close();
}

// 关闭连接
$mysqli->close();
?>

遍历

数组遍历

折叠代码块PHP 复制代码
1
2
3
foreach($line as $arr) {
var_dump($line);
}

文件读写

折叠代码块PHP 复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
// 将文件写出到本地
$file = "asdf";
$op_file = fopen("index.html", 'w');
fwrite($op_file, $file);
fclose($op_file);

// 读出文件
$op_file = fopen("index.html", 'r');
// 读取整个文件
$newFile = fread($op_file, filesize("index.html"));
fclose($op_file);
var_dump($newFile);

正则

折叠代码块PHP 复制代码
1
2
3
4
5
6
7
8
9
10
<?php
// 查看字符串是否匹配这个正则,如果需要匹配结果,则放到了$matches中
// 0下标是所有匹配,1是第一个匹配
preg_match('/(href=")(["\/])/', $str, $matches);
// ----------------------------------------------------------
// $patternArr是一个模式匹配数组,$replacementArr是一个替换的数组
$patternArr = ['/action="/', '/href="/'];
$replacementArr = ['action="/lalala', 'href="/lalala'];
// 前边的0下标数据替换后边的0下标数据
preg_replace($patternArr, $replacementArr, $str);

对象

折叠代码块PHP 复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
class dbEditor {
private $config;
// 构造函数
public function __construct() {
// 使用属性
$this->config = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'test'
);
// 使用方法
$this->hello("hello");
}
private function hello($str) {
echo $str;
}
}
 评论
Powered By Valine
v1.5.2