PHP basics
PHP basics
2019/10/12 (更新內容)
2023/10/07 (補充內容)
2023/10/26 (補充內容)
開發環境
利用PHP開發web應用,需要Apache Web Server、資料庫(MySQL/MariaDB)、PHP,也有一些安裝包(如:AppServ、MAMP、XAMPP)將這些軟體包裝好,可以一次安裝好,不必一個一個的安裝。使用安裝包的時候要注意,每個安裝包所內含的軟體是不太一樣的,目前最大的差異在於使用MySQL或MariaDB,例如,XAMPP內含MariaDB,AppServ內含MySQL,WampServer則是MySQL及MariaDB,另外,還要注意的是支援的作業系統,AppServ及WampServer支援windows,XAMPP號稱跨平台,所以,支援Windows、Mac、Linux版本。不過,因為XAMPP後來支援MariaDB,很多的設定都跟MySQL不一樣,會有一些困擾。
在家使用Windows的同學,可以採用AppServ或XAMPP,目前資訊中心安裝的版本有AppServ及XAMPP。使用Mac的同學採用MAMP或XAMPP。
上資料庫課程時,老師會要求助教告訴大家直接安裝mysql,原因是要讓大家知道,如果不用AppServ或XAMPP,也可以使用mysql。我們可以下載免費的community server,目前最新版本是8.2.0。因為跟App Serv及XAMPP上的資料庫版本不一樣,使用時請注意。另外,可下載MySQL Workbench,目前最新版本是: 8.0.34。
安裝步驟請詳參:
WAMP (Windows, Apache, MySQL and PHP)
AppServ : Apache + PHP + MySQL (Release Date : 2019-09-29)
安裝時會要求設定mysql的密碼
AppServ 9.3.0
Apache 2.4.41
PHP 7.3.10
MySQL 8.0.17
phpMyAdmin 4.9.1
Support TLS,SSL or https
For 64bit only
XAMPP安裝與操作初步 (Windows、Mac、Linux)
XAMPP Apache + MariaDB + PHP + Perl
要自行設定mysql密碼
XAMPP 8.2.4, 8.1.17 and 8.0.28 (Release Date: 2023-04-08)
Apache 2.4.56
MariaDB 10.4.28
PHP 8.2.4, 8.1.17 or 8.0.28
phpMyAdmin 5.2.1
OpenSSL 1.1.1t
XAMPP Control Panel 3.2.4
Webalizer 2.23-04
Mercury Mail Transport System 4.63
FileZilla FTP Server 0.9.41
Tomcat 8.5.87 (with mod_proxy_ajp as connector)
Strawberry Perl 5.32.1.1 Portable
WAMPSERVER 64 BITS (X64) 3.17 (2019/08/19)
Wampserver 3.1.9 64 bit x64
Apache 2.4.37
PHP 5.6.40, 7.0.33, 7.1.26, 7,1.30, 7.2.19, 7.2.14, 7.3.1, 7.3.6
MySQL 5.7.24
MariaDB 10.3.12
PhpMyAdmin 4.8.4
Adminer 4.7.0
PhpSysInfo 3.2.10
MAMP (Macintosh, Apache, MySQL and PHP) (也支援windows)
![](https://www.google.com/images/icons/product/drive-32.png)
目前資訊中心的電腦教室及系機房所安裝的都是AppServ。
在資訊中心的電腦教室裡,由於一些管理上的需要,Apache及MySQL的服務是被停掉的,所以,必須手動開啟。
在資訊中心的電腦教室裡,預設php 5,如果用到php 7的語法,必須更換版本。
如果是安裝在自己家裡的電腦,就不需要這些動作了。
第一個PHP程式
以windows下的appserv為例,先找到appserv的安裝路徑 (如:c:\AppServ),在AppServ下有www的資料夾,請先在www下產生一個新的資料夾(如: web),在新資料夾中新增一個index.php
** 有些appserv版本預設不顯示錯誤,所以,要編輯php.ini,將
display_errors = Off
改為
display_errors = On
如果是使用windows下的xampp,先找到xampp的安裝路徑 (如:c:\xampp),在xampp下有htdocs的資料夾,請先產生一個新的資料夾(如: web),再新增一個index.php
<?php
echo "Hello";
?>
啟動Apache後,在瀏覽器上輸入:
http://localhost/web
Apache就會執行web資料夾下的index.php,所以,就可以看到
Hello
也可以找出電腦的ip,試著從另一台電腦(或手機)連上剛剛寫的網頁
** 如果看到「 localhost 拒絕連線」,通常是我們還沒啟動Apache。如果看到「 Error 404」,通常是檔案名稱錯誤或資料夾名稱錯誤。
基本語法與輸出
<?php ?>中間就是php的程式碼,echo 或 print就是印出內容的意思,所以,這程式會印出「My first PHP script!」(詳參: PHP 7 echo and print Statements)
<?php
echo "My first PHP script!";
?>
如果內容包含HTML,那就成了網頁了。php是以「.」來連接兩個字串,另外,php有一些內建的函數,如date。(詳參: PHP 7 Date and Time & PHP 7 Date/Time Functions & PHP 7 Calendar Functions)
<?php
echo "My first PHP script!";
echo "<p>";
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l") . "<br>";
echo "The time is " . date("h:i:sa"). "<br>";
?>
也可以寫成:
My first PHP script!<p>
Today is <?php echo date("Y/m/d") ?><br>
Today is <?php echo date("Y.m.d") ?><br>
Today is <?php echo date("Y-m-d") ?><br>
Today is <?php echo date("l") ?><br>
Today is <?php echo date("h:i:sa") ?><br>
php 5以後,可以利用<?= ?>,簡化<? php echo ?> (詳參: [鐵人賽Day12]PHP的簡寫標籤與使用方式 )。
My first PHP script!<p>
Today is <?= date("Y/m/d") ?><br>
Today is <?= date("Y.m.d") ?><br>
Today is <?= date("Y-m-d") ?><br>
Today is <?= date("l") ?><br>
Today is <?= date("h:i:sa") ?><br>
d - 代表日 (01 to 31)
m - 代表月 (01 to 12)
Y - 代表年 (四位數)
l (小寫 'L') - 星期幾
H - 以24小時方式表達時 (00 to 23)
h - 以24小時方式表達時 (01 to 12)
i - 代表分鐘 (00 to 59)
s - 代表秒 (00 to 59)
a - 小寫的上午或下午 (am or pm)
變數
PHP的變數使用方式跟python比較像,不需要設定變數的資料型態。跟python不同的是,PHP的變數名稱前要加上"$" (詳參: PHP 7 Variables & PHP 四種變數範圍比較:區域、全域、靜態、參數)。
<?php
$x = 2;
$y = 3;
echo $x + $y;
?>
跟python很像,同一個變數,在不同的時間可以儲存不同資料型態的內容。
<?php
$x = 'hello world';
echo $x;
$x = 1;
echo $x;
?>
這時候,數字相加跟字串相加的效果就不一樣了,而PHP會自動的轉換對應的資料型態,試試看以下的程式:
<?php
$x = 2;
$y = 3;
echo $x + $y;
echo "<br>";
echo $x . $y;
echo "<br>";
$x = "20";
$y = "30";
echo $x + $y;
echo "<br>";
echo $x . $y;
echo "<br>";
?>
也可以在字串裡直接放變數,可以省掉字串相加的麻煩,這也是PHP變數要加「$」的原因。
$txt = "PHP";
echo "I love ".$txt."!";
echo "I love $txt!";
php變數名稱的規則:
PHP的變數名稱前加上"$"
PHP的變數名稱開頭要是字母或底線(underscore),PHP的變數名稱開頭不能是數字
變數名稱只允許字母、數字或底線
變數名稱大小寫會被認為是不同的變數,例如:$age跟$AGE會是不同的變數
判斷式
PHP的判斷式跟java比較像 (詳參: PHP Operators),不過,源頭應該不是java,而是c語言,因為java與PHP的公開使用都是在1995年左右。
不過因為PHP變數的使用比java有彈性,所有會有"=="及"==="的差別
"=="會忽略變數類型
var_dump()就是把變數內容印出來
$x = 100;
$y = "100";
var_dump($x == $y); // 顯示bool(true)因為會忽略變數類型
"==="不會忽略變數類型
$x = 100;
$y = "100";
var_dump($x === $y); // 顯示bool(false)因為變數類型不同
if
php的if跟java的表示方法一樣。
php取亂數的方法是利用內建函數rand (詳參: rand / PHP rand() Function)
<?php
$r = rand(1,30);
if ($r < 20) {
echo "小於20";
}
else {
echo "大於20";
}
?>
switch
php的if跟java的表示方法一樣。
<?php
$r = rand(1,6);
switch ($r) {
case 1:
echo "扣五分";
break;
case 2:
echo "扣三分";
break;
case 3:
echo "扣一分";
break;
default:
echo "得三分";
}
?>
Ternary (? :)
這個語法在java及python也都有,如果問號前的條件為真,回傳冒號前的內容,否則,回傳冒號後的內容。
$statuslist = isset($_POST["status"])? $_POST["status"] : ["N/A"];
Null coalescing (??) (php 7的語法)
如果??前的內容存在且不是空值,則傳回??前的值,否則,傳回??後的值。(詳參: Null coalescing operator)
//new syntax in php 7
$statuslist = $_POST["status"]?? ["N/A"];
相當於
$statuslist = isset($_POST["status"])||!is_null($_POST["status"])? $_POST["status"]:["N/A"];
迴圈
PHP的迴圈跟java比較像。
while
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
for
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
迴圈結合table
<?php
echo "<table border='1'>";
for ($col = 0; $col < 10; $col++) {
echo "<tr>";
for ($row = 0; $row <10; $row ++){
echo "<td>".$row."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
也可以寫成,這種寫法對開發者來講很難看的懂,但是一般的語法檢查器(linter)比較能幫我們檢查語法:
<table border='1'>
<?php
for ($col = 0; $col < 10; $col++) {?>
<tr>
<?php
for ($row = 0; $row <10; $row ++){ ?>
<td><?=$row?></td>
<?php }?>
</tr>
<?php}?>
</table>
兩種寫法都是把HTML跟PHP混雜在一起,其實很容易眼花撩亂。尤其是寫好HTML之後,要把PHP的邏輯放進去之後,很容易就會跑版。或者是寫好PHP之後再去改HTML,就會讓PHP出現語法錯誤。
陣列
php的陣列表示方法跟java或python不太一樣,不過原理滿相似的。就跟python一樣,陣列裡的資料型態可以不同。PHP還有一種比較特別的陣列Associative Arrays(詳參:PHP 7 Arrays、PHP 7 Multidimensional Arrays)。
陣列也可以使用foreach,php的foreach其實在java與python都有類似的語法。
print_r() (也可以用var_dump()) 可以印出陣列的內容。
<?php
$customers = array( "Ben", "Mary", "Tom", "Nancy", "Peter");
foreach( $customers as $customer ) {
echo "Value is $customer <br />";
}
$customers[2] = "Sam";
$customers[9] = "Steven";
print_r ($customers);
echo "</br>";
foreach( $customers as $cus ) {
echo "Value is $cus <br />";
}
?>
陣列的寫法也可以寫成:
<?php
$customers = ["Ben", "Mary", "Tom", "Nancy", "Peter"];
foreach( $customers as $customer ) {
echo "Value is $customer <br />";
}
$customers[2] = "Sam";
$customers[9] = "Steven";
print_r ($customers);
echo "</br>";
foreach( $customers as $cus ) {
echo "Value is $cus <br />";
}
?>
結果會是:
Value is Ben
Value is Mary
Value is Tom
Value is Nancy
Value is Peter
Array ( [0] => Ben [1] => Mary [2] => Sam [3] => Nancy [4] => Peter [9] => Steven )
Value is Ben
Value is Mary
Value is Sam
Value is Nancy
Value is Peter
Value is Steven
Associative Arrays
<?php
$customers = array( "Ben"=>20, "Mary"=>30, "Tom"=>40, "Nancy"=>60, "Peter"=>50);
foreach( $customers as $customer ) {
echo "Value is $customer <br />";
}
$customers["Mary"] = 35;
$customers["Steven"] = 30;
print_r ($customers);
echo "</br>";
foreach( $customers as $cus ) {
echo "Value is $cus <br />";
}
?>
陣列的寫法也可以寫成:
<?php
$customers = ["Ben"=>20, "Mary"=>30, "Tom"=>40, "Nancy"=>60, "Peter"=>50];
foreach( $customers as $customer ) {
echo "Value is $customer <br />";
}
$customers["Mary"] = 35;
$customers["Steven"] = 30;
print_r ($customers);
echo "</br>";
foreach( $customers as $cus ) {
echo "Value is $cus <br />";
}
?>
結果會是:
Value is 20
Value is 30
Value is 40
Value is 60
Value is 50
Array ( [Ben] => 20 [Mary] => 35 [Tom] => 40 [Nancy] => 60 [Peter] => 50 [Steven] => 30 )
Value is 20
Value is 35
Value is 40
Value is 60
Value is 50
Value is 30
如果要同時列出key及value: (詳參: foreach)
<?php
$customers = array( "Ben"=>20, "Mary"=>30, "Tom"=>40, "Nancy"=>60, "Peter"=>50);
foreach( $customers as $name => $age ) {
echo "Name is $name and age is $age <br />";
}
?>
函數
php的函數語法混合了java及python的語法 (詳參: PHP 7 Functions),引數(argument)可以有預設值,在php7之後,引數可以設資料型態,並利用return回傳值。
<?php
function println($p="-----") {
echo $p."<br>";
}
println("hello"); // call the function
println("my name");
println();
println("is ben");
?>
參考資料
PHP 7
SPEED!
Type Declarations
Error Handling
New Operators
Easy User-land CSPRNG
開發環境
Top Code Editors and IDE for PHP Development of 2019
IDE
PHPStorm
NetBeans
Eclipse
Code Editor
Visual Studio Code
Learning HTML — should you use an editor?: Two good tools to shape your web pages
Brackets
Visual Studio Code
The chief difference between Brackets and VS Code (that’s what the cool kids call it) is that VS Code is designed to be a complete application development environment. That means you can start scratching out simple web pages today, and graduate to more advanced code-heavy projects in the future.
Sublime
Atom
Brackets
** 注意 ** 在學校使用時,會有無法取得php的問題,所以,沒辦法幫忙檢查php語法。要修改設定檔。利用Debug->Open Preferences File,會打開兩個檔案:defaultPreferences.json及brackets.json,defaultPreferences.json是供參考,不能修改的,要修改brackets.json。
brackets.json:
{
"brackets-eslint.gutterMarks": true,
"brackets-eslint.useLocalESLint": false,
"fonts.fontSize": "12px",
"fonts.fontFamily": "'SourceCodePro-Medium', MS ゴシック, 'MS Gothic', monospace",
"useTabChar": true,
"tabSize": 2,
"brackets-minifier.on-save": false,
"hirse.outline.enabled": true,
"linting.enabled": true,
"brackets-minimap.whatsnew": "3.2.6",
"php": {
"enablePhpTooling": true,
"executablePath": "C:\\AppServ\\php7\\php.exe",
"memoryLimit": "4095M",
"validateOnType": "false"
}
}
也可以在專案目錄下建立.brackets.json,這些設定就只適用在這個專案。(詳參: Preferences)
Learning HTML — should you use an editor?: Two good tools to shape your web pages
Brackets
Visual Studio Code
熱門的插件 (Extension / Plug-in) (根據2019/09/15的下載次數排序)
Emmet (1,568,322)
Beautify (1,347,655) ** 推薦 **
幫我們排版程式,增加程式可讀性
Brackets Git (517,394) ** 推薦 **
Brackets Icon (504,627)
Autoprefixer (437,525)
Themes for Brackets (305,160)
PHP Syntax Hint (289,088)
JSHint (263,802)
HTML Skeleton (212,621)
Extensions Rating (146,322)
CSSLint (139,824)
Todo (131,132)
JS CSS Minifier (117,840)
Interactive Linter (91,444) ** 推薦 **
檢查語法錯誤 (Javascript、CSS、html....)
Brackets已經內建lint但是沒有Javascript、CSS、html....
12 Brackets Extensions That Will Make Your Life Easier
CanIUse
Quickly see the current level of browser support a certain web technology has without leaving Brackets.
HTML Skeleton
HTML Skeleton helps you set up your HTML files quickly by automatically inserting basic markup such as the doctype declaration, <html>, <head>, <body>, etc.
HTML Wrapper
Rapidly mark up a list of text into list items (<li>), table rows (<tr>), hyperlinks, (<a>), and more with HTML Wrapper.
Brackets Icons
This is a super simple extension that adds file icons in Brackets’s sidebar. The icons are excellent visual cues that make it much easier to identify the file you’d like to work on.
Autoprefixer
Automatically and intelligently add vendor prefixes to your CSS properties with the Autoprefixer extension
JS CSS Minifier
This extension will remove unneeded characters from your JavaScript and CSS files. This process is called minification, and it can improve your website’s speed.
CSSLint
This extension highlights CSS errors and code-quality issues. The errors and warnings reported by this extension are based on CSS Lint rules.
Emmet
Emmet is a collection of tools and keyboard shortcuts that can speed up HTML- and CSS-authoring.
Lorem Ipsum Generator
The Lorem Ipsum Generator extension helps you conveniently generate dummy text. (And if you need image placeholders, have a look at Lorem Pixel or DEVimg.)
Beautify
This extension will help keep your HTML, CSS, and JavaScript code consistently formatted, indented, and — most importantly — readable. An alternative option to check out is the CSSComb extension.
Simple To-Do
Make sure you don’t forget your project tasks by using the Simple To-Do extension, which allows you to create and manage to-do lists for each project within Brackets.
eqFTP
Transferring and syncing your project’s files to your web host or server requires FTP or SFTP, but such a fundamental web development feature doesn’t come with Brackets.
25 of the Useful and Best Brackets Extensions (2019)
Beautify
Beautify Brackets extension makes your code look good. Not only does it make your files more readable, but it also gives you a handy shortcut key to beautify those files — CMD-Shift-L (Mac) and Ctrl-Shift-L (Win). JavaScript code can be consistently formatted and made more readable using Beautify.
Autoprefixer
Autoprefixer is a postprocessor for dealing with vendor prefixes in the best possible way. Autoprefixer parses CSS files and adds vendor prefixes to CSS rules.
Emmet
Emmet helps improve your HTML and CSS workflow by letting you type in CSS-like expressions that can be dynamically parsed and produce an output according to what you actually typed in the abbreviation.
Minifier
Minifier minifies JavaScript and CSS files in brackets and saves them as filename.min.ext
ToDo
ToDo is Brackets extension that displays all To-Do comments in the current document or project. By default, it supports five tags — TODO, NOTE, FIXME, CHANGES and FUTURE. To keep track of your team’s progress, you may mark tasks as done.
Bracket Gits
Bracket Gits is an extension for Brackets editor that provides Git integration for Brackets. It is tested and works on any platform supported by Brackets (Windows, Mac OS X, and GNU/Linux). Bracket Git is easily the best among similar Brackets extensions as it lets you easily commit changes from Brackets itself, as well as push and pull changes with a single click.
Brackets File Icons
Brackets File Icons adds file icons to the Brackets file tree. It supports files like JavaScript, HTML, JSON, XML, CSS, PNG, and JPG. You can spice up your code editor with file icons by adding colors to your icons based on your file type to all files listed in your side bar. You can also post icon requests on the GitHub page.
Swatcher
Swatcher generates code hints and color palettes by importing via LESS/SASS files, images or Adobe Swatch files. It supports all color related functions, such as rgba().
Lorem Pixel
Lorem Pixel is a Brackets extension that can be used to generate placeholder images.
eqFTP
eqFTP is an FTP/SFTP client for Brackets code editor.
Code Folding (已內建)
Code Folding Brackets extension provides simple code folding for files edited in Brackets.
Color Picker
Color Picker appears to be handy if you are working with CSS files.
Extension rating
Brackets Extension Rating can be used to display other extensions’ statistics based on downloads and GitHub stats. It shows online and maximum users counters for selected extensions, and displays star and forks counter from the GitHub repository.
Interactive Linter
Interactive Linter integrates with linters such as JSHint, JSLint, ESlint, JSCS, CoffeeLint, and more.
15 Best Brackets Extensions For A Smooth Coding Experience (2017)
Top 10 PHP Development Tools That Every Developer Have To Know
Eclipse
NetBeans
PHPStorm
NUSphere
Zend Studio
Sublime Text
Komodo
Aptana Studio
PHPDesigner
Codelobster
10 Best PHP Development Tools That Every Developer Must Explore
PHPStorm
Eclipse PDT
NetBeans
Sublime Text 3
NuSphere
Zend Studio
Atom
Komodo
Aptana Studio
Cloud 9
Cloud IDE
PHP Sandbox (onlinephpfunctions.com)
Online PHP Sandbox (wtools.io)
Cloud IDEs For Web Developers – Best Of (2018)
Cloud 9 (PHP)
Codeanywhere (PHP)
Sourcekit (PHP)
Kodingen (PHP)
ShiftEdit (PHP)
Top 10+ Best Cloud IDE For The Developers
Cloud 9 (PHP)
AWS Cloud9 is one of the best cloud IDE of the world. It is a cloud-based Ide which allows you to code, run and debug your source code using a simple browser. AWS includes the debugger, code editor and terminal. Cloud9 packed with important tools for common programming languages, containing PHP, JavaScript, Python, and more.
Codeanywhere (PHP)
Codeanywhere Cloud IDE is a cloud-based integrated development environment. This is one of the best IDE Software according to user review.
Koding (PHP)
Koding is one of the best Cloud IDE software. It let you create and share a fully automated development environment. The developers get an interface to streamline development workflow from Koding.
SourceLair (PHP)
Sourcelair is another wonderful cloud integrated development environment. It has a frictionless development facility in your browser. Sourcelair develops software from any device using PHP, HTML5, Python, Node.js and more.
Eclipse Next-Generation (PHP)
Eclipse Next-Generation cloud IDE is a developer workspace server for team and organization.
Repl.it (PHP)
Repl.it IDE Platform is an online IDE where it needs only 2 seconds to boot up an environment for the programming language. When a program runs on it, then it opens a port.
The Ultimate Guide to Deploying PHP Apps in the Cloud
Heroku
Google Cloud
IBM BlueMix
Microsoft Azure
Amazon Web Services