三月 2024
 123
45678910
11121314151617
18192021222324
25262728293031

彙整

教研中心研習:PHP 網頁程式設計(1060807-0808)

時間:106年8月7日-8月8日

主題:PHP 網頁程式設計

講師:莊政儀

教學網站:PHP基礎課程

課程講義:1060807_PHP基礎課程教學範例

開發環境與工具:

範例檔:

九九乘法表:

<table border="1">
<?php
for ($i=1; $i<=9; $i++) {
    echo "<tr>";
    for ($j=1; $j<=9; $j++) {
        echo "<td>$i * $j = " . ($i*$j) . "</td>";
    }
    echo "</tr>";
}
?>
</table>

計數器:

<?php
// opens countlog.txt to read the number of hits
$datei = fopen("countlog.txt","r");
$count = fgets($datei,1000);
fclose($datei);
$count=$count + 1;
echo "$count";
echo " hits";
echo "\n";
// opens countlog.txt to change new hit number
$datei = fopen("countlog.txt","w");
fwrite($datei, $count);
fclose($datei);
?>

終極密碼:

form.php (練習用)

<form action="" method="post">
    <input type="text" name="num1" value="111">
    <input type="text" name="num2" value="222">
    <input type="submit" name="ok" value="送出">
</form>
<?php
// !empty()
if (isset($_POST["num1"])) {
    echo $_POST["num1"];
}
if (isset($_POST["num2"])) {
    echo $_POST["num2"];
}
if (isset($_POST["ok"])) {
    echo $_POST["ok"];
}
?>

magic1.php

<?php
$answer=rand(2,98);
$min=1;
$max=99;
?>
<form action="magic2.php" method="post">
    請在 <?=$min?> 和 <?=$max?> 之間一數字
    <input type="text" name="num">
    <input type="hidden" name="min" value="<?=$min?>">
    <input type="hidden" name="max" value="<?=$max?>">
    <input type="hidden" name="answer" value="<?=$answer?>">
    <input type="submit" name="ok" value="送出">
</form>

magic2.php

<?php
$num = !empty($_POST["num"]) ? $_POST["num"] : 0;
$answer = $_POST["answer"];
$min = $_POST["min"];
$max = $_POST["max"];
$ok = false;

if ($num === $answer) {
    $ok = true;
}
elseif ($num > $answer)
    $max = $num;
else
    $min = $num;

if ($ok) {
    echo "猜中了!<br/>";
    echo "<a href='magic1.php'>再玩一次</a>";
}
else {
?>
<form action="magic2.php" method="post">
    請在 <?=$min?> 和 <?=$max?> 之間一數字
    <input type="text" name="num">
    <input type="hidden" name="min" value="<?=$min?>">
    <input type="hidden" name="max" value="<?=$max?>">
    <input type="hidden" name="answer" value="<?=$answer?>">
    <input type="submit" name="ok" value="送出">
</form>
<?php
}
?>

files.php : 更改 images 資料夾下的所有檔案的檔名

<?php
if ($handle = opendir('images')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $newfile = "abc0".substr($file,1);
            if (rename("images/".$file, "images/".$newfile))
                echo "$file → $newfile<br>";
        }
    }
    closedir($handle);
}
?>

Oracle VM VirtualBox 安裝:

目標:以virtualbox 安裝 ubuntu 17.04 系統,並且在ubuntu 下安裝 amp(lamp)

  • step1:下載已經作好系統的 ubuntu1704.ova
  • step2:安裝virtualbox
  • step3:安裝virtualbox ext-pack
  • step4:開啟virtualbox,在檔案/匯入應用裝置
  • step5:啟動ubuntu1704虛擬機
  • step6:登入系統,帳號密碼為teacher,ntpc

註:如果滑鼠鍵盤被困在虛擬機內,可按 host key離開,內鍵的host key 為右ctrl

