星期三, 10月 20, 2010

Zend PHP 5 Certification Study Guide 筆記 (三) - Web Programming & OO

  1. Web Programming 
    • Managing File Uploads
      檔案上傳後,php會將上傳檔移到暫存的地方,如果沒有複製或搬移,將會存活到script結束為止 透過$_FILES可取得上傳檔的資訊
      nameThe original name of the file
      typeThe MIME type of the file provided by the browser
      sizeThe size (in bytes) of the file
      tmp_nameThe name of the file’s temporary location
      errorThe error code associated with this file. A value of UPLOAD_ERR_OK indicates a successful transfer, while any other
      error indicates that something went wrong (for example, the
      file was bigger than the maximum allowed size).
      由於直接存取上傳檔有安全性問題,所以最好先
      1. 檢查upload information為UPLOAD_ERR_OK
      2. 檢查檔案size not zero 及 tmp_name is not set to none.
      3. 存取檔案(2種方法)
        • is_uploaded_file(),檢查是否為上傳檔案,再進行複製 if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
             echo 
          "File "$_FILES['userfile']['name'] ." uploaded successfully.\n";
             echo 
          "Displaying contents\n";
             
          readfile($_FILES['userfile']['tmp_name']);
          } else {
             echo 
          "Possible file upload attack: ";
             echo 
          "filename '"$_FILES['userfile']['tmp_name'] . "'.";
          }
        • move_uploaded_file()直接搬移檔案
          $uploads_dir '/uploads';
          foreach (
          $_FILES["pictures"]["error"] as $key => $error) {
              if (
          $error == UPLOAD_ERR_OK) {
                  
          $tmp_name $_FILES["pictures"]["tmp_name"][$key];
                  
          $name $_FILES["pictures"]["name"][$key];
                  
          move_uploaded_file($tmp_name"$uploads_dir/$name");
              }
          }

    • Http Headers
      header在需在任何output前完成,否則會無效或出錯,除非有用buffer
      • Redirection
        redirect後,最好加個exit(),避免執行到後續的script
        header("Location: http://phparch.com"); exit();
        在送出form,如果回上一頁,會出現要"重送資訊",如果要避免,就可以透過redirect forward到正確頁
  2. OO

沒有留言: