標籤:
在W3C網站上過了一遍基礎教程後,對php文法有了一些瞭解。
開始做一些小項目來練手:
1.1:產生隨機字串
做一個頁面,上面有一個文本編輯框和一個按鈕,在編輯框中輸入一個數字,點擊按鈕後在頁面上顯示一個隨機產生的字串,字串的長度為編輯框中輸入的數值,字串只能包含(0-9,a- z, A-Z)。
代碼實現如下:
Test1.1.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<?php
echo "1.1:產生隨機字串";
echo "<br>";
echo "做一個頁面,上面有一個文本編輯框和一個按鈕,在編輯框中輸入一個數字,點擊按鈕後在頁面上顯示一個隨機產生的字串,字串的長度為編輯框中輸入的數值,字串只能包含(0-9,a-z, A-Z)。";
echo "<br>";
?> //經提醒,靜態文字最好用html輸出,不要使用php
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">
請輸入數字:<br>
<input type = "text" name = "txt1"><br>
<input type = "submit" value = "提交" name = "btn1"><br>
</form>
<?php
$txt1 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") { //會進一步改進,使用JQ進行非同步呼叫,局部重新整理
$txt1 = testInput($_POST["txt1"]);
if(is_numeric($txt1) && is_int($txt1+0) && $txt1>0)
{
echo "產生的".$txt1."位隨機碼:";
echo creatRandom($txt1);
}else
echo "輸入的不是正整數";
}
/** //經提醒,方法應該格式化的注釋
*
* @param $len
*/
function creatRandom($len){ //產生對應位元的隨機碼
$word = $tmp = ‘‘;
$chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789‘;
while(strlen($word)<$len){
$tmp = substr($chars,(mt_rand()%strlen($chars)),1); //產生一位隨機碼
$word.= $tmp;
}
return $word;
}
function testInput($data) { //對使用者輸入的資料進行處理,包括去除空格和反斜線
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
php學習 (一)