php筆記

$GLOBALS宣告為全域變數

假如你在函式內是一般$var的話,並不會跟函式外的數字產生響應。

var_dump()檢查型態
strlen()長度
strrev()翻轉
str_replace("replaced","replace","$var")//替換字體
str_word_count("Hello world!")//檢查有幾個字
strpos("Hello world!", "world")//第幾個字是被搜尋的字 由0開始
is_int() , is_integer , is_long() //回傳值是boolean
is_float() , is_double() //回傳值是boolean
is_finite() //回傳值是boolean 超過最大值被認定為false
is_infinite() //回傳值是boolean 超過最大值被認定為true
is_nan() //非number 非可執行運算 回傳null
is_numerical() //數字以及文字的數字都回傳true
intval() //轉型為int
pi() //圓周率 3.1415926535898
min() max() //最小值最大值
abs() //絕對值
sqrt() //平方根
round() //四捨五入
rand(x , y) //隨機從x~y的範圍內選一數字 沒給xy=不指定範圍



製造常數
define(name , value , case-insensitive)
name 名稱
value 值
case-insensitive 區分name的大小寫 預設為false(要區分)
php7 以後可以用define建立array

常數就算宣告在函式外,還是能用於函式內

$x ** $y //x的y次方 10 ** 3 = 1000
$x === $y //同樣的值 同樣的型態
php中 "100" == 100
但是 "100" 型態為String 並不是 number
!== 跟 ===相反

$x .= $y
echo $x //$x等於字串相加

陣列宣告
$x = array("a" => "xxx" , "b" => "yyy");
$y = array("c" => "zzz" , "d" => "ooo");
陣列相加 $x + $y
其餘通用於邏輯運算

邏輯判斷
$x = ex1 ? exT : exF //true 回傳 exT false 回傳 exF
$x = ex1 ?? ex2 //若ex1存在則ex1 否則 ex2

foreach($x as $y) //讀取$x的資料由$y輸出 跟一般的程式語法相反
foreach($x as $y => $val) //也可以讀取陣列


<?php declare(strict_types=1); //增加這條之後 型別要正確才能傳輸

表達式 /value/i //value內打文字 後面的i表示不區分大小寫
preg_match($value , $str) //找尋str內是否有value 有return 1
preg_match_all($value , $str) //找尋str內有幾個value
preg_replace($value , replace , $str)

$_SERVER["PHP_SELF"] 將提交的數據發送至頁面本身
htmlspecialchars() 防止駭客攻擊
避免駭客將html文檔輸入至表單以形成html或者javascript代碼

trim() 刪除不必要字符
stripslashes() 刪除\

filter_var($email , FILTER_VALIDATE_EMAIL) //驗證電子郵件
!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-p+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i" , $website)

date(time , now);
H-小時的24小時格式(00到23)
h-小時的12小時格式,前導零(01至12)
i-以零開頭的分鐘(00到59)
s-前導零的秒數(00至59)
a-小寫的前子午節和後子午節(上午或下午)

date("h:i:sa");
date_default_timezone_set("地區:國家");

echo "Created date is " . date("Y-m-d h:i:sa", 0); //Created date is 1970-01-01 12:00:01am

mktime(hour, minute, second, month, day, year)
echo "Created date is " . date("Y-m-d h:i:sa", $d); //Created date is hour, minute, second, month, day, year
strtotime(time , now);

require 跟 include 的差別
require 文件 只要少了那份文件就會直接喊停,include則不會
因此include可以喊一些不重要的文件,但是require則在喊一些重要的文件時用
require 'filename';

readfile("filename"); //讀取檔案

$varfile = fopen("filename" , "type") or die ("String");
fread($varfile , filesize("filename")); //讀取字串大小為filename的大小
fread(varfile , filesize);
type =
r read only , w write only , a write only if file not exist create ,  x create a new file,
r+ 從文件頭開始寫起, w+ 消除文件內容,如果檔案不存在則建立一個新檔案,然後可以寫可以讀,文件從開頭寫起 , a+ 文件現有內容保留,從尾端開始寫起,如果文件不存在則創建新文件 , x+ 創建新文件

fgets($varfile); //讀取第一行,讀取完之後point會跳到下一行
feof($varfile); //檢查文件結尾
while (!feof($varfile)) //直到文件結束為止
fgetc($varfile); //讀取單個字詞

$string = "xxx"
fwrite($varfile, string)

html表單 enctype = "multipart/form-data" 提交文件時使用的內容類別

