Web程序設計(微課版)-實訓參考答案_第1頁
Web程序設計(微課版)-實訓參考答案_第2頁
Web程序設計(微課版)-實訓參考答案_第3頁
Web程序設計(微課版)-實訓參考答案_第4頁
Web程序設計(微課版)-實訓參考答案_第5頁
已閱讀5頁,還剩66頁未讀 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

第1章Web應用程序概述參考答案:1.簡單HTML頁面示例<html><head>

<title>我的第一個HTML頁面</title>

<metacharset="UTF-8"></head><body>

<h1>歡迎來到我的網站</h1>

<p>這是一個簡單的HTML頁面示例。</p>

<ul><li>列表項1</li><li>列表項2</li><li>列表項3</li>

</ul>

<ahref="">單擊這里訪問示例網站</a></body></html>程序運行結果如圖1-1所示。圖1-1簡單頁面示例2.中國企業調研示例<!DOCTYPEhtml><htmllang="zh-CN"><head><metacharset="UTF-8"><title>中國科技企業調研</title><style>body{font-family:"MicrosoftYaHei",sans-serif;line-height:1.6;}header{background-color:#f8f9fa;padding:20px;text-align:center;}.company{border:1pxsolid#ddd;margin:15px;padding:15px;border-radius:5px;}</style></head><body><header><h1>國內知名科技企業</h1><p>探索中國科技創新力量</p></header><section><divclass="company"><h2>華為技術有限公司</h2><p>成立時間:1987年|總部:深圳</p><ul><li>全球領先的ICT基礎設施和智能終端提供商</li><li>2022年研發投入達1615億人民幣</li></ul><ahref=""target="_blank">訪問官網</a></div><divclass="company"><h2>阿里巴巴集團</h2><p>成立時間:1999年|總部:杭州</p><ol><li>全球最大的電子商務平臺之一</li><li>云計算市場份額亞太第一</li></ol><ahref=""target="_blank"><imgsrc="alibaba-logo.png"alt="阿里巴巴Logo"width="100"></a></div></section><footer><p>?2023Web技術課程|數據來源:各企業年報</p></footer></body></html>程序運行結果如圖1-2所示。圖1-2企業調研

第2章Web開發環境搭建參考答案:參考教材p22-p241.AppServ集成環境安裝AppServ是一個集成了Apache、PHP、MySQL等軟件的開發環境,其安裝步驟如下。(1)下載AppServ安裝文件。在AppServ的官方網站下載AppServ安裝文件。(2)打開下載好的安裝文件,雙擊AppServ應用程序,出現圖2-1所示的安裝界面,然后單擊“Next”按鈕。圖2-1安裝界面(3)在接下來的界面中選擇需要安裝的組件。通常,為了能在以后的學習中使用ApacheHTTPServer、phpMyAdmin、MySQLDatabase等服務,建議全部選中并安裝這些服務。軟件默認是全部選中的。然后單擊“Next”按鈕,如圖2-2所示。圖2-2選擇組件(4)填寫HTTP服務器的地址和端口。地址一般填寫為或者localhost,這是計算機網絡的本地回環地址。端口填寫為8080。同時,還需要填寫管理員的電子郵箱地址。填寫完成后單擊“Next”按鈕,如圖2-3所示。圖2-3填寫地址和端口(5)設置MySQL數據庫的參數,包括為管理員用戶root設置密碼和設置MySQL服務器的字符集,單擊“Install”按鈕開始安裝,如圖2-4所示。圖2-4設置MySQL數據庫的參數系統會默認開啟Apache和MySQL服務,單擊“Finish”按鈕即可完成安裝,如圖2-5所示。圖2-5完成安裝環境測試:(1)PHP環境測試。在任意瀏覽器中輸入“localhost:8080”(此處端口為自己在安裝過程中設置的端口)。如果出現圖2-6所示的頁面,說明PHP已經安裝成功。在此處可以查看PHP及MySQL版本等信息。(2)phpMyAdmin可視化界面測試。在圖2-6所示頁面中單擊“phpMyAdminDatabaseManagerVersion4.9.1”超鏈接,進入MySQL可視化登錄頁面,如圖2-7所示。圖2-6PHP安裝測試成功頁面圖2-7MySQL可視化登錄頁面(3)輸入安裝時設置的用戶名與密碼,默認用戶名為root(不區分大小寫)。(4)單擊“執行”按鈕,可以看到phpMyAdmin可視化頁面,如圖2-8所示,說明MySQL安裝成功。圖2-8phpMyAdmin可視化頁面編寫第一個PHP程序:將通過SublimeText編輯器進行PHP程序的開發與運行。(1)打開SublimeText編輯器,選擇“文件>新建”,輸入程序源代碼,如圖2-9所示。圖2-9在SublimeText編輯器中輸入源代碼(2)保存文件,此處保存在D:\AppServ\www下,并將文件命名為diyige.php。源代碼如下。<html><head><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><title>第一個PHP程序</title></head><body><?php

echo"這是我的第一個PHP程序<br>";//輸出“這是我的第一個PHP程序”?></body></html>(3)打開任意瀏覽器并輸入“localhost:8080/diyige.php”,按Enter鍵,程序運行結果如圖2-10所示。圖2-10第一個PHP程序運行結果

第3章PHP基礎語法參考答案:1.計算器程序<?php//定義常量define("CALC_TITLE","PHP計算器");//處理表單提交$result="";if($_SERVER["REQUEST_METHOD"]=="POST"){$num1=$_POST['num1'];$num2=$_POST['num2'];$operator=$_POST['operator'];//驗證輸入if(is_numeric($num1)&&is_numeric($num2)){switch($operator){case'+':$result=$num1+$num2;break;case'-':$result=$num1-$num2;break;case'*':$result=$num1*$num2;break;case'/':$result=($num2!=0)?$num1/$num2:"除數不能為0";break;default:$result="無效運算符";}}else{$result="請輸入有效數字";}}?><!DOCTYPEhtml><html><head><title><?=CALC_TITLE?></title><style>.calculator{width:300px;margin:20pxauto;padding:20px;border:1pxsolid#ddd;border-radius:5px;}input,select,button{margin:5px0;padding:8px;width:100%;}</style></head><body><divclass="calculator"><h2><?=CALC_TITLE?></h2><formmethod="post"><inputtype="number"name="num1"requiredplaceholder="第一個數字"><selectname="operator"required><optionvalue="+">加(+)</option><optionvalue="-">減(-)</option><optionvalue="*">乘(*)</option><optionvalue="/">除(/)</option></select><inputtype="number"name="num2"requiredplaceholder="第二個數字"><buttontype="submit">計算</button></form><?phpif($result!==""):?><h3>結果:<?=$result?></h3><?phpendif;?></div></body></html>運行結果如圖3-1所示:圖3-1計算器運行結果2.學生成績輸出程序<?php//定義常量define("SCHOOL_NAME","信息學院");define("PASS_SCORE",60);//學生數據$students=[["name"=>"張三","math"=>85,"english"=>78,"php"=>92],["name"=>"李四","math"=>62,"english"=>58,"php"=>75],["name"=>"王五","math"=>45,"english"=>67,"php"=>82]];//計算總分和平均分foreach($studentsas&$student){$student['total']=$student['math']+$student['english']+$student['php'];$student['average']=round($student['total']/3,2);$student['pass']=$student['average']>=PASS_SCORE;}unset($student);//斷開引用?><!DOCTYPEhtml><html><head><title><?=SCHOOL_NAME?>成績單</title><style>table{width:80%;margin:20pxauto;border-collapse:collapse;}th,td{border:1pxsolid#ddd;padding:8px;text-align:center;}th{background-color:#f2f2f2;}.pass{color:green;}.fail{color:red;}</style></head><body><h1style="text-align:center;"><?=SCHOOL_NAME?>學生成績報告</h1><table><thead><tr><th>姓名</th><th>數學</th><th>英語</th><th>PHP</th><th>總分</th><th>平均分</th><th>狀態</th></tr></thead><tbody><?phpforeach($studentsas$student):?><tr><td><?=$student['name']?></td><td><?=$student['math']?></td><td><?=$student['english']?></td><td><?=$student['php']?></td><td><?=$student['total']?></td><td><?=$student['average']?></td><tdclass="<?=$student['pass']?'pass':'fail'?>"><?=$student['pass']?'及格':'不及格'?></td></tr><?phpendforeach;?></tbody></table><?php//統計信息$total=count($students);$pass=array_reduce($students,function($carry,$item){return$carry+($item['pass']?1:0);},0);$pass_rate=round(($pass/$total)*100,2);?><divstyle="width:80%;margin:0auto;"><h3>班級統計:</h3><p>總人數:<?=$total?></p><p>及格人數:<?=$pass?></p><p>不及格人數:<?=$total-$pass?></p><p>及格率:<?=$pass_rate?>%</p></div></body></html>運行結果如圖3-2所示。圖3-2學生成績運行結果

流程控制語句參考答案1.網頁每日問候語<?php//獲取當前時間的小時數$hour=date('H');//根據時間顯示不同的問候語if($hour<12){$greeting="早上好!";}elseif($hour<18){$greeting="下午好!";}else{$greeting="晚上好!";}//顯示問候語echo"<h1>$greeting</h1>";echo"<p>現在是北京時間".date('Y年m月d日H:i:s')."</p>";?>程序運行結果如圖4-1所示。圖4-1問候語示例2.單選多項選擇題網頁<?php//定義問題和選項(支持單選和多選)$questions=[['question'=>"PHP是什么類型的語言?(單選)",'options'=>["編譯型","解釋型","匯編型","標記型"],'answer'=>[1],//單個正確答案表示單選'type'=>'radio'],['question'=>"以下哪些是PHP的流程控制語句?(多選)",'options'=>["if","switch","echo","while"],'answer'=>[0,1,3],//多個正確答案表示多選'type'=>'checkbox'],['question'=>"PHP中用于輸出內容的關鍵字有哪些?(多選)",'options'=>["print","echo","write","output"],'answer'=>[0,1],'type'=>'checkbox']];//處理表單提交if($_SERVER['REQUEST_METHOD']=='POST'){$score=0;$totalQuestions=count($questions);foreach($questionsas$index=>$question){$userAnswers=$_POST['q'.$index]??[];//將用戶答案轉換為整數數組(因為從表單獲取的是字符串)$userAnswers=is_array($userAnswers)?array_map('intval',$userAnswers):[intval($userAnswers)];//排序后比較答案(確保順序不影響判斷)sort($userAnswers);$correctAnswers=$question['answer'];sort($correctAnswers);//完全匹配才得分if($userAnswers===$correctAnswers){$score++;}}//顯示結果echo"<h2>您的得分:$score/$totalQuestions</h2>";echo"<p><ahref='".$_SERVER['PHP_SELF']."'>重新測試</a></p>";exit;//停止執行后續的題目顯示}?><!DOCTYPEhtml><html><head><title>PHP單選和多選題測試</title><style>body{font-family:Arial,sans-serif;max-width:800px;margin:0auto;padding:20px;}fieldset{margin-bottom:20px;padding:15px;border:1pxsolid#ddd;border-radius:5px;}legend{font-weight:bold;padding:010px;}label{display:block;margin:8px0;cursor:pointer;}button{padding:8px15px;background-color:#4CAF50;color:white;border:none;border-radius:4px;cursor:pointer;}button:hover{background-color:#45a049;}h1{color:#333;text-align:center;}h2{color:#4CAF50;text-align:center;}.question-type{font-style:italic;color:#666;margin-left:10px;}</style></head><body><h1>PHP基礎知識測試</h1><formmethod="post"><?phpforeach($questionsas$index=>$question):?><fieldset><legend><?=($index+1).".".htmlspecialchars($question['question'])?><spanclass="question-type">(<?=$question['type']=='radio'?'單選':'多選'?>)</span></legend><?phpforeach($question['options']as$optIndex=>$option):?><label><inputtype="<?=$question['type']?>"name="q<?=$index?><?=$question['type']=='checkbox'?'[]':''?>"value="<?=$optIndex?>"><?=htmlspecialchars($option)?></label><?phpendforeach;?></fieldset><?phpendforeach;?><divstyle="text-align:center;"><buttontype="submit">提交答案</button></div></form></body></html>程序運行結果如圖4-2所示。圖4-2單選多選題3.加減乘除游戲程序<?php//生成隨機數和運算符$num1=rand(1,20);$num2=rand(1,20);$operators=['+','-','*','/'];$operator=$operators[rand(0,3)];//計算正確答案switch($operator){case'+':$answer=$num1+$num2;break;case'-':$answer=$num1-$num2;break;case'*':$answer=$num1*$num2;break;case'/':$answer=round($num1/$num2,2);break;}//處理用戶提交的答案$message="";if($_SERVER['REQUEST_METHOD']=='POST'){$userAnswer=$_POST['answer'];if($userAnswer==$answer){$message="<pstyle='color:green'>回答正確!</p>";//生成新題目$num1=rand(1,20);$num2=rand(1,20);$operator=$operators[rand(0,3)];}else{$message="<pstyle='color:red'>回答錯誤!正確答案是$answer</p>";}}?><!DOCTYPEhtml><html><head><title>加減乘除游戲</title></head><body><h1>算術游戲</h1><formmethod="post"><p>請計算:<?="$num1$operator$num2=?"?></p><inputtype="number"step="0.01"name="answer"required><buttontype="submit">提交</button></form><?=$message?></body></html>程序運行結果如圖4-3所示。圖4-3加減乘除游戲4.九九乘法表(循環嵌套)<?phpecho"<h2>九九乘法表</h2>";echo"<tableborder='1'>";for($i=1;$i<=9;$i++){echo"<tr>";for($j=1;$j<=$i;$j++){echo"<td>$j×$i=".($i*$j)."</td>";}echo"</tr>";}echo"</table>";?>程序運行結果如圖4-4所示。圖4-4九九乘法表5.輸出菱形圖案<?php$size=5;//菱形大小//上半部分for($i=1;$i<=$size;$i++){for($j=1;$j<=$size-$i;$j++){echo" ";}for($k=1;$k<=2*$i-1;$k++){echo"*";}echo"<br>";}//下半部分for($i=$size-1;$i>=1;$i--){for($j=1;$j<=$size-$i;$j++){echo" ";}for($k=1;$k<=2*$i-1;$k++){echo"*";}echo"<br>";}?>程序運行結果如圖4-5所示。圖4-5菱形圖形輸出

Web數組應用參考答案1.學生成績錄入及排序系統<?phpsession_start();//初始化學生數組(僅第一次訪問時)if(!isset($_SESSION['students'])){$_SESSION['students']=[];}//處理表單提交if($_SERVER['REQUEST_METHOD']=='POST'){//添加學生成績if(isset($_POST['add'])){$name=$_POST['name'];$score=(int)$_POST['score'];if(!empty($name)&&$score>=0&&$score<=100){$_SESSION['students'][$name]=$score;$message="添加成功:$name-$score分";}else{$message="請輸入有效的姓名和成績(0-100)";}}//刪除學生成績if(isset($_POST['delete'])&&isset($_POST['student_name'])){$name=$_POST['student_name'];if(isset($_SESSION['students'][$name])){unset($_SESSION['students'][$name]);$message="已刪除:$name";}}//排序學生成績if(isset($_POST['sort'])){arsort($_SESSION['students']);//按成績降序排序$message="已按成績降序排序";}}?><!DOCTYPEhtml><html><head><title>學生成績管理系統</title><style>table{border-collapse:collapse;width:80%;margin:20pxauto;}th,td{border:1pxsolid#ddd;padding:8px;text-align:center;}th{background-color:#f2f2f2;}.container{width:80%;margin:0auto;}.form-group{margin:10px0;}</style></head><body><divclass="container"><h1>學生成績管理系統</h1><?phpif(!empty($message)):?><pstyle="color:green"><?=$message?></p><?phpendif;?><formmethod="post"><divclass="form-group"><label>學生姓名:<inputtype="text"name="name"required></label></div><divclass="form-group"><label>學生成績:<inputtype="number"name="score"min="0"max="100"required></label></div><buttontype="submit"name="add">添加學生</button><buttontype="submit"name="sort">按成績排序</button></form><h2>學生成績列表</h2><?phpif(!empty($_SESSION['students'])):?><table><tr><th>姓名</th><th>成績</th><th>操作</th></tr><?phpforeach($_SESSION['students']as$name=>$score):?><tr><td><?=htmlspecialchars($name)?></td><td><?=$score?></td><td><formmethod="post"style="display:inline;"><inputtype="hidden"name="student_name"value="<?=htmlspecialchars($name)?>"><buttontype="submit"name="delete">刪除</button></form></td></tr><?phpendforeach;?></table><?phpelse:?><p>暫無學生成績數據</p><?phpendif;?></div></body></html>運行結果如圖5-1所示。可以添加學生成績信息,并進行排序和刪除信息。圖5-1學生成績管理系統2.購物車系統<?phpsession_start();//初始化購物車if(!isset($_SESSION['cart'])){$_SESSION['cart']=[];}//商品列表$products=["P001"=>["name"=>"iPhone13","price"=>5999],"P002"=>["name"=>"華為Mate50","price"=>4999],"P003"=>["name"=>"小米12","price"=>3699],"P004"=>["name"=>"OPPOFindX5","price"=>3999]];//處理購物車操作if($_SERVER['REQUEST_METHOD']=='POST'){if(isset($_POST['add_to_cart'])&&isset($_POST['product_id'])){$productId=$_POST['product_id'];if(isset($products[$productId])){if(isset($_SESSION['cart'][$productId])){$_SESSION['cart'][$productId]['quantity']++;}else{$_SESSION['cart'][$productId]=['name'=>$products[$productId]['name'],'price'=>$products[$productId]['price'],'quantity'=>1];}}}if(isset($_POST['remove_item'])&&isset($_POST['product_id'])){$productId=$_POST['product_id'];if(isset($_SESSION['cart'][$productId])){unset($_SESSION['cart'][$productId]);}}if(isset($_POST['clear_cart'])){$_SESSION['cart']=[];}if(isset($_POST['update_quantity'])&&isset($_POST['product_id'])&&isset($_POST['quantity'])){$productId=$_POST['product_id'];$quantity=(int)$_POST['quantity'];if(isset($_SESSION['cart'][$productId])&&$quantity>0){$_SESSION['cart'][$productId]['quantity']=$quantity;}}}?><!DOCTYPEhtml><html><head><title>簡易購物車系統</title><style>body{font-family:Arial,sans-serif;margin:20px;}.container{display:flex;}.products,.cart{flex:1;padding:20px;}table{width:100%;border-collapse:collapse;margin-top:20px;}th,td{border:1pxsolid#ddd;padding:8px;text-align:left;}th{background-color:#f2f2f2;}.total{font-weight:bold;font-size:1.2em;margin-top:20px;}</style></head><body><h1>簡易購物車系統</h1><divclass="container"><divclass="products"><h2>商品列表</h2><table><tr><th>商品ID</th><th>商品名稱</th><th>價格</th><th>操作</th></tr><?phpforeach($productsas$id=>$product):?><tr><td><?=$id?></td><td><?=$product['name']?></td><td>¥<?=number_format($product['price'],2)?></td><td><formmethod="post"><inputtype="hidden"name="product_id"value="<?=$id?>"><buttontype="submit"name="add_to_cart">加入購物車</button></form></td></tr><?phpendforeach;?></table></div><divclass="cart"><h2>購物車</h2><?phpif(!empty($_SESSION['cart'])):?><table><tr><th>商品名稱</th><th>單價</th><th>數量</th><th>小計</th><th>操作</th></tr><?php$total=0;foreach($_SESSION['cart']as$id=>$item):$subtotal=$item['price']*$item['quantity'];$total+=$subtotal;?><tr><td><?=$item['name']?></td><td>¥<?=number_format($item['price'],2)?></td><td><formmethod="post"style="display:inline;"><inputtype="hidden"name="product_id"value="<?=$id?>"><inputtype="number"name="quantity"value="<?=$item['quantity']?>"min="1"style="width:50px;"><buttontype="submit"name="update_quantity">更新</button></form></td><td>¥<?=number_format($subtotal,2)?></td><td><formmethod="post"style="display:inline;"><inputtype="hidden"name="product_id"value="<?=$id?>"><buttontype="submit"name="remove_item">移除</button></form></td></tr><?phpendforeach;?></table><divclass="total">總計:¥<?=number_format($total,2)?></div><formmethod="post"><buttontype="submit"name="clear_cart">清空購物車</button></form><?phpelse:?><p>購物車為空</p><?phpendif;?></div></div></body></html>運行結果如圖5-2所示。圖5-2購物車商品列表信息單擊加入購物車出現購物車圖5-3所示頁面。圖5-3購物車信息單擊移除會移除商品信息。3.數組操作練習<?php//1.創建和初始化數組$colors=["red","green","blue"];$person=["name"=>"張三","age"=>25,"city"=>"北京"];//2.數組遍歷echo"<h3>遍歷索引數組:</h3>";foreach($colorsas$color){echo$color."<br>";}echo"<h3>遍歷關聯數組:</h3>";foreach($personas$key=>$value){echo"$key:$value<br>";}//3.數組操作echo"<h3>數組操作示例:</h3>";//添加元素array_push($colors,"yellow");$person["job"]="工程師";//刪除元素unset($colors[1]);//刪除"green"unset($person["age"]);//查找元素if(in_array("red",$colors)){echo"紅色在顏色數組中<br>";}//排序sort($colors);//索引數組排序ksort($person);//關聯數組按鍵名排序//輸出結果echo"<pre>";print_r($colors);print_r($person);echo"</pre>";?>運行結果如圖5-4所示。圖5-4數組操作示例

Web函數應用參考答案一、函數定義與調用1.有參函數和無參函數定義與調用<?php//無參函數functiongreet(){echo"Hello,World!<br>";}//有參函數functionaddNumbers($num1,$num2){return$num1+$num2;}//調用無參函數greet();//調用有參函數$result=addNumbers(5,7);echo"5+7=".$result."<br>";?>程序運行結果如6-1所示。圖6-1函數定義與調用二、內置函數應用2.使用五個不同的PHP內置函數<?php//1.字符串長度函數$str="HelloPHP";echo"字符串長度:".strlen($str)."<br>";//2.日期函數echo"當前日期:".date("Y-m-dH:i:s")."<br>";//3.數學函數-四舍五入$number=3.14159;echo"四舍五入(2位小數):".round($number,2)."<br>";//4.數組函數$colors=array("red","green","blue");echo"數組元素數量:".count($colors)."<br>";//5.文件系統函數if(file_exists("test.txt")){echo"文件存在<br>";}else{echo"文件不存在<br>";}?>程序運行結果如圖6-2所示。圖6-2內置函數三、函數嵌套與遞歸3.1函數嵌套示例<?php//計算圓的面積functioncircleArea($radius){returnpi()*pow($radius,2);}//計算圓柱體體積(嵌套調用circleArea函數)functioncylinderVolume($radius,$height){$baseArea=circleArea($radius);//嵌套調用return$baseArea*$height;}//使用示例$radius=5;$height=10;echo"圓柱體體積:".cylinderVolume($radius,$height)."<br>";?>程序運行結果如圖6-3所示。圖6-3函數嵌套示例3.2遞歸函數示例(斐波那契數列)<?phpfunctionfibonacci($n){if($n==0){return0;}elseif($n==1){return1;}else{returnfibonacci($n-1)+fibonacci($n-2);//遞歸調用}}//輸出前10個斐波那契數echo"斐波那契數列前10項:";for($i=0;$i<10;$i++){echofibonacci($i)."";}?>程序運行結果如圖6-4所示。圖6-4函數遞歸示例四、錯誤處理與調試4.1故意引入錯誤并修復<?php//原始有錯誤的代碼functiondivideNumbers($a,$b){return$a/$b;//當$b為0時會出錯}//修復后的代碼functiondivideNumbersFixed($a,$b){if($b==0){return"除數不能為零";}return$a/$b;}//測試echodivideNumbersFixed(10,2)."<br>";//輸出5echodivideNumbersFixed(10,0)."<br>";//輸出"除數不能為零"?>程序運行結果如圖6-5所示。圖6-5錯誤引入示例五、綜合應用示例<?php//綜合應用:函數實現計算器程序functioncalculate($num1,$num2,$operator){switch($operator){case'+':return$num1+$num2;case'-':return$num1-$num2;case'*':return$num1*$num2;case'/':if($num2==0){return"除數不能為零";}return$num1/$num2;default:return"無效的運算符";}}//測試計算器echo"5+3=".calculate(5,3,'+')."<br>";echo"10/0=".calculate(10,0,'/')."<br>";echo"4*6=".calculate(4,6,'*')."<br>";?>程序運行結果如圖6-6所示。圖6-6函數綜合應用

PHP與Web頁面交互參考答案一、表單數據獲取與處理1.使用$_GET[]和$_POST[]獲取表單數據<?phpif(isset($_GET['submit'])){$name=htmlspecialchars($_GET['name']??'');$email=htmlspecialchars($_GET['email']??'');echo"GET方法獲取的數據:<br>";echo"姓名:$name<br>郵箱:$email";}if(isset($_POST['submit'])){$name=htmlspecialchars($_POST['name']??'');$email=htmlspecialchars($_POST['email']??'');echo"POST方法獲取的數據:<br>";echo"姓名:$name<br>郵箱:$email";}?><formaction=""method="get">姓名:<inputtype="text"name="name"><br>郵箱:<inputtype="text"name="email"><br><inputtype="submit"name="submit"value="提交(GET)"></form><formaction=""method="post">姓名:<inputtype="text"name="name"><br>郵箱:<inputtype="text"name="email"><br><inputtype="submit"name="submit"value="提交(POST)"></form>程序運行結果如圖7-1所示。圖7-1獲取用戶數據二、正則表達式應用2.使用正則表達式驗證用戶輸入<?phpfunctionvalidateInput($input,$pattern){returnpreg_match($pattern,$input);}//驗證規則$patterns=['username'=>'/^[a-zA-Z0-9_]{4,16}$/',//4-16位字母數字下劃線'password'=>'/^[a-zA-Z0-9@#$%^&*]{6,18}$/',//6-18位包含特殊字符'email'=>'/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/','phone'=>'/^1[3-9]\d{9}$/'//11位手機號];//測試數據$testData=['username'=>'user_123','password'=>'P@ssw0rd','email'=>'test@','phone'=>];//驗證測試foreach($testDataas$field=>$value){$result=validateInput($value,$patterns[$field])?'有效':'無效';echoucfirst($field).":$value-$result<br>";}?>程序運行結果如圖7-2所示。圖7-2正則表達式示例三、綜合應用-用戶注冊驗證3.完整的用戶注冊驗證系統<?php//register.phpif($_SERVER['REQUEST_METHOD']==='POST'){//獲取并清理輸入數據$username=trim($_POST['username']??'');$password=trim($_POST['password']??'');$email=trim($_POST['email']??'');$phone=trim($_POST['phone']??'');//定義驗證規則$errors=[];$patterns=['username'=>'/^[a-zA-Z0-9_]{4,16}$/','password'=>'/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@#$%^&*]{8,}$/','email'=>'/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/','phone'=>'/^1[3-9]\d{9}$/'];//執行驗證if(!preg_match($patterns['username'],$username)){$errors[]="用戶名必須是4-16位的字母、數字或下劃線";}if(!preg_match($patterns['password'],$password)){$errors[]="密碼必須至少8位,包含字母和數字";}if(!preg_match($patterns['email'],$email)){$errors[]="請輸入有效的電子郵件地址";}if(!preg_match($patterns['phone'],$phone)){$errors[]="請輸入有效的11位手機號碼";}//處理驗證結果if(empty($errors)){echo"<divstyle='color:green'>注冊成功!歡迎$username</div>";//這里可以添加數據庫存儲邏輯}else{echo"<divstyle='color:red'>注冊失敗:<br>".implode("<br>",$errors)."</div>";}}?><!DOCTYPEhtml><html><head><title>用戶注冊</title><style>.form-group{margin-bottom:15px;}label{display:inline-block;width:100px;}.error{color:red;font-size:12px;}</style></head><body><h2>用戶注冊</h2><formmethod="post"action="register.php"><divclass="form-group"><labelfor="username">用戶名:</label><inputtype="text"id="username"name="username"required><spanclass="error">4-16位字母、數字或下劃線</span></div><divclass="form-group"><labelfor="password">密碼:</label><inputtype="password"id="password"name="password"required><spanclass="error">至少8位,包含字母和數字</span></div><divclass="form-group"><labelfor="email">電子郵箱:</label><inputtype="email"id="email"name="email"required></div><divclass="form-group"><labelfor="phone">手機號碼:</label><inputtype="tel"id="phone"name="phone"required></div><divclass="form-group"><inputtype="subm

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論