目標:建立2個網卡,NAT 負責外部網路(可上網安裝軟體);僅限主機介面卡–和本地機的連線

  • step1:因要安裝虛擬機的網卡,請先將虛擬機關機
  • step2:<設定值/網路>,<介面卡1->NAT>,<介面卡2->僅限主機>
  • step3:虛擬機開機,並登入系統
  • step4:查虛擬機的 ip , 指令 ip addr
  • step5: 指令 sudo nano /etc/network/interfaces
    在下方輸入
    auto enp0s8
    iface enp0s8 inet dhcp
  • step6:指令 sudo service networking restart:重啟網路
  • step7:再查虛擬機的 ip , 指令 ip addr
  • step8:指令 ping 8.8.8.8:測試能否連線外網
  • step9:在本機操作,開啟cmder,
    指令 ping 虛擬機IP:測試能否連線虛擬機

註:如果<介面卡>請選[橋接介面卡],可以取得ip,用[橋接介面卡]會比上面 [NAT] + [僅限主機]的方式更方便,因為虛擬機和主機的ip 同網段,虛擬機的網路行為如真實機器一般

目標:安裝 amp(apache2,php7,mysql)

以下都在cmder 底下操作

  • step1:從本機以 ssh 登入虛擬機
    ssh teacher@虛擬機IP
  • step2 安裝 apache2
    sudo apt install apache2
  • step3 安裝 php7
    sudo apt install php php-cli
  • step4 安裝 mysql
    sudo apt install mysql-server mysql-client
  • step5 安裝 mysql 的管理程式 phpmyadmin
    sudo apt install phpmyadmin

目標:為方便上傳製作網頁,設定apache DocumentRoot 的位置到 /home/teacher 底下

  • mkdir wwwroot
  • sudo nano /etc/apache2/sites-available/000-default.conf
#DocumentRoot /var/www/html 本行前面加#
DocumentRoot /home/teacher/wwwroot
<Directory /home/teacher/wwwroot>
options Indexes FollowSymLinks MultiViews
AllowOverride None
Require all granted
</Directory>
  • sudo service apache2 restart

目標:安裝 moodle

  1. moodle 檔案全複製至/home/teacher/wwwroot 下
  2. 刪除 moodle 根目錄下的 config.php
  3. 使用 phpMyAdmin 建立 moodle3 資料庫,編碼 utf8mb4_unicode_ci
  4. mkdir /home/teacher/moodledata
    cdmod 777 /home/teacher/moodledata
  5. sudo apt install php-xmlrpc
    sudo apt install php-soap
    sudo apt install php-intl

目標:題庫匯入格式外掛程式

phpMyAdmin 安裝

moodle 安裝

moodle安裝教學影片

作業練習:

http://webnas.bhes.ntpc.edu.tw/chiubor/1060807_php/homework/

練習一:利用迴圈,將10張圖片顯示出來

<?php
if ($handle = opendir('images')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "<img src='images/$file'><br>";
        }
    }
    closedir($handle);
}
?>

利用練習一的檔案,只想顯示號碼是奇數(或偶數)的圖片

<?php
if ($handle = opendir('images')) {
    $i = 0;
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            if ($i % 2 === 0)
                echo "<img src='images/$file'><br>";
        }
        $i++;
    }
    closedir($handle);
}
?>

練習二:假設在 images 底下的圖片張數不清楚有幾張,請利用讀取檔案的方式,顯示全部的圖片

<?php
if ($handle = opendir('images')) {
    $fileArray = [];
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            array_push($fileArray, $file);
        }
    }
    closedir($handle);
    foreach ($fileArray as $file) {
        echo "<img src='images/$file' width=400><br>";
        echo "$file<br>";
    }
}
?>
  • 利用練習二的檔案,將圖片寛度設為200px,再將圖片排列,一排有三張,將全部的圖片顯示,並在圖片下顯示圖片名稱
<?php
if ($handle = opendir('images')) {
    $fileArray = [];
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            array_push($fileArray, $file);
        }
    }
    closedir($handle);

    echo "<table>";
    for ($i=0; $i<count($fileArray); $i++) {
        if ($i % 3 === 0) {
            if ($i > 0) echo "</tr>";
            echo "<tr>";
        }
        echo "<td><img src='images/$fileArray[$i]' width=200><br>";
        echo "$fileArray[$i]</td>";
    }
    echo "</table>";
}
?>
  • 進階練習:利用練習二的檔案,將圖片名稱由小到大(或由大到小),排列顯示
