php小笔记

php在线工具

三目运算

1
2
3
4
5
10%2==0 ? echo '$a 是偶数' : echo '$a 是奇数';
10%2==0 ? "" : echo '$a 是奇数';
$a = 10; $b = 6; $c = 12;
$x = $a>$b ? ($a<$c ? $c-$a : $a-$c) : ($b<$c ? $c-$b : $b-$c);
echo '$x ='.$x; //$x =2

字符串

数组转换为字符串

1
2
3
4
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr)."\n"; //Hello World! Beautiful Day!
echo join(" ",$arr)."\n"; //同上
echo implode($arr)."\n"; //!HelloWorld!BeautifulDay!
1
2
3
4
5
6
7
8
9
$arrs = array(
array('topicid' => 1),
array('topicid' => 2),
array('topicid' => 6)
);

$topicid = ''; //变量赋值为空
foreach($arrs as $key=>$vals){ $topicid.=$vals['topicid'].','; }
echo rtrim($topicid, ','); //1,2,6 使用 rtrim() 函数从字符串右端删除字符:

字符串切割为数组

1
2
3
4
5
$str = "hello,,world";
print_r(explode(",", $str)); //Array ( [0] => hello [1] => [2] => world)
//将字符串分割成数组,参数二将字符串从左向右每3个字符分割一次,最后的不够3个了 有几个算几个
print_r(str_split($str, 3)); //Array ( [0] => hel [1] => lo, [2] => ,wo [3] => rld)
print_r(preg_split("/,+/", $str)); //Array ( [0] => hello [1] => world)

插入元素到数组末尾

1
$a=array("red","green"); array_push($a,"blue","yellow"); print_r($a); // Array ( [0] => red [1] => green [2] => blue [3] => yellow)

数组相减

1
2
3
4
$a1 = [1,2,3,4,5];
$a2 = [2,4,6];
print_r(array_intersect($a1, $a2)); // Array ( [1] => 2 [3] => 4) //交集
print_r(array_diff($a1, array_intersect($a1, $a2))); // Array ( [0] => 1 [2] => 3 [4] => 5) //减去交集(差集)

遍历修改数组

1
2
3
4
$array= array(1,2,3,4,5,);
foreach ($array as &$value) { $value = $value*2; } //使用引用符号
unset($value); //遍历后value依然引用着最后元素,可用unset取消
print_r($array); //Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10)

换行改为br换行

1
2
3
echo nl2br("One line.\nAnother line.");
//One line.<br />
//Another line.

执行shell命令

这三个函数在默认的情况下,都是被禁止了的,如果要使用这几个函数,就要先修改php的配置文件php.ini,查找关键字disable_functions,将这一项中的这几个函数名删除掉,然后注意重启apache。

system()

1
2
3
4
$last_line=system("ping 192.168.16.1 -c1", $status); //输出到当前位置,返回最后一行字符串
if($status){ echo "执行失败\n"; }
else { echo "执行成功\n"; }
echo "last_line:".$last_line;
1
2
3
4
5
6
7
8
PING 192.168.16.1 (192.168.16.1) 56(84) bytes of data.
64 bytes from 192.168.16.1: icmp_seq=1 ttl=63 time=2.37 ms

--- 192.168.16.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 2.372/2.372/2.372/0.000 ms
执行成功
last_line:rtt min/avg/max/mdev = 2.372/2.372/2.372/0.000 ms

exec()

1
2
3
4
$last_line=exec("ping 192.168.16.1 -c1", $result, $status); //输出到数组$result,返回最后一行字符串
if($status){ echo "执行失败\n";print_r($result); }
else { echo "执行成功\n";print_r($result); }
echo "last_line:".$last_line;
1
2
3
4
5
6
7
8
9
10
11
执行成功
Array
(
[0] => PING 192.168.16.1 (192.168.16.1) 56(84) bytes of data.
[1] => 64 bytes from 192.168.16.1: icmp_seq=1 ttl=63 time=2.54 ms
[2] =>
[3] => --- 192.168.16.1 ping statistics ---
[4] => 1 packets transmitted, 1 received, 0% packet loss, time 0ms
[5] => rtt min/avg/max/mdev = 2.536/2.536/2.536/0.000 ms
)
last_line:rtt min/avg/max/mdev = 2.536/2.536/2.536/0.000 ms

passthru()

passthru('ls',$res);输出到当前位置,命令执行结果存到$res,函数返回void

form checkbox

1
2
3
4
5
6
7
8
9
<!--a.html-->
<form action="checkbox-form.php" method="post">
<label>使能: <input type="checkbox" name="enable" value="enabled" /></label><br/>
<label><input type="checkbox" name="testarray[]" value="apple" />苹果</label><br/>
<label><input type="checkbox" name="testarray[]" value="banana" />香蕉</label><br/>
<label><input type="checkbox" name="testarray[]" value="cat" /></label><br/>
<label><input type="checkbox" name="testarray[]" value="dog" /></label><br/>
<input type="submit" name="提交" value="Submit" />
</form>
1
2
3
4
//checkbox-form.php
if(isset($_POST['enable']) && $_POST['enable'] == 'enabled') { echo "enabled<br/>"; }
else { echo "disabled<br/>"; }
if(isset($_POST['testarray'])){ var_dump($_POST['testarray']); if(empty($_POST['testarray'])) { echo("You select nothing."); } }
1
2
disabled
array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(3) "cat" }

