1. 程式人生 > >PHP學習練手(十二)

PHP學習練手(十二)

傳送電子郵件


函式:
1、傳送郵件函式: (subject中不能包含換行符;正文中每一行的長度都不能超過70,故用wordwrap函式進行隔斷)
mail(to, subject, body, [headers])

2、字串隔斷函式

wordwrap(string, len)

程式碼:
email.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Me</title>
</head
>
<body> <h1>Contact Me</h1> <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { if(!empty($_POST['name']) && !($_POST['email']) && !empty($_POST['comments'])) { $body = "Name: {$_POST['name']}\n\nComments: {$_POST['comments']}"
; //字元截斷 $body = Wordwrap($body, 70); mail('[email protected]', 'Contact From Submission', $body, "From:{$_POST['email']}"); echo '<p><em>Thank you for contacting me. I will reply some day.</em></p>'; $_POST
=array() ; //將$_POST清空 }else{ echo '<p style="font-weight: bold; color: #C00"></p>'; } } ?>
<p>Please fill out this form to contact me.</p> <form action="email.php" method="post"> <p>Name: <input type="text" name="name" size="30" maxlength="60" value="<?php if(isset($_POST['name'])) echo $_POST['name']; ?>" /></p> <p>Email Address: <input type="text" name="name" size="30" maxlength="80" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>" /></p> <p>Comments: <textarea name="comments" rows="5" cols="30"><?php if(isset($_POST['comments'])) echo $_POST['comments']; ?></textarea></p> <p><input type="submit" name="submit" value="Send!" /></p> </form> </body> </html>

執行:
這裡寫圖片描述

這裡寫圖片描述

處理檔案上傳

準備工作:

  1. 必須正確地設定PHP
    這裡寫圖片描述

    這裡寫圖片描述

    這裡寫圖片描述

    這裡寫圖片描述

    這裡寫圖片描述

  2. 必須有一個臨時儲存目錄,它具有正確的許可權
    這裡寫圖片描述

  3. 必須有一個最終儲存目錄,它具有正確的許可權
    注:與htdocs在同一級目錄下,這樣更安全
    這裡寫圖片描述

表單必要語法條件:

<form enctype="multipart" action="script.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    File <input type="file" name="upload" />
</form>

初始表單標籤的enctype部分指示表單能夠處理多種型別的資料,包括檔案。如果想接受檔案上傳,就必須包括enctype! 提交表單必須使用POST方式。MAX_FILE_SIZE 隱藏輸入框是一種表單限制元素,用於限制所選的檔案可以有多大(以位元組為單位),它必須出現在檔案輸入框之前。file輸入框型別將在表單中建立合適的按鈕

函式:

  1. 從臨時目錄轉移到永久目錄:move_uploaded_file()

  2. 函式搜尋陣列中是否存在指定的值:in_array()

  3. 檔案超全域性變數:$_FILES

  4. 檢查檔案或目錄是否存在:file_exists()

  5. 查指定的檔名是否是正常的檔案:is_files()

  6. 刪除檔案:unlink()

程式碼:
upload_image.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload an Image</title>
</head>
<body>
    <?php #Script 11.2 - upload_image.php
        if($_SERVER['REQUEST_METHOD'] == 'POST')
        {

            if(isset($_FILES['upload']))
            {
                //允許的圖片格式
                $allowed = array('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/png', 'image/x-png');

                if(in_array($_FILES['upload']['type'], $allowed))
                {
                    $name = $_FILES['upload']['name'];
                    //解決檔名中文亂碼問題
                    $name = iconv("UTF-8","gb2312", $name);
                    if(move_uploaded_file($_FILES['upload']['tmp_name'], "../../../../uploads/$name"))
                    {
                        echo '<p><em>The file has been upload!</em></p>';
                    }
                }else{
                        echo '<p>Please upload a JPEG or PNG image</p>';
                    }
            }

            if($_FILES['upload']['error'] > 0)
            {
                echo '<p style="font-weight: bold; color: #C00">The file could not be uploaded because: <strong>';
                    switch ($_FILES['upload']['error']) {
                        case 1:
                            print 'The file exceeds the upload_max_filesize setting in php.ini';
                            break;
                        case 2:
                            print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
                            break;
                        case 3:
                            print 'The file was only partially upload.';
                            break;
                        case 4:
                            print 'No File was upload.';
                            break;
                        case 6:
                            print 'No temporary folder was available.';
                            break;
                        case 7:
                            print 'Unable to write to the disk.';
                            break;
                        case 8:
                            print 'File upload stopped.';
                            break;
                        default:
                            print 'A system error occurred.';
                            break;
                    }
                print '</strong></p>';
            }

            //若臨時檔案依然存在,則刪除臨時檔案
            if(file_exists($_FILES['upload']['tmp_name']) && is_file($_FILES['upload']['tmp_name']))
            {
                unlink($_FILES['upload']['tmp_name']);
            }
        }
    ?>

    <form enctype="multipart/form-data" action="upload_image.php" method="post">
        <input type="hidden" name="MAX_FILE_SIZE" value="534288" />
        <fieldset><legend>Select a JPEG or PNG image of 512KB or smaller to be uploaded: </legend>
        <p><b>File: </b><input type="file" name="upload" /></p>
        </fieldset>
        <div align="center"><input type="submit" name="submit" value="Submit" /></div>
    </form>
</body>
</html>

執行前uploads資料夾為空:
這裡寫圖片描述

上傳圖片後:
這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

當載入bmp檔案時:
這裡寫圖片描述

當不載入任何圖片檔案時:
這裡寫圖片描述

處理檔案上傳之PHP與JS

函式:

  1. 返回一個數組,其中包含指定路徑中的檔案和目錄:scandir()

  2. 返回字串的一部分:substr()

  3. 函式用於獲取影象尺寸,型別等資訊:getimagesize()

  4. 把所有字元轉換為小寫:strtolower()

  5. 返回指定檔案的大小:filesize()

  6. 該函式讀入一個檔案並寫入到輸出緩衝:readfile()

  7. 設定用於一個指令碼中所有日期時間函式的預設時區:date_default_timezone_set()

  8. 函式用於對日期或時間進行格式化:date()

程式碼:
function.js:

//Script 11.3 - function.js

function create_window(image, width, height)
{
    width = width + 10;
    height = height + 10;

    if(window.popup && window.popup.closed)
    {
        window.popup.resizeTo(width, height);
    }

    var specs = "location=no, scrollbars=no, menubars=no, resizeable=yes, left=0, top=0, width=" + width + ", height=" + height;

    var url="show_image.php?image="+image;

    popup = window.open(url, "ImageWindow", specs);
    popup.focus();

}

images.php:
注:此處省略PHP的結束標籤。因為不經意在PHP的結束標籤後面加了多餘的空格或空行時,瀏覽器可能無法顯示圖片(因為瀏覽器接受到與Content-Length頭匹配的X長度的影象資料後,還會多接受一點多餘的資料)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Images</title>
    <script type="text/javascript" charset="utf-8" src="../JS/function.js"></script>
</head>
<body>
    <p>Click on an image to view it in a separate window.</p>
    <ul>
        <?php #Script 11.4 - image.php
            $dir = "../../../../uploads";

            $files = scandir($dir);
            foreach ($files as $image) {
                //substr()返回字串的一部分
                if(substr($image, 0, 1) != '.')
                {

                    $image_size = getimagesize("$dir/$image");
                    $image_true_name = iconv("gb2312", "utf-8", $image);
                    $image_name = urlencode($image_true_name);

                    echo "<li><a href=\"javascript:create_window('$image_true_name', $image_size[0], $image_size[1])\">$image_true_name</a></li>\n";
                }


            }   
        ?>
    </ul>
</body>
</html>

show_image.php:

<?php
    $name = false;

    if(isset($_GET['image']))
    {
        $ext = strtolower(substr($_GET['image'], -4));
        if(($ext == '.jpg') OR ($ext == 'jpeg') OR ($ext == '.png'))
        {
            $image_true_name = iconv("UTF-8","gb2312", $_GET['image']);
            $image="../../../../uploads/$image_true_name";
            //echo $image;
            //$image = "../../../../uploads/{$_GET['image']}";
            //echo $image;
            if(file_exists($image) && is_file($image))
            {
                $name = $_GET['image'];
            }
        }

    }

    if(!$name)
    {
        $image = 'images/unavailable.png';
        $name = 'unavailable.png';
    }

    $info = getimagesize($image);
    $fs = filesize($image);

    //傳送資訊頭:
header ("Content-type: {$info['mime']}\n");
header ("Content-Disposition: inline; filename=\"$name\"\n");
header ("Content-Length: $fs\n");

readfile($image);

執行:
這裡寫圖片描述

這裡寫圖片描述

images1.php:(對images.php的增強)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Images</title>
    <script type="text/javascript" charset="utf-8" src="../JS/function.js"></script>
</head>
<body>
    <p>Click on an image to view it in a separate window.</p>
    <ul>
        <?php #Script 11.6 - image1.php

            date_default_timezone_set('PRC');   //中國標準時間
            $dir = "../../../../uploads";

            $files = scandir($dir);
            foreach ($files as $image) {
                //substr()返回字串的一部分
                if(substr($image, 0, 1) != '.')
                {

                    $image_size = getimagesize("$dir/$image");

                    $file_size = round((filesize("$dir/$image")) / 1024)."kb";

                    $image_date = date("F d, Y H:i:s", filemtime("$dir/$image"));

                    $image_true_name = iconv("gb2312", "utf-8", $image);
                    $image_name = urlencode($image_true_name);

                    echo "<li><a href=\"javascript:create_window('$image_true_name', $image_size[0], $image_size[1])\">$image_true_name</a> $file_size ($image_date)</li>\n";
                }


            }   
        ?>
    </ul>
</body>
</html>

執行:
這裡寫圖片描述