php-運行在服務端的跨平臺免費面向對象的腳本語言javascript
Windows Apache MySQL PHP
,官網:www.wampserver.com/ (首頁挺狂放)php
安裝軟件能夠隨便在哪裏下,官網挺慢的。安裝next,也沒什麼好說的css
訪問localhost,出現界面,表示服務端已經通了。(雖然目前什麼都沒作)html
也就是便捷操做的面板java
好比進入MySQL的控制檯(WAMPServer會自動幫咱們裝一個MySQL,默認無密碼)python
如今將一個之前的靜態站點放在項目下的poem文件夾下mysql
而後訪問:http://localhost/poem/,不出所料,正常訪問。
注意:
到如今爲止都是Apache的功勞,和PHP還沒太大的關係。c++
這裏在:
J:\PHP\webset
文件夾下放一個站點的文件,只須要簡單的修改如下配置,再重啓便可git
---->[D:\M\WAMP\wamp64\bin\apache\apache2.4.23\conf\extra\httpd-vhosts.conf]------------------------
<VirtualHost *:80>
ServerName toly1994328.com #站點名
DocumentRoot J:/PHP/webset #站點源碼文件夾
<Directory "J:/PHP/webset">
Options Indexes FollowSymLinks #站點權限相關
AllowOverride all
Require all granted
</Directory>
</VirtualHost>
---->[C:\Windows\System32\drivers\etc\hosts]------------------------
127.0.0.1 toly1994328.com
---->[D:\M\WAMP\wamp64\bin\apache\apache2.4.23\conf\httpd.conf]------------------------
# Virtual hosts
Include conf/extra/httpd-vhosts.conf #這句話若是封住要解封(我這默認就開的)
複製代碼
詳見圖片上的url中的端口號github
---->[D:\M\WAMP\wamp64\bin\apache\apache2.4.23\conf\httpd.conf]------------------------
Listen 0.0.0.0:8081
Listen [::0]:8081
ServerName localhost:8081
|-- 多站點的話也要修改 httpd-vhosts 裏的端口號
---->[D:\M\WAMP\wamp64\bin\apache\apache2.4.23\conf\extra\httpd-vhosts.conf]------------------------
<VirtualHost *:8081>
ServerName localhost
...
<VirtualHost *:8081>
ServerName toly1994328.com #站點名
...
</VirtualHost>
複製代碼
Hello World
先 : echo 輸出
感受挺爽的嘛,SpringBoot的HelloWorld比這麻煩多了
---->[Hello.php]---------------------------
<?php
echo "Hello World!";
複製代碼
$ 名稱 = 變量
---->[vartest.php]---------------------------
<?php
$name="張風捷特烈";//生成變量
echo $name;//輸出變量
echo "<br />";//輸出換行
$name="toly";//改變變量
echo $name;//輸出變量
複製代碼
感受比JavaScript還要奔放,比Python要收斂一丟丟。就是$符號太多...晃眼
<?php
$t = true;//1.布爾型
$fa = false;//布爾型
$i = 5; //2.整型
$a = 0xff; // 支持十六進制數 -- 255
$b = 074; // 支持八進制數 -- 60
$f = 3.14159;//3.浮點型
$f1 = 3.14159e4;//浮點型 31415.9
$f2 = 3.14159e-3;//浮點型 0.00314159
$str = "String Type";//4.字符串
$str = 'String Type';//字符串
$color = array("red", "green", "blue");//5.數組
echo $color[0];//獲取元素
$colorMap = array("red"=>"紅色", "green"=>"綠色", "blue"=>"藍色");//6.相似映射或字典
echo $colorMap["red"];//紅色
$shape = new Shape("四維空間");//7.對象
echo $shape->getName(); //調用方法
$n=null;//8.null
class Shape{
var $name;
function __construct($name = "green"){
$this->name = $name;
}
/**
* @return string
*/
public function getName() {
return $this->name;
}
/**
* @param string $name
*/
public function setName($name){
$this->name = $name;
}
}
複製代碼
Hello.php
|--- 客戶端請求 (此時不太關心)
GET http://toly1994328.com/Hello.php HTTP/1.1
Host: toly1994328.com
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
|--- 服務端響應
HTTP/1.1 200 OK
Date: Wed, 13 Mar 2019 14:06:15 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By: PHP/5.6.25
Content-Length: 13
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8 <----text/html 表示可讓瀏覽器解析請求體中的html代碼
Hello World! <---- 可見echo能夠將數據放入請求體裏
複製代碼
既然echo能夠輸出,放個靜態頁面輸出會怎麼樣,就來個粒子吧
這說明echo能夠將整個html頁面輸出讓瀏覽器解析,這樣的話php的地位應該是控制服務端的輸出流。
<?php
echo "<!doctype html> <html> <head> <meta charset=\"utf-8\"> <title>液態粒子字體</title> <style> body,html { margin:0; width:100%; overflow:hidden; } canvas { width:100%; } .control { position:absolute; } .control input { border:0; margin:0; padding:15px; outline:none; text-align:center; } .control button { border:0; margin:0; padding:15px; outline:none; background:#333; color:#fff; } .control button:focus,.control button:hover { background:#222 } </style> </head> <body> <div class = \"control\" style = \"position:absolute\"> <input type = \"text\" value = \"張風捷特烈\" id = \"t\"> <button onclick = \"changeText(t.value)\"> change </button> </div> <script> var can = document.createElement(\"canvas\"); document.body.appendChild(can); var ctx = can.getContext('2d'); function resize(){ can.width = window.innerWidth; can.height = window.innerHeight; } const max_radius = 3; const min_radius = 1; const drag = 50; window.onresize = function(){ resize(); }; function cfill(){ ctx.fillStyle = \"#000\"; ctx.fillRect(0,0,can.width,can.height); ctx.fill(); } var mouse = { x:-1000, y:-1000 }; can.onmousemove = function(e){ mouse.x = e.clientX; mouse.y = e.clientY; }; can.ontouchmove = function(e){ mouse.x = e.touches[0].clientX; mouse.y = e.touches[0].clientY; }; resize(); cfill(); function distance(x,y,x1,y1){ return Math.sqrt( ( x1-x ) * ( x1-x ) + ( y1-y ) * ( y1-y ) ); } class Particle{ constructor(pos,target,vel,color,radius){ this.pos = pos; this.target = target; this.vel = vel; this.color = color; this.radius = radius; var arr = [-1,1]; this.direction = arr[~~(Math.random()*2)]*Math.random()/10; } set(type,value){ this[type] = value; } update(){ this.radius += this.direction; this.vel.x = (this.pos.x - this.target.x)/drag; this.vel.y = (this.pos.y - this.target.y)/drag; if(distance(this.pos.x,this.pos.y,mouse.x,mouse.y) < 50){ this.vel.x += this.vel.x - (this.pos.x - mouse.x)/15; this.vel.y += this.vel.y - (this.pos.y - mouse.y)/15; } if(this.radius >= max_radius){ this.direction *= -1; } if(this.radius <= 1){ this.direction *= -1; } this.pos.x -= this.vel.x; this.pos.y -= this.vel.y; } draw(){ ctx.beginPath(); ctx.fillStyle = this.color; ctx.arc(this.pos.x,this.pos.y,this.radius,0,Math.PI*2); ctx.fill(); } } var particles = []; var colors = [\"#bf1337\",\"#f3f1f3\",\"#084c8d\",\"#f2d108\",\"#efd282\"]; var bool = true; var current = 0,i; function changeText(text){ var current = 0,temp,radius,color; cfill(); ctx.fillStyle = \"#fff\"; ctx.font = \"120px Times\"; ctx.fillText(text,can.width*0.5-ctx.measureText(text).width*0.5,can.height*0.5+60); var data = ctx.getImageData(0,0,can.width,can.height).data; cfill(); for(i = 0;i < data.length;i += 8){ temp = {x:(i/4)%can.width,y:~~((i/4)/can.width)}; if(data[i] !== 0 && ~~(Math.random()*5) == 1/*(temp.x % (max_radius+1) === 0 && temp.y % (max_radius+1) === 0)*/){ if(data[i+4] !== 255 || data[i-4] !== 255 || data[i+can.width*4] !== 255 || data[i-can.width*4] !== 255){ if(current < particles.length){ particles[current].set(\"target\",temp); }else{ radius = max_radius-Math.random()*min_radius; temp = {x:Math.random()*can.width,y:Math.random()*can.height}; if(bool){ temp = {x:(i/4)%can.width,y:~~((i/4)/can.width)}; } color = colors[~~(Math.random()*colors.length)]; var p = new Particle( temp, {x:(i/4)%can.width,y:~~((i/4)/can.width)},{x:0,y:0}, color, radius); particles.push(p); } ++current; } } } bool = false; particles.splice(current,particles.length-current); } function draw(){ cfill(); for(i = 0;i < particles.length;++i){ particles[i].update(); particles[i].draw(); } } changeText(\"張風捷特烈\"); setInterval(draw,1);</script> </body> </html>"
複製代碼
工欲善其事必先利其器,總不能在文本編輯器裏寫代碼吧,IDE 本人首選Idea
而後就開心的敲代碼了,提示什麼的都有
好了,引入到此爲止,下面開始正文
---->[obj/Shape.php]----------------
<?php
namespace toly1994;
class Shape{
public function __construct(){
echo "Shape構造函數";
}
function __destruct(){
echo "Shape析構函數";
}
}
---->[obj/Client.php]----------------
<?php
include './Shape.php';//引入文件
use toly1994\Shape;
$shape = new Shape();
複製代碼
---->[obj/Shape.php]----------------
<?php
namespace toly1994;
class Shape{
private $name;
public function __construct($name){
echo "Shape構造函數<br/>";
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function setName($name){
$this->name = $name;
}
public function draw(){
echo "繪製$this->name <br/>";
}
function __destruct(){
echo "Shape析構函數";
}
}
|-- 使用 --------------------------
$shape = new Shape("Shape");
$shape->draw();//繪製Shape
$shape->setName("四維空間<br/>");
echo $shape->getName();//四維空間
複製代碼
---->[obj/Point.php]----------------
<?php
namespace toly1994;
class Point extends Shape{
public $x;
public $y;
}
|-- 使用 --------------------------
$point = new Point("二維點");
$point->draw();//繪製二維點
echo $point->getName();//二維點
$point->x=20;//二維點
echo $point->x;//20
複製代碼
---->[obj/Circle.php]----------------
<?php
namespace toly1994;
class Circle extends Shape{
private $radius;
public function getRadius(){
return $this->radius;
}
public function setRadius($radius){
$this->radius = $radius;
}
public function draw(){
echo "Draw in Circle<br/>";
}
}
---->[obj/Point.php]----------------
<?php
namespace toly1994;
class Point extends Shape{
public $x;
public $y;
public function draw(){
echo "Draw in Point<br/>";
}
}
|-- 使用 --------------------------
$point=new Point("");
doDraw($point);//Draw in Point
$circle=new Circle("");
doDraw($circle);//Draw in Circle
function doDraw(Shape $shape){
$shape->draw();
}
複製代碼
抽象類---->[obj/Shape.php]----------------
abstract class Shape{
...
//抽象方法
abstract protected function draw();
}
接口---->[obj/Drawable.php]----------------
<?php
namespace toly1994;
interface Drawable{
public function draw();
}
|-- 實現接口 implements 關鍵字-----------
include './Drawable.php';//引入文件
abstract class Shape implements Drawable
複製代碼
在Circle類中,定義一個函數計算圓的面積:
getArea
---->[obj/Circle.php]----------------
<?php
namespace toly1994;
define("PI", 3.141592654);//定義常量
class Circle extends Shape{
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
...
/**
* 獲取圓的面積
* @return float|int
*/
public function getArea(){
$area = PI * $this->radius * $this->radius;
return $area;
}
}
|-- 對象使用函數(方法)
$circle = new Circle(10);
echo $circle->getArea();//314.15926541
$circle->setRadius(20);
echo $circle->getArea();//256.6370616
複製代碼
函數名調用時居然不區分大小寫,方法也不支持重載,真是神奇的語言...
建立一個工具類來換行
---->[utils/Utils.php]--------------------
<?php
class Utils{
/**
* 換行工具方法
* @param int $num 行數
* @param bool $line true <hr> false <br>
*/
public static function line($num = 1, $line = true)
{
for ($i = 0; $i < $num; $i++) {//for循環控制
if ($line) {//條件控制
echo "<hr>";
} else {
echo "<br>";
}
}
}
}
---->[base/Funtest.php]------調用--------------
<?php
include '../utils/Utils.php';
Utils::line();//默認一行 有線
Utils::line(2,false);//兩行 無線
Utils::line(5);//五行 無線
複製代碼
/** 建立表格
* @param $content 二維數組
* @param string $css 表格樣式
* @return string
*/
public static function createTable($content, $css = "border='1' cellspacing='0' cellpadding='0' width='80%'")
{
$row = count($content);
$col = count($content[0]);
$table = "<table $css>";
for ($i = 0; $i < $row; $i++) {//for循環控制
$table .= "<tr/>";
for ($j = 0; $j < $col; $j++) {
$value = $content[$i][$j];
$table .= "<td>$value</td>";
}
$table .= "</tr>";
}
$table .= "</table>";
return $table;
}
|-- 使用---------------------------
<?php
include '../utils/Utils.php';
$content = [
["姓名", "年齡", "性別", "武器", "職業"],
["捷特", 24, "男", "黑風劍", "戰士"],
["龍少", 23, "男", "控尊戒", "鑄士"],
["巫纓", 23, "女", "百里弓", "弓士"],
];
echo Utils::createTable($content);
Utils::line();
$css = "border='5' cellspacing='0' cellpadding='0' width='80%' bgcolor=#81D4F5";
echo Utils::createTable($content, $css);//自定義表格樣式
複製代碼
局部變量不能在塊的外面被調用
|--- 方法中[局部變量-動態變量]在函數調用完成會釋放------------------
function area1(){
static $inArea = true;
if ($inArea) {
echo "true<br/>";
} else {
echo "false<br/>";
}
$inArea = !$inArea;
}
area1();//true
area1();//true
area1();//true
|--- 方法中[局部變量-靜態變量]在函數調用完成不會釋放,在靜態內存區----------------
function area1(){
static $inArea = true;
if ($inArea) {
echo "true<br/>";
} else {
echo "false<br/>";
}
$inArea = !$inArea;
}
area1();//true
area1();//false
area1();//true
複製代碼
|-- 方法體中不能使用外面定義的變量
$name = "toly";
function say(){
echo "My name is $name" ;//Undefined variable: name
}
say();
|-- 解決方,1,在方法體中使用global關鍵字對變量進行修飾
$name = "toly";
function say(){
global $name;
echo "My name is $name";
}
say();
|-- 解決方法2,使用$GLOBALS鍵值對獲取全局變量
$name = "toly";
function say(){
echo "My name is " . $GLOBALS['name'];
}
say();
複製代碼
|-- 傳入值,並不會致使原值污染
function add($target){
$target = $target + 1;
return $target;
}
$num = 10;
$res = add($num);
echo $res;//11
echo $num;//10
|-- 傳引用,方法中對入參的修改會修改原值
function add(&$target)//取地址{
$target = $target + 1;
return $target;
}
$num = 10;
$res = add($num);
echo $res;//11
echo $num;//11
複製代碼
|-- 可變函數(函數的變量化)----------------
function add($x, $y){
return $x + $y;
}
$fun = "add";//函數變量化
echo $fun(3, 4);//7
|-- 函數做爲入參(俗稱回調) ----------------
function add($x, $y, $fun){
return $fun($x) + $fun($y);
}
echo add(3, 4, function ($i) {//此處經過匿名函數
return $i * $i;
});//25
|-- //此處經過create_function建立匿名函數(php7.2後過期)
echo add(3, 4, create_function('$i', 'return $i * $i;'));//25
|-- 經過 call_user_func 來調用函數--------感受挺詭異
call_user_func("md5", "張風捷特烈");//20ce3e8f34f3a3dd732a150a36d41512
|-- 經過 call_user_func_array 來調用函數--------第二參是參數的數組
function add($x, $y){
return $x + $y;
}
echo call_user_func_array("add", array(3,4));//7
複製代碼
$path = 'G:/Out/language/php/2/3/45/dragon.txt';
createFile($path);
function createFile($path){
$dir = dirname($path);//獲取父文件
if (!file_exists($dir)) {
mkdirs($dir);
createFile($path);
} else {
fopen($path, "w");
}
}
function mkdirs($dir){
return is_dir($dir) or mkdirs(dirname($dir)) and mkdir($dir, 0777);
}
複製代碼
文件不存在,則建立文件再寫入
/**
* 將內容寫入文件
* @param $path 路徑
* @param $content 內容
*/
function writeStr($path, $content){
if (file_exists($path)) {
if ($fp = fopen($path, 'w')) {
fwrite($fp, $content);
fclose($fp);
echo "<br>寫入成功 " . $content;
} else {
echo "<br>建立失敗 ";
}
} else {
createFile($path);
writeStr($path, $content);
}
}
複製代碼
|-- 內置函數 readfile 讀取文件
echo readFile($path);
|-- fgetc 逐字讀取
function readFileByPath($path){
$result = "";
$file = fopen($path, "r") or $result . "沒法打開文件!";
while (!feof($file)) {
$result .= fgetc($file);
}
fclose($file);
return $result;
}
|-- fgets 逐行讀取
function readFileByLine($path){
$result = "";
$file = fopen($path, "r") or $result . "沒法打開文件!";
while (!feof($file)) {
$result .= fgets($file)."<br/>";
}
fclose($file);
return $result;
}
|-- 以行劃分將文件讀入數組
var_dump(file($path));
array(3) { [0]=> string(26) "應龍----張風捷特烈 " [1]=> string(49) "一遊小池兩歲月,洗卻凡世幾閒塵。 " [2]=> string(48) "時逢雷霆風會雨,應乘扶搖化入雲。" }
複製代碼
還有不少亂七八糟的方法...用的時候再找吧,感受和Python挺像的
$path = 'G:/Out/language/php/2/3/45/dragon.txt';
$stat = stat($path);
echo "建立時間:" . date("Y-m-d H:i", $stat["ctime"]);//2019-03-14 04:45
echo "修改時間:" . date("Y-m-d H:i", $stat["mtime"]);//2019-03-14 04:54
echo "文件大小:" . $stat["size"] . " 字節";
echo "文件模式:" . $stat["mode"];
echo "文件名:" . basename($path);
echo "父文件夾:" . dirname($path);
echo "是不是文件夾:" . (is_dir($path) ? "true" : "false");
echo "是不是文件:" . (is_file($path) ? "true" : "false");
echo "是否存在:" . (file_exists($path) ? "true" : "false");
echo "文件所在磁盤可用大小:" . disk_free_space(dirname($path)) . " 字節";
echo "文件所在磁盤總大小:" . disk_total_space(dirname($path)) . " 字節";
echo "文件類型:" . filetype($path);//file
複製代碼
基本上和其餘語言同樣
r 只讀。在文件的開頭開始。
r+ 讀/寫。在文件的開頭開始。
w 只寫。打開並清空文件的內容;若是文件不存在,則建立新文件。
w+ 讀/寫。打開並清空文件的內容;若是文件不存在,則建立新文件。
a 追加。打開並向文件末尾進行寫操做,若是文件不存在,則建立新文件。
a+ 讀/追加。經過向文件末尾寫內容,來保持文件內容。
x 只寫。建立新文件。若是文件已存在,則返回 FALSE 和一個錯誤。
x+ 讀/寫。建立新文件。若是文件已存在,則返回 FALSE 和一個錯誤。
複製代碼
仍是玩sword表吧
<?php
$host = "localhost";
$user = "root";
$pwd = "----";
$conn = mysqli_connect($host, $user, $pwd);
// 檢測鏈接
if ($conn->connect_error) {
die("鏈接失敗: " . $conn->connect_error);
}
echo "鏈接成功";
$conn->close();//關閉數據庫
複製代碼
連上數據庫而後就是SQL的領域了
<?php
include './Sword.php';
$host = "localhost";
$user = "root";
$pwd = "----";
$conn = mysqli_connect($host, $user, $pwd);
// 檢測鏈接
if ($conn->connect_error) {
die("鏈接失敗: " . $conn->connect_error);
}
echo "鏈接成功";
mysqli_select_db($conn, "zoom");//選擇數據庫
$sql = "SELECT * FROM sword";//sql語句
$result = $conn->query($sql);
$swords = array();
if ($result->num_rows > 0) {
// 輸出數據
while ($row = $result->fetch_assoc()) {
$sword = new Sword(
$row["id"],
$row["name"],
$row["atk"],
$row["hit"],
$row["crit"],
$row["attr_id"],
$row["type_id"]
);
array_push($swords, $sword);
}
}
複製代碼
echo json_encode($swords);
複製代碼
也能夠將結果輸出成表格
function createTable($content, $css = "border='1' cellspacing='0' cellpadding='0' width='80%'"){
$row = count($content);
$table = "<table $css >";
for ($i = 0; $i < $row; $i++) {//for循環控制
$table .= "<tr/>";
$value = $content[$i];
$table .= "<td >$value->id</td>";
$table .= "<td >$value->name</td>";
$table .= "<td >$value->atk</td>";
$table .= "<td >$value->hit</td>";
$table .= "<td >$value->crit</td>";
$table .= "<td >$value->attr_id</td>";
$table .= "<td >$value->type_id</td>";
$table .= "</tr>";
}
$table .= "</table>";
return $table;
}
複製代碼
// 建立數據庫
$sql = "CREATE DATABASE php";
echo $conn->query($sql) ? "數據庫建立成功" : "數據庫建立失敗" . $conn->error;
複製代碼
mysqli_select_db($conn, "php");//選擇數據庫
$sql="create table sword ( id smallint(5) unsigned auto_increment primary key, name varchar(32) not null, atk smallint(5) unsigned not null, hit smallint(5) unsigned not null, crit smallint(5) unsigned default '10' null, attr_id smallint(5) unsigned not null, type_id smallint(5) unsigned not null )";
echo $conn->query($sql) ? "sword建立成功" : "sword建立失敗" . $conn->error;
複製代碼
另外增刪改查的操做關鍵是sql語句,本文就不引伸了
|-- 雙引號 : 可解析變量 解析全部轉移符--------------
<?php
$name = "toly-張風捷特烈-1994328";
echo "$name";
|-- 單引號: 不可解析變量 只解析\' \\兩個轉義符------------ <?php $name = "toly-張風捷特烈-1994328"; echo '$name'; |-- 字符衝突時用轉義符 : \--------------------- \\ \' \$ \" \r \n \t \f |-- {}的輔助 --- {}要緊貼變量,不要加空格---------------- echo "{$name}s";//toly-張風捷特烈-1994328s echo "${name}s";//toly-張風捷特烈-1994328s |-- 字符的操做 echo $name[0];//t Utils::line(); echo $name{1};//o Utils::line(); $name[2]='L'; echo $name;//toLy-張風捷特烈-1994328 複製代碼
|-- heredoc做用同雙引號,只是在其中雙引號不用轉義------------
$html = <<<EOF
"在"""""s這裏面'''""'原樣輸出" EOF; echo $html; |-- nowdoc做用同單引號,只是在其中雙引號不用轉義------------ $html = <<<'EOD' "在"""""s這裏面'''""'原樣輸出"
EOD;
echo $html;
複製代碼
數字: 原樣
布爾: ture 1 false ''
null: ''
數組: Array
$num=1;
$res = (string)$num;//類型轉換
strval($num);//類型轉換
settype($num,'string')//$num自己轉變
|-- php中布爾值爲false的狀況
$flag = '';//假
$flag = "";//假
$flag = null;//假
$flag = 0;//假
$flag = "0";//假
$flag = 0.0;//假
$flag = "0.0";//真
$flag = array();//假
$flag = 'false';//真
echo $flag ? "真" : "假";
複製代碼
$name = "kiNg tolY-張風捷特烈-1994328";
echo is_string($name) ? "是字符串" : "不字符串";//是字符串
echo empty($name) ? "爲空" : "不爲空";//不爲空
echo "字符串長度:" . strlen($name);//字符串長度:33
echo "轉大寫:" . strtoupper($name);//轉大寫:KING TOLY-張風捷特烈-1994328
echo "轉小寫:" . strtolower($name);//轉小寫:king toly-張風捷特烈-1994328
echo "首字母大寫:" . ucfirst($name);//首字母大寫:KiNg tolY-張風捷特烈-1994328
echo "單詞首字母大寫:" . ucwords($name);//單詞首字母大寫:KiNg TolY-張風捷特烈-1994328
echo substr($name, 2, 8);//Ng tolY-
echo substr($name, -7, 4);//1994
echo substr($name, 2);//Ng tolY-張風捷特烈-1994328
echo substr($name, 2, -4);//Ng tolY-張風捷特烈-199
echo trim(" rry ");//rry 去除兩端的空格
echo rtrim(" rry ");// rry 去除右端的空格
echo ltrim(" rry ");//rry 去除左端的空格
echo trim($name, "k");//iNg tolY-張風捷特烈-1994328 指定字符trim
$arr = ["java","kotlin","javascript","c++"];
echo join($arr, "-->");//java-->kotlin-->javascript-->c++
|-- 字符串的正則操做
$split = preg_split("/-/", $name);//正則切割
print_r($split);//Array ( [0] => kiNg tolY [1] => 張風捷特烈 [2] => 1994328 )
$match = preg_match("/\d{10,16}/", $name);//匹配連續10~16個數字
print_r($match ? "匹配成功" : "匹配失敗");//匹配失敗
echo preg_replace("/-/","·",$name);//kiNg tolY·張風捷特烈·1994328
複製代碼
---->[reg.php]-----------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>註冊頁面</title>
</head>
<body>
<h1>註冊頁面</h1>
<form action="doReg.php" method="post">
<label>用戶名:</label>
<input type="text" name="username" placeholder="請輸入用戶名">
<label>密碼:</label>
<input type="password" name="password" placeholder="請輸入密碼">
<label>確認密碼:</label>
<input type="password" name="conform-password" placeholder="確認密碼">
<input type="submit" name="submit">
</form>
</body>
</html>
---->[doReg.php]-----------------------
<?php
$name = $_POST['username']; //獲取表單數據
echo $name; //這樣就能夠鏈接mysql插入數據庫了
複製代碼
---->[upload.php]-----客戶端-----------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳頁面</title>
</head>
<body>
<h1>上傳頁面</h1>
<form action="doUploadFile.php" method="post" enctype="multipart/form-data">
<label>選擇文件:</label>
<input type="file" name="filename" placeholder="請輸入用戶名">
<input type="submit" name="submit">
</form>
</body>
</html>
---->[doUploadFile.php]-----服務端-----------------------
<?php
print_r($_FILES); //打印一下信息(非必要)
$file = $_FILES["filename"];
$name = $file["name"];//上傳文件的名稱
$type = $file["type"];//MIME類型
$tempName = $file["tmp_name"];//臨時文件名
$size = $file["size"];//文件大小
$error = $file["error"];//錯誤
//方式一:將臨時文件移動到指定文件夾
//move_uploaded_file($tempName, "G:/Out/" . $name);
//方式二: 拷貝到目標文件夾
copy($tempName, "G:/Out/" . $name);
複製代碼
D:\M\WAMP\wamp64\bin\php\php5.6.25\php.ini
file_uploads = On 容許HTTP上傳
upload_tmp_dir ="D:/M/WAMP/wamp64/tmp" 臨時文件夾
upload_max_filesize = 2M 文件最大尺寸
max_file_uploads = 20 最大單次上傳文件數
post_max_size = 8M post發送的最大尺寸
|-- 錯誤碼----------------------
UPLOAD_ERR_OK;//0 沒有錯誤
UPLOAD_ERR_INI_SIZE;//1 超過 upload_max_filesize
UPLOAD_ERR_FORM_SIZE;//2 超過max_file_uploads
UPLOAD_ERR_PARTIAL;//3 只有部分上傳
UPLOAD_ERR_NO_FILE;//4 沒有文件
UPLOAD_ERR_NO_TMP_DIR;//6 沒有找到臨時文件夾
UPLOAD_ERR_CANT_WRITE;//7 文件寫入失敗
UPLOAD_ERR_EXTENSION;//8 上傳被中斷
複製代碼
function upload(
$file, //文件信息對象
$dir = "G:/Out/", //目標文件夾
$acceptType = ["png", "jpg", "jpeg", "gif", "bmp"],//容許的類型
$all = false, //是否忽略類型
$maxSize = 2 * 1024 * 1024){//文件大小
$name = $file["name"];//上傳文件的名稱
$tempName = $file["tmp_name"];//臨時文件名
$size = $file["size"];//文件大小
$error = $file["error"];//錯誤
$ext = pathinfo($name, PATHINFO_EXTENSION);;
judge_dirs($dir);
$dest = $dir . md5(uniqid(microtime(true), true)) . ".$ext";
if ($error == 0) {//1.上傳正確
if ($size < $maxSize) {//2.上傳文件大小
if (in_array($ext, $acceptType) || $all) {//3.拓展名
if (is_uploaded_file($tempName)) {//4.經過http post上傳
copy($tempName, $dest);// 拷貝到目標文件夾
return $dest;
}
}
}
}
exit("上傳錯誤");
}
/**
* 遞歸建立文件夾
* @param $dir 文件夾
* @return bool
*/
function judge_dirs($dirName)
{
if (file_exists($dirName)) {
return true;
}
return is_dir($dirName) or judge_dirs(dirname($dirName)) and mkdir($dirName, 0777);
}
複製代碼
從獲取的數據上來看,一個二維數組,每一個裝載了一個文件信息
---->[upload.php]--------form表單---------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳頁面</title>
</head>
<body>
<h1>上傳頁面</h1>
<form action="doUploadFile.php" method="post" enctype="multipart/form-data">
<label>選擇文件:</label><input type="file" name="filename1"><br>
<label>選擇文件:</label><input type="file" name="filename2"><br>
<label>選擇文件:</label><input type="file" name="filename3"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
---->[doUploadFile.php]--------上傳處理---------
<?php
print_r($_FILES);
複製代碼
XXX[]
從獲取的數據上來看,一個三維數組,針對每一個屬性對多個文件進行規整成數組
---->[upload2.php]--------form表單---------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳頁面</title>
</head>
<body>
<h1>上傳頁面</h1>
<form action="doUploadFile.php" method="post" enctype="multipart/form-data">
<label>選擇文件:</label><input type="file" name="filename[]"><br>
<label>選擇文件:</label><input type="file" name="filename[]"><br>
<label>選擇文件:</label><input type="file" name="filename[]"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
---->[doUploadFile.php]--------上傳處理---------
<?php
print_r($_FILES);
複製代碼
這裏封裝一個Uploader類來進行上傳管理
class Uploader
{
/** 格式化多文件上傳返回數據
* @param $files 文件信息
* @return mixed
*/
public function format($files)
{
$i = 0;
foreach ($files as $file) {
if (is_string($file['name'])) {//說明是二維數組
$result[$i] = $file;
$i++;
} elseif (is_array($file['name'])) {//說明是三維數組
foreach ($file['name'] as $k => $v) {
$result[$i]['name'] = $file['name'][$k];
$result[$i]['type'] = $file['type'][$k];
$result[$i]['tmp_name'] = $file['tmp_name'][$k];
$result[$i]['size'] = $file['size'][$k];
$result[$i]['error'] = $file['error'][$k];
$i++;
}
}
}
return $result;
}
}
複製代碼
public static $errorInfo = [
"上傳成功",
"超過 upload_max_filesize",
"超過max_file_uploads",
"只有部分上傳",
"沒有文件",
"文件類型不匹配",
"沒有找到臨時文件夾",
"文件寫入失敗",
"上傳被中斷",
"文件大小超出限制",
"文件不是經過POST上傳",
"文件移動失敗",
];
複製代碼
public function upload(
$file,
$dir = "C:/Users/Administrator/upload/temp",//目標文件夾
$all = false, //是否忽略類型,//文件大小
$maxSize = 2 * 1024 * 1024,//文件大小
$acceptType = ["png", "jpg", "jpeg", "gif", "bmp"]//容許的類型
)
{
$name = $file["name"];//上傳文件的名稱
$tempName = $file["tmp_name"];//臨時文件名
$size = $file["size"];//文件大小
$error = $file["error"];//錯誤
$ext = File::getExt($name);
$dest = $dir . File::getUniName() . "." . $ext;//輸出文件名
new File($dest);//文件夾不存在則建立文件夾
$msg["code"] = $error;
$msg["src"] = $name;
$msg["dest"] = $dest;
$msg['info'] = Uploader::$errorInfo[$error];
if ($file["error"] == UPLOAD_ERR_OK) {//1.成功
if ($size > $maxSize) {//2.文件大小限制
$msg['info'] = Uploader::$errorInfo[9];
}
if (!in_array($ext, $acceptType) && !$all) {//3.文件類型匹配
$msg['info'] = Uploader::$errorInfo[5];
}
if (!is_uploaded_file($tempName)) {//4.經過http post上傳
$msg['info'] = Uploader::$errorInfo[10];
}
if (!move_uploaded_file($tempName, $dest)) {// 拷貝到目標文件夾
$msg['info'] = Uploader::$errorInfo[11];
}
}
return $msg;
}
複製代碼
<?php
namespace file;
class File
{
private $path;
/**
* File constructor.
* @param $path
*/
public function __construct($path)
{
$this->path = $path;
if (is_dir($path)) {
$this->judge_dirs_or_create($path);
} else {
$this->createFile($path);
}
}
public function createFile($path)
{
$dir = dirname($path);//獲取父文件
if (!file_exists($dir)) {
$this->judge_dirs_or_create($dir);
$this->createFile($path);
} else {
fopen($path, "w");
}
}
/**
* 遞歸建立文件夾
* @param $dir 文件夾
* @return bool
*/
public function judge_dirs_or_create($dirName)
{
if (file_exists($dirName)) {
return true;
}
return is_dir($dirName) or $this->judge_dirs_or_create(dirname($dirName)) and mkdir($dirName, 0777);
}
/**
* 獲取文件拓展名
* @param $name
* @return mixed
*/
public static function getExt($name)
{
return pathinfo($name, PATHINFO_EXTENSION);
}
/**
* 獲取惟一名稱
* @param $name
* @return mixed
*/
public static function getUniName()
{
return md5(uniqid(microtime(true), true));
}
}
複製代碼
7.對一些字段進行抽取和封裝
<?php
namespace file;
include 'File.php';
class Uploader{
private $files;
private $dir;
private $acceptType;
private $all;
private $maxSize;
private $msgs = [];
//getter setter方法....略...
public static $errorInfo = [
"上傳成功",
"超過 upload_max_filesize",
"超過max_file_uploads",
"只有部分上傳",
"沒有文件",
"文件類型不匹配",
"沒有找到臨時文件夾",
"文件寫入失敗",
"上傳被中斷",
"文件大小超出限制",
"文件不是經過POST上傳",
"文件移動失敗",
];
/**
* Uploader constructor.
* @param string $dir 文件夾
* @param array $acceptType 上傳類型
* @param bool $all 是否忽略類型
* @param float|int $maxSize 文件大小限制
*/
public function __construct(
$dir = "C:/Users/Administrator/upload/temp",
$acceptType = ["png", "jpg", "jpeg", "gif", "bmp"],
$all = false, //是否忽略類型,//文件大小
$maxSize = 2 * 1024 * 1024
){
$this->files = $_FILES;
$this->dir = $dir;
$this->acceptType = $acceptType;
$this->maxSize = $maxSize;
$this->all = $all;
}
public function uploadFile(){
$format = $this->format($this->files);
foreach ($format as $file) {
$res = $this->upload($file);
array_push($this->msgs, $res);
}
return $this->msgs;
}
private function upload($file){
$name = $file["name"];//上傳文件的名稱
$tempName = $file["tmp_name"];//臨時文件名
$size = $file["size"];//文件大小
$error = $file["error"];//錯誤
$ext = File::getExt($name);
$dest = $this->dir . File::getUniName() . "." . $ext;//輸出文件名
new File($dest);//文件夾不存在則建立文件夾
$msg["code"] = $error;
$msg["src"] = $name;
$msg["dest"] = $dest;
$msg['info'] = Uploader::$errorInfo[$error];
if ($file["error"] == UPLOAD_ERR_OK) {//1.成功
if ($size > $this->maxSize) {//2.文件大小限制
$msg["code"] = 9;
}
if (!in_array($ext, $this->acceptType) && !$this->all) {//3.文件類型匹配
$msg["code"] = 5;
}
if (!is_uploaded_file($tempName)) {//4.經過http post上傳
$msg["code"] = 10;
}
if (!move_uploaded_file($tempName, $dest)) {//拷貝到目標文件夾
$msg["code"] = 11;
}
}
$msg['info'] = Uploader::$errorInfo[$msg["code"]];
return $msg;
}
/** 格式化多文件上傳返回數據
* @param $files 文件信息
* @return mixed
*/
public function format($files){
$i = 0;
foreach ($files as $file) {
if (is_string($file['name'])) {//說明是二維數組
$result[$i] = $file;
$i++;
} elseif (is_array($file['name'])) {//說明是三維數組
foreach ($file['name'] as $k => $v) {
$result[$i]['name'] = $file['name'][$k];
$result[$i]['type'] = $file['type'][$k];
$result[$i]['tmp_name'] = $file['tmp_name'][$k];
$result[$i]['size'] = $file['size'][$k];
$result[$i]['error'] = $file['error'][$k];
$i++;
}
}
}
return $result;
}
}
複製代碼
<?php
use file\Uploader;
require "../lib/file/Uploader.php";
$uploader = new Uploader("G:/a/d/f/g");
$uploader->uploadFile();
複製代碼
OK ,第一次接觸PHP,感受還好吧,我的感受和python有點像,不少東西都是函數調用
而不是像Java,Kotlin等用對象的api來操做,因此感受函數多起來,挺亂的。
PHP和JavaScript怎麼說呢,感受側重點不一樣,誰好誰壞的說不清,各有千秋吧。
語言都相似,基本模塊都差很少,關鍵仍是看能不能玩轉起來,不吹不黑,PHP還不錯。
項目源碼 | 日期 | 附錄 |
---|---|---|
V0.1--無 | 2018-3-14 | 無 |
發佈名:
編程語言對比手冊(橫向版)[-PHP-]
捷文連接:juejin.im/post/5c8a19…
筆名 | 微信 | |
---|---|---|
張風捷特烈 | 1981462002 | zdl1994328 |
個人github:github.com/toly1994328
個人簡書:www.jianshu.com/u/e4e52c116…
個人簡書:www.jianshu.com/u/e4e52c116…
我的網站:www.toly1994.com
1----本文由張風捷特烈原創,轉載請註明
2----歡迎廣大編程愛好者共同交流
3----我的能力有限,若有不正之處歡迎你們批評指證,一定虛心改正
4----看到這裏,我在此感謝你的喜歡與支持