$_FILES["varfile"]["name"] //上傳檔案名稱
$_FILES["varfile"]["type"] //上傳檔案類型
$_FILES["varfile"]["size"] //上傳檔案原始大小
$_FILES["varfile"]["tmp_name] //上傳檔案後資料夾位置
$_FILES["varfile"]["error"] //上傳檔案錯誤後錯誤代碼

basename("路徑" , "省略掉的東西"); //取得路徑最後的檔案的整體名稱
$path = Users/Administrator/Desktop/hhh.txt
$fs = pathinfo($path , "四個型別"); //為一個Array 含有dirname , basename , extension , filename
dirname = Users/Administrator/Desktop
basename = hhh.txt
extension = txt
filename = hhh
加入四個型別之後 輸出就為該型別
$fs = pathinfo($path , "basename"); // $fs = hhh.txt

$info = new SplFileInfo('Users/Administrator/Desktop/hhh.txt')
$fn = $info->getFilename(); //hhh.txt
$dir = $info->getPath(); //Users/Administrator/Desktop
$path = $info->getPathname(); //Users/Administrator/Desktop/hhh.txt

cookie 是用於識別用戶 
setcookie(name , value , expire , path , domain , secure , httponly)
僅name 是必須欄位
對於再次設定cookie只需要再次setcookie覆蓋過即可

$_COOKIE[$cookiename]
if (count($_COOKIE) > 0) //如果COOKIE一個以上,代表有COOKIE

session_start(); //session開始,要比任何的html還要更前面

接著所有有連線的都需要session_start()
便會共享值,儲存於$_SESSION[] 中

print_r($_SESSION); 顯示所有存於session 中的值,以array的型態
修改值直接overwrite過去
session_unset(); //刪除所有變數
session_destroy(); //刪除session

session以用戶密鑰當作認證,當你在另一個頁面開啟session時,會自動掃描密鑰,存在匹配項則訪問,不存在則啟動一個新的session

php Filers
Validating data = 驗證格式是否正確
Sanitizing data = 刪除任何非法字符





<?php
$x = 5;
$y = 10;

function myTest() {
  echo $x . "," . $y . "/r"; //output = "" , ""       "">是空的意思
  $y = $x + $y;
}

myTest();  // run function
echo $y; // output = 10
?>
--------------------------------------------next
<?php
$x = 5;
$y = 10;

function myTest() {
  $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; //這樣輸出為15
?>
--------------------------------------------next
<?php
function myTest() {
  static $x = 0; //靜態變數不會消失,會累加
  echo $x;
  $x++;
}

myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
--------------------------------------------next
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;

echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";

echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y . "<br>";
echo $txt1 . $txt2 //只有數字能相加 字串只能 . 
?>
--------------------------------------------next
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;

print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";

print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y . "<br>";
print $txt1 . $txt2;
?>
--------------------------------------------next
<?php  
$cars = array("Volvo","BMW","Toyota"); //陣列
var_dump($cars);
?>  
輸出結果 : 
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
--------------------------------------------next
<?php
class Car {
  function Car() {
    $this->model = "VW";
    $this->xx = "yy";
    echo var_dump($this) . "<br>"; //類似於map
  }
}
// create an object
$herbie = new Car();
echo var_dump($herbie)  . "<br>";
// show object properties
echo $herbie->model;
?>
輸出結果 : 
object(Car)#1 (2) { ["model"]=> string(2) "VW" ["xx"]=> string(2) "yy" }
object(Car)#1 (2) { ["model"]=> string(2) "VW" ["xx"]=> string(2) "yy" }
VW
--------------------------------------------next
<?php
echo str_word_count("Hello,World!") . "<br>";
echo str_word_count("Hello World!") . "<br>";
echo str_word_count("Hello!World!") . "<br>";
echo str_word_count("Hello.World!") . "<br>";
echo str_word_count("Hello/World!") . "<br>";
echo str_word_count("HelloWorld!") . "<br>";
?>
輸出結果 :
2
2
2
2
2
1
--------------------------------------------next
<?php
// Check if the variable is numeric 
$x = 5985;
var_dump(is_numeric($x));

echo "<br>";

$x = "5985";
var_dump(is_numeric($x));

echo "<br>";

$x = "59.85" + 100;
var_dump(is_numeric($x));

echo "<br>";

$x = "Hello";
var_dump(is_numeric($x));

echo "<br>";

$x = "0xf4c3b00c";
var_dump(is_numeric($x));

echo "<br>";

$x = 0xf4c3b00c;
var_dump(is_numeric($x));

?>
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(true)
--------------------------------------------next
<?php
// Cast float to int 
$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast;
  
echo "<br>";

// Cast string to int
$x = "23465.768";
$int_cast = (int)$x;
echo $int_cast;

echo "<br>";

$x = "23465.768";
$int_cast = intval($x);
echo $int_cast;
?>  
23465
23465
23465


--------------------------------------------next
<?php
echo(min(0, 150, 30, 20, -8, -200) . "<br>");
echo(max(0, 150, 30, 20, -8, -200));
?>
--------------------------------------------next
<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
  echo GREETING;
}
myTest();
?> 


--------------------------------------------next
<?php
function setHeight(int $minheight = 50) { //function可以預設參數
  echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); //50
setHeight(135);
setHeight(80);
?>
--------------------------------------------next
<?php declare(strict_types=1); // strict requirement
function addNumbers(int $a, int $b) : float { //可以改變回傳型態 感覺沒啥用
  return $a + $b;
}
var_dump(addNumbers(1, 5)); //float
echo addNumbers(1, 5); 
?>
--------------------------------------------next
if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
  }

Name: <
  <<?php<
  <<

當沒東西時跳回並輸出錯誤
--------------------------------------------next

<?php
$target_dir = "uploads/"; //設定路徑
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); //設定路徑
// basename($_FILES["fileToUpload"]["name"]) 抓取files["FileToUpload"]這個file的檔案名稱
$uploadOk = 1; //用於確認是否有上傳
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); //extension抓資料type 

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
  $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
  if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
  } else {
    echo "File is not an image.";
    $uploadOk = 0;
  }
}

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
  echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
  $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
  echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

--------------------------------------------next


























留言

這個網誌中的熱門文章

無法載入檔案或組件 'System.IO.Compression' 或其相依性的其中之一。

MongoDB 入門

DDD With MVC