PHP 語法入門


Posted by Nicolakacha on 2020-09-06

語法基礎

變數宣告 variable & const

以字母或底線開頭
-只允許字母、數字和底線
有分大小寫

<?php
    $a = 'apple';
  $b = 'banana';
    echo $a;

    **// const 宣告**
    define('GREETING', 'Hello Everyone');
    echo GREETING;
?>

字串

**// 字串相接用點點**
echo $a . $b; //apple banana
echo "$a $b";  //apple banana

**// 用 \ 來跳脫**
$string = "They\"re Here";

**// if ... else**
$score = 5;
if ($score >= 60) {
  echo "pass";
} else {
  echo "fail";
}

常用的字串 Functions

subsrt() //回傳切片的 string

$output = substr('Hello', 1, 3);
echo $output; // ell

$output = substr('Hello', -2);
echo $output; // lo

strlen() // 回傳字串長度

$output = strlen('Hello World');
echo $output; // 11

strpos // 找到第一個出現的位置

$output = strpos('Hello World', 'o');
echo $output; // 4

$output = strrpos('Hello World', 'o');
echo $output; // 7

trim() // 去掉空白

$output = trim('Hello World    ';
echo $output; // Hello World

strolower() //全部變小寫 ;
stroupper() //全部變大寫 ;
ucwords() // 字首變大寫 ;
str_replace() // 替換

$text = 'Hello World';
$output = str_replace('Word', 'Everyone', $text);
echo $output; // Hello Everyone

is_string() // 檢查是不是字串

$val = '22';
$output = is_string($val);
echo $output;  //1

陣列

Indexed 特性

$arr = array(1, 2, 3, 4, 'a'); //建立陣列
$car = ['Honda', 'Toyota', 'Ford']; //建立陣列的另一種方法
$car[3] = 'Chevy'; //插入項目
$car[] = 'BMW'; //如果不知道 index,可使用此方法插入項目

echo $arr[0]; // 印出第一個
echo count($cars); //印出 $car 的長度
echo "length:" . sizeof($arr);  // arr的長度
echo $arr[sizeof($arr) -1]; //最後一個項目
print_r($cars) // **印出** $cars ****的資料結構
var_dump($arr) // **印出更詳細的** $cars ****的資料結構

Associative (有 key 和 value 的特性)

<?php
    // Associative Array with key and value
    $people = array('Brad' => 35, 'Jose' => 32, 'William' => 37);
    $ids = [22 => 'Brad', 44 => 'Jose', 63 => 'William'];
    echo $people['Brad']; //35
    echo $ids[22]; //Brad

    $people['Jill'] = 42;
    echo $people['Jiil'] //42
?>

Multi-dimensional (可多層)

$cars = array(
    array('Honda', 20, 10);
    array('Toyota', 30, 10);
    array('Ford', 23, 12);
)
echo $car[1][0];

迴圈

For

for ($i = 1; $i <= 10; $i++) {
  echo "<br/>" . $i;
}

While

while($i < 10) {
    echo $i;
    $i++;
}

Do While

do {
    echo $i;
    echo '<br>'
    $i++;
}
while ($i < 10);

Foreach

$people = array('Brad' => 35, 'Jose' => 32, 'William' => 37);

foreach($people as $person){
    echo $person;
}

$people = array('Brad' => 'brad@gmail.com', 'Jose' => 'Jose@gmail.com', 'William' => 'William@gmail.com');

foreach($people as $person => $email){
    echo $person.': '.$email;
    echo '<br>';
}

gzcompress()

$compressed = gzcompress($string);
echo $compressed; //壓縮

$original = gzuncompress($compressed);
eecho $origin; //解壓縮

函式

基本用法

function add($a, $b) {
  echo $a + $b;
}
add(1, 3);

//自帶參數
function sayHello($name = 'World') {
  echo "Hello ${name}<br>";
}

//return
function add($a, $b) {
  return $a + $b;
}
echo add(1, 3);

PHP 預設是 Pass by value,需要 Pass by reference 時要用 &

$myNum = 10;

//Pass by value (default)
function addFive($num) {
    $num += 5;
}

addFive($myNum);  
echo $myNum; //10

function addTen(&$num) { 
    $num += 10;
}

addTen($myNum);
echo $myNum; //20

日期與時間

echo date('d'); //DAY
echo date('m'); //Month
echo date('Y'); //Year
echo date('l'); //Day of the week

echo date('Y/m/d');
echo date('Y-m-d');

echo date('h'); //hour
echo date('i'); //min
echo date('s'); //sec
echo date('a'); //am or pm
echo date('h:i:sa');
//Set time zone
date_default_timezone_set('Asia/China');

$timestamp = mktime(10, 14, 54, 9, 10, 1981);
echo date('m/d/Y h:i:sa', $timestamp);

//string to time
$timestamp2 = strtotime('7:00pm March 22 2020');
$timestamp3 = strtotime('tomorrow');
$timestamp4 = strtotime('next Sunday');
$timestamp5 = strtotime('+2 months');
echo $timestamp2;
echo date('m/d/Y h:i:sa', $timestamp2);

Include & Require

在 php 檔案引入另一個 php 檔案

include

include
include_once
<?php include 'header.php'; ?>

require

require
require_once
<?php require 'header.php'; ?>
//如果該檔案不存在,引入到的檔案也會一起錯誤

超全域變數 Super Global Variable

//Create Server Array
$server = [
    'Host Server Name' => $_SERVER['SERVER_NAME'],  //localhost
    'Host Header' => $_SERVER['HTTP_HOST'], //localhost
    'Server Software' => $_SERVER['SERVER_SOFTWARE']. //Apache
    'Document Root' => $_SERVER['DOCUMENT_ROOT'], //C/xampp/htdocs
    'Current Page' => $_SERVER['PHP_SELF'],
    'Script Name' => $_SERVER['SCRIPT_NAME']
    'Absolute Path' => $_SERVER['SCRIPT_FILENAME']
];

// Create Client Array
$client = [
    'Client System info' => $_SERVER['HTTP_USER_AGENT'], //browers you are using
    'Client IP' => $_SERVER['REMOTE_ADDR'], //return user's IP address
    'Remote Port' => $_SERVER['REMOTE_PORT'], //62794
]

GET & POST

$_GET

送出的結果會直接顯示在網址列上

XSS attack issue
當 input 輸入可被解析的語法時,會被解析出來,例如 <script> 等等,
為了確保輸入的都是字串,可使用 htmlentities 來防止 cross-site scripting XSS 攻擊
$name = htmlentities($_GET['name'])

$_POST

資料不會直接顯示出來在網址列上

$_REQUEST

不論 form 的方法是 POST 或 GET 都可以拿到資料

$_SERVER['QUERY_STRING']

可以拿到資料的完整字串

三元運算子

echo ($loggedIn) ? 'You are logged in' : 'You are not logged in';

偷吃步

<div>
<?php if($loggedIn) { ?>
    <h1>Welcome User</h1>
<?php } else { ?>
    <h1>Welcome Guest</h1>
<?php } ?>
</div>

<div>
<?php if($loggedIn): ?>
    <h1>Welcome User</h1>
<?php else: ?>
    <h1>Welcome Guest</h1>
<?php endif; ?>
</div>

<div>
    <?php foreach($arr as $val): ?>
        <?php echo $val; ?>
    <?php endforeach; ?>
</div>

<div>
<?php for($i = 0;$i < 10;$i++): ?>
    <li><?php echo $i; ?></li>
<?php endfor; ?>
</div>

Filter 相關 Functions

filter_has_var()

檢查 POST data 是否存在

// Check for posted data
<?php
    if(filter_has_var(INPUT_POST, 'data')){
        echo 'Data Found';
    } else {
        echo 'No Data';
    }
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="data">
    <button type="submit">Submit</button>
</form>

filter_var()

搭配 FILTER_VALIDATE_EMAIL 檢查 email 是否有效加入,搭配 FILTER_SANITIZE_EMAIL 可以把不合法的字移除:

<?php
if(filter_has_var(INPUT_POST, 'data')){
        $email = $_POST['data'];
        // Remove illegal chars
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        echo $email.'<br>';

        if(filter_var($email, FILTER_VALIDATE_EMAIL)){
            echo 'Email is valid';
        } else {
            echo 'Email is NOT valid';
        }
    }
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="data">
    <button type="submit">Submit</button>
</form>

排除特殊字元

$var = '<script>alert(1)</script>';
//echo $var;
echo filter_var($var, FILTER_SANITIZE_SPECIAL_CHARS);

其他可搭配 filter_var() 的 filter 參數

filter_input_array 利用陣列建立一組過濾器

範例一

  1. 首先檢查 data 是否是 email
  2. 再檢查 data 是否是數字,檢查此數字是否介於 1 ~ 100
    ```php
    <?php
    $filters = array(

     "data" => FILTER_VALIDATE_EMAIL,
     "data2" => array(
         "filter" => FILTER_VALIDATE_INT,
         "options" => array(
             "min_range" => 1,
             "max_range" => 100
         )
     )
    

    );

    print_r(filter_input_array(INPUT_POST, $filters));

?>

Submit


範例二
1. 利用 FILTER_CALLBACK 把  ucwords 這個 function 運用在 name 上面
2. 過濾 age 是不是 1~120 之間的數字
3. 檢查 email 的有效性
```php
<?php
$filters = array(
        "name" => array(
            "filter" => FILTER_CALLBACK,
            "options" => "ucwords"
        ),
        "age" => array(
            "filter" => FILTER_VALIDATE_INT,
            "options" => array(
                "min_range" => 1,
                "max_range" => 120
            )
        ),
        "email" => FILTER_VALIDATE_EMAIL
    );

    print_r(filter_var_array($arr, $filters));

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="data">
    <input type="text" name="data2">
    <button type="submit">Submit</button>
</form>

檔案相關 Functions

basename($path) // 回傳檔案名稱
basename($path, '.php') // 回傳無副檔名的檔案名稱
dirname($path) // 回傳檔案路徑
file_exist($file) // 檢查同路徑下某檔案是否存在
realpath($path) // 檔案的絕對路徑
is_file($file) // 檢查同路徑下某檔案是否存在,但如果是資料夾會回傳 0
is_writable($file) // 檢查檔案是否可寫
is_readable($file) // 檢查檔案是否可讀
filesize($file) // 檔案大小的 bytes
mkdir('testing') // 創建資料夾
rmdir('testing) // 如果資料夾為空則移除
copy('A.txt', 'B.txt') // 複製 A 檔案,新增 B 檔案
rename('A.txt', 'A_new.txt') // 更名,第一個參數為原檔名,第二個參數為新改的檔名
unlink('myfile.txt') // 刪除檔案
file_get_contents($file) // 回傳檔案內的字串
file_put_contents($file, 'hehe') // 在檔案裡新增字串,要注意的是,此函式的回傳值是檔案大小
fopen($file, 'r') // 開啟檔案
第一個參數是檔案位置,第二個參數是要怎麼打開,常見有下列幾種:

  • r // 只讀方式打開
  • w // 寫入方式打開

fread($handle, filesize($file)) 讀取檔案,第一個參數是要打開的檔案,第二個參數為最大字節數

fwrite($handle, $txt) 寫入檔案,實作範例如下

範例:

//Open for reading
$handle = fopen($file, 'r'); // r 代表 read
$data = fread($handle, filesize($file));
echo $data;

// Open for writing
$handle = fopen('file2.txt', 'w');
$txt = 'hello world';
fwrite($handle, $txt);
fclose($handle);

#PHP







Related Posts

How to solve the perpetual loading issue in Evernote? Evernote 一直轉圈圈的解決辦法

How to solve the perpetual loading issue in Evernote? Evernote 一直轉圈圈的解決辦法

關於 JavaScript 的提升 (Hoisting)

關於 JavaScript 的提升 (Hoisting)

# 2021 review

# 2021 review


Comments