<?php
if ($handle = opendir('images')) {
    $fileArray = [];
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            array_push($fileArray, $file);
        }
    }
    closedir($handle);

    //升冪
    sort($fileArray);
    echo "<h2>由小排到大(升冪)</h2>";
    echo "<table>";
    for ($i=0; $i<count($fileArray); $i++) {
        if ($i % 3 === 0) {
            if ($i > 0) echo "</tr>";
            echo "<tr>";
        }
        echo "<td><img src='images/$fileArray[$i]' width=200><br>";
        echo "$fileArray[$i]</td>";
    }
    echo "</table>";

    //降冪
    rsort($fileArray);
    echo "<h2>由大排到小(降冪)</h2>";
    echo "<table>";
    for ($i=0; $i<count($fileArray); $i++) {
        if ($i % 3 === 0) {
            if ($i > 0) echo "</tr>";
            echo "<tr>";
        }
        echo "<td><img src='images/$fileArray[$i]' width=200><br>";
        echo "$fileArray[$i]</td>";
    }
    echo "</table>";
}
?>

練習三:分別將 images 底下的10張圖片取其中2張,存成 base64的格式到陣列中,另外產生名稱為 1 和2 的連結,點1會將陣列0的圖片顯示,點2會將陣列1的圖片顯示(註:陣列由0開始),請勿連結到 imges 底下的圖片

      這是圖片1的連結<a href='?img=1'>1</a>
      提示:在網址列  XXXXXX.php?img=1 ,在 php 內部 用$_GET['img'] 來取得變數的值
<?php
session_start();
if (!isset($_SESSION['images'])) {
    if ($handle = opendir('images')) {
        $fileArray = [];
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                array_push($fileArray, $file);
            }
        }
        closedir($handle);

        $count = count($fileArray);
        $images = [];
        $img_no = 2; //隨機選幾張圖
        for ($i=0; $i<$img_no; $i++) {
            while (in_array($file = $fileArray[rand(0, $count)], $images));
            $path = "images/$file";
            $type = pathinfo($path, PATHINFO_EXTENSION);
            $data = file_get_contents($path);
            $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
            Array_push($images, $base64);
        }
        $_SESSION['images'] = $images;
    }
}
for ($i=1; $i<=count($_SESSION['images']); $i++)
    echo "<a href='?img=$i'>圖片$i</a> ";
echo "<br>";
if (!empty($_GET['img']))
    echo "<img src='" . $_SESSION['images'][$_GET['img']-1] . "'><br>";
?> 

