php學習 (一)

來源:互聯網
上載者:User

標籤:

  在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學習 (一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.