form 提交多维数组

二维

1
2
3
4
5
6
7
8
<tr>
<td><input name="params[0][a]" type="text" /></td>
<td><input name="params[0][b]" type="text" /></td>
</tr>
<tr>
<td><input name="params[1][a]" type="text" /></td>
<td><input name="params[1][b]" type="text" /></td>
</tr>
1
2
3
4
5
6
7
8
array(2) {
["params"]=> array(2) {
[0]=> array(2) {
["a"]=> string(1) "1" ["b"]=> string(1) "2" }
[1]=> array(2) {
["a"]=> string(1) "3" ["b"]=> string(1) "4" }
}
}

三维和关联数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<tr>
<td><input name="params[hello]" type="text" /></td>
<td><input name="params[world]" type="text" /></td>
</tr>
<tr>
<td><input name="params[0][0][a]" type="text" /></td>
<td><input name="params[0][0][b]" type="text" /></td>
</tr>
<tr>
<td><input name="params[0][1][a]" type="text" /></td>
<td><input name="params[0][1][b]" type="text" /></td>
</tr>
<tr>
<td><input name="params[1][0][a]" type="text" /></td>
<td><input name="params[1][0][b]" type="text" /></td>
</tr>
<tr>
<td><input name="params[1][1][a]" type="text" /></td>
<td><input name="params[1][1][b]" type="text" /></td>
</tr>
1
2
3
4
5
6
7
8
9
10
11
12
array(2) {
["params"]=> array(4) {
["hello"]=> string(1) "h"
["world"]=> string(1) "w"
[0]=> array(2) {
[0]=> array(2) { ["a"]=> string(1) "1" ["b"]=> string(1) "2" }
[1]=> array(2) { ["a"]=> string(1) "3" ["b"]=> string(1) "4" } }
[1]=> array(2) {
[0]=> array(2) { ["a"]=> string(1) "5" ["b"]=> string(1) "6" }
[1]=> array(2) { ["a"]=> string(1) "7" ["b"]=> string(1) "8" } }
}
}

注意:

  1. html代码中,提交name数组中的key不用加引号,加引号之后后端的键值中会存在引号
  2. 现在更流行的做法是ajax提交,用ajax提交的时候怎么获取表单中的值呢?通过jquery提供的serialize()方法可以很方便的将所有要提交的内容拼接成url字符串,然后通过get的方式就可以提交给后台了。

ajax提交多维数组

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
//var_dump($_POST);
<form id="myForm" method="post" onsubmit="return save()">
<label>Favorite Colors</label>
<input type="text" name="fav[color][]" required value="red"/>
<input type="text" name="fav[color][]" required value="green"/>
<input type="text" name="fav[color][]" required value="blue"/>

<label>Favorite Food</label>
<input type="text" name="fav[food][]" required value="bacon"/>
<input type="text" name="fav[food][]" required value="eggs"/>

<input type="submit" value="Submit"/>
</form>

<script type="text/javascript">
function save () {
// (A) GET FORM DATA
var form = document.getElementById("myForm"),
data = new FormData(form);

// (B) TO MANUALLY APPEND MORE DATA
data.append("address[]", "Foo Street 123");
data.append("address[]", "Hello World #234");

// (C) AJAX FETCH
fetch("<?php echo $_SERVER['PHP_SELF']; ?>", { method:"POST", body:data })
.then(res=>res.text()).then((response) => {
console.log(response);
});
return false;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
array(3) {
["fav"]=> array(2) {
["color"]=> array(3) {
[0]=> string(3) "red" [1]=> string(5) "green" [2]=> string(4) "blue"
}
["food"]=> array(2) {
[0]=> string(5) "bacon" [1]=> string(4) "eggs"
}
}
["address"]=> array(2) {
[0]=> string(14) "Foo Street 123"
[1]=> string(16) "Hello World #234"
}
}

如果需要用json,那ajax代码改为

1
2
3
4
5
6
7
8
9
10
11
<script>
// (A) ARRAY TO STRING
var colors = ["Red", "Green", "Blue"];
colors = JSON.stringify(colors);
console.log(colors); // ["Red","Green","Blue"]

// (B) SEND AS FLAT STRING
var data = new FormData(form);
data.append("colors", colors);
fetch("SCRIPT", { method:"POST", body:data });
</script>

后端处理代码为:var_dump(json_decode($_POST["colors"]));

json_encode ‘/‘不转义,中文不转码

一般用json_encode($data,256)或json_encode($data,true) 来保证数据中的中文等特殊字符不被转码

如果数据中含有URL或是有转义字符(如斜杆/),这些字符将被转义,前面加上\,如:http://www.xxx.com/xxxx 将会被转义成http:\/\/www.xxx.com\/xxxx 。这种情况下,若接口方未对数据进行json_decode的话,这种URL就是不合法的,你直接在浏览器访问也会访问不到。

这就需要把数据转json时,既不被转义,中文也不转码,防范如下(JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE不要加引号):

json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE); // 斜杆(/)不转义,中文不转码