作業

  1. 用遞迴寫出兩個正整數的最大公因數(gcd)
    gcd(144,128) 得到 ? gcd (742469137,283209877)得到?
    gcd(144,128) = 16
    gcd (742469137,283209877) = 7654321

    <?php
    function gcd($x, $y){
        if ($x === 0) return $y;
        if ($y === 0) return $x;
        if ($x >= $y) return gcd($y, $x % $y);
        else return gcd($y % $x, $x);
    }
    ?>
    <h1>最大公因數</h1>
    <form action="" method="post">
        <input type="text" name="num1">
        <input type="text" name="num2">
        <input type="submit" name="ok" value="送出">
    </form>
    <?php
    $num1 = !empty($_POST['num1'])?$_POST['num1']:0;
    $num2 = !empty($_POST['num2'])?$_POST['num2']:0;
    
    if ($num1>0 and $num2>0)
        echo "gcd($num1,$num2) = ".gcd($num1, $num2);
    ?>
  2. 分別用for 迴圈,while 迴圈及遞迴寫出階乘計算
    並計算出10!=3628800

    <?php
    function fact($n){
        if ($n === 0 || $n === 1) return 1;
        else return $n*fact($n-1);
    }
    ?>
    <h1>階乘計算</h1>
    <form action="" method="post">
        <input type="text" name="num">
        <input type="submit" name="ok" value="送出">
    </form>
    <?php
    $num = !empty($_POST['num'])?$_POST['num']:'';
    if ($num === 0) echo "$num! = 1";
    elseif ($num > 0 && $num <= 170){
        //for 迴圈
        $sum = 1;
        for ($i=1; $i<=$num; $i++)
            $sum *= $i;
        echo "for 迴圈:$num! = $sum<br>";
    
        //while 迴圈
        $i = 1;
        $sum = 1;
        while($i<=$num){
            $sum *= $i;
            $i++;
        }
        echo "while 迴圈:$num! = $sum<br>";
    
        //遞迴
        echo "遞迴:$num! = ".fact($num)."<br>";
    }
    ?>

    (進階題:如何算出大數階乘?譬如300!?,提示:因數值很大,無法用實際的乘積來計算,建議用for 迴圈+對數,指數)

    <?php
    function fact($n){
        if ($n < 0) return -1;
        if ($n == 0 || $n == 1) return 1;
        $big[0] = 1;
        for ($i=2; $i<=$n; $i++){
            $carry = 0;
            $len = count($big);
            for ($j=0; $j<$len; $j++) {
                $total = $carry + $big[$j] * $i;
                if ($total > 0) {
                    $big[$j] = $total % 10;
                    $carry = ($total - $big[$j]) / 10;
                }
            }
            while($carry > 0){
                $len = count($big);
                $big[$len] = $carry % 10;
                $carry = ($carry - $big[$len]) / 10;
            }
        }
        return join("", array_reverse($big));
    }
    ?>
  3. 一元二次方程式 a*x^2+b*x+c=0(次方^符號是借用basic 的表示方式,無關php)
    分別給 係數 a,b,c,請算出x 的解,如為虛數,請在虛數i表示
    例 a=1,b=-3,c=2,得 x1=2,x2=1

    <?php
    function caculate($a, $b, $c){
        if ($a == 0) return null;
        $delta = $b*$b - 4*$a*$c;
        $delta2 = sqrt(abs($delta));
        $x=[];
        if ($delta < 0) {
            array_push($x,(-$b/(2*$a)).'+'.($delta2/(2*$a)).'i');
            array_push($x,(-$b/(2*$a)).'-'.($delta2/(2*$a)).'i');
        }
        else {
            array_push($x,(-$b+$delta2)/(2*$a));
            array_push($x,(-$b-$delta2)/(2*$a));
        }
        return $x;
    }
    ?>
    <h1>一元二次方程式求解</h1>
    <form action="" method="post">
        <input type="text" name="a"> x^2 +
        <input type="text" name="b"> x +
        <input type="text" name="c"> = 0
        <input type="submit" name="ok" value="送出">
    </form>
    <?php
    $a = !empty($_POST['a'])?$_POST['a']:0;
    $b = !empty($_POST['b'])?$_POST['b']:0;
    $c = !empty($_POST['c'])?$_POST['c']:0;
    if ($a != 0 && $b && $c) {
            $x = caculate($a, $b, $c);
            echo "x1 = $x[0]<br>";
            echo "x2 = $x[1]<br>";
    }
    ?>
  4. 費氏數列是很特別的數列,黃金比例男星,自然界中的費氏數
    請列出1000下內的費氏數列

    <?php
    function fibonacci($n){
        if ($n === 0) return 0;
        if ($n === 1) return 1;
        return fibonacci($n-1) + fibonacci($n-2);
    }
    ?>
    <h1>費氏數列</h1>
    <form action="" method="post">
        <input type="text" name="num">
        <input type="submit" name="ok" value="送出">
    </form>
    <?php
    $num = !empty($_POST['num'])?$_POST['num']:'';
    if ($num >= 0) {
        echo "0";
        for ($i=1; ($f = fibonacci($i)) <= $num; $i++){
            echo ",$f";
        }
    }
    ?>

學習資源:

教學影片:

PHP + MYSQL 教學影片

動態網頁設計 php 教學 mysql 資料庫

Comments are closed.