PHP-форма с возможностью загрузки нескольких файлов

1

Я пытаюсь приспособить форму php, которую я нашел, называется "fns". Он использует до загрузки страницы

<?php
session_start();

require_once('parts-request-fns.php'); 
$_SESSION['myForm'] = $_POST;

?>

и где я хочу, чтобы форма появлялась

<?php
            // contact form
            if (isset($_POST['submitted']) && ('true' == $_POST['submitted'])) { 
                // checks if the form is submitted and then processes it
                process_form(); 

            } else { 
                // else prints the form
                print_form(); 
            }

            ?>

ссылающийся на part-request-fns.php выглядит следующим образом. Мне нужно 3 поля для загрузки файлов, поэтому мой вопрос заключается в том, как я смогу адаптировать код, чтобы можно было разместить все 3 файла? В настоящее время каждый файл может быть отправлен в форму, но публикуется только первая. Я изменил идентификатор ввода, имя на второе вложение и третье вложение, но не уверен, как ссылаться на него дальше.

    <?php
//start session
session_start();

// prints form
function print_form(){
?>

<form method="post" action="<?php echo $_SERVER[PHP_SELF];?>" id="uploadform" enctype="multipart/form-data" style="font-size: 16px;
    font-family: Helvetica, Arial, sans-serif;
    padding: 14px 0 14px 0;
    font-weight: lighter;
    line-height: 20px;">

    <br />

  <input type="hidden" name="parts-request" id="parts-request" value="OandH "> 

    <h3>Vehicle Details</h3>

    <p style="margin:17px 0">  <label style=" font-family: Helvetica, Arial, sans-serif;">Vehicle Registration: <span style="color:red">*</span></label>
<input class="form-input" name="vehiclereg" id="vehiclereg" type="text" value="<?= $_SESSION['myForm']['vehiclereg']; ?>" tabindex="1" style="width:100%;"/></p>

    <p style="margin:17px 0">  <label style=" font-family: Helvetica, Arial, sans-serif;">VIN/Chassis Number (Last 6 Digits):</label>
<input class="form-input" name="chassisnumber" id="chassisnumber" type="text" value="<?= $_SESSION['myForm']['chassisnumber']; ?>" tabindex="1" style="width:100%;"/></p>




  <h3>Customer Details</h3>
<p style="margin:17px 0">  <label style=" font-family: Helvetica, Arial, sans-serif;">Name: <span style="color:red">*</span></label>
<input class="form-input" name="namefrom" id="namefrom" type="text" value="<?= $_SESSION['myForm']['namefrom']; ?>" tabindex="1" style="width:100%;"/></p>

<!--changed these-->
<p style="margin:17px 0">  <label style=" font-family: Helvetica, Arial, sans-serif;">Address:</label>
<input class="form-input" name="address" id="address" type="text" value="<?= $_SESSION['myForm']['address']; ?>" tabindex="1" style="width:100%;"/></p>

<p style="margin:17px 0">  <label style=" font-family: Helvetica, Arial, sans-serif;">Town:</label>
<input class="form-input" name="town" id="town" type="text" value="<?= $_SESSION['myForm']['town']; ?>" tabindex="1" style="width:100%;"/></p>

<p style="margin:17px 0">  <label style=" font-family: Helvetica, Arial, sans-serif;">Postcode:</label>
<input class="form-input" name="postcode" id="postcode" type="text" value="<?= $_SESSION['myForm']['postcode']; ?>" tabindex="1" style="width:100%;"/></p>
<!--changed these-->


<p style="margin:17px 0">  <label style=" font-family: Helvetica, Arial, sans-serif;">Email: <span style="color:red">*</span></label>
<input class="form-input" name="emailfrom" id="emailfrom" type="text" value="<?= $_SESSION['myForm']['emailfrom']; ?>" tabindex="3" style="width:100%;"/></p>



<p style="margin:17px 0">  <label style="margin-right: 4px; font-family: Helvetica, Arial, sans-serif;">Contact No: <span style="color:red">*</span></label>
<input type="text" class="form-input" name="contactnumber" id="contactnumber" rows="2" cols="22" tabindex="6" value="<?= $_SESSION['myForm']['contactnumber']; ?>" style="width:100%;" /></p>

<p style="margin:17px 0">  <label style="margin-right: 4px; vertical-align:top; font-family: Helvetica, Arial, sans-serif; ">Brief Description of Request: </label>
<textarea class="form-input" name="comments" id="comments" rows="7" cols="22" tabindex="6" value="<?= $_SESSION['myForm']['comments']; ?>" style="height:50px; width:100%;" ></textarea></p>
<p>If appropriate, please upload any photos or documents</p>
<p>Please make sure each image does not exceed 1mb in size.</p>
<p style="margin:17px 0">
<label style="margin-right: 4px; font-family: Helvetica, Arial, sans-serif;">Vehicle image/doc one:</label>
<input name="attachment" id="attachment" type="file" tabindex="7"></p>

<p style="margin:17px 0">
<label style="margin-right: 4px; font-family: Helvetica, Arial, sans-serif;">Vehicle image/doc two:</label>
<input name="second-attachment" id="second-attachment" type="file" tabindex="7"></p>

<p style="margin:17px 0">
<label style="margin-right: 4px; font-family: Helvetica, Arial, sans-serif;">Vehicle image/doc three:</label>
<input name="third-attachment" id="third-attachment" type="file" tabindex="7"></p>


<!--<div class="clear:both">
<input type="checkbox" name="agree" value="Yes, I agree for photo to be shared on facebook">I am willing for my photo to appear on facebook.</div>-->


  <!-- <input style="margin:55px 0 0 10px"class="submit-button" type="image" value="POST ME" id="submit" src="images/enter.jpg"  width="165" alt="submit"> -->

  <input type="submit" class="submit-button" type="image" value="SUBMIT" id="submit" alt="submit">

<input type="hidden" name="submitted"  value="true" />
</form>




<?php
}

// enquiry form validation

function process_form() {
    // Read POST request params into global vars
    // FILL IN YOUR EMAIL
    $to = "[email protected]";
    $subject = trim($_POST['namefrom']);
    $vehiclereg = trim($_POST['vehiclereg']);
    $chassisnumber = trim($_POST['chassisnumber']); 
    $contactnumber = trim($_POST['contactnumber']);
    $emailfrom = trim($_POST['emailfrom']);
    $address = trim($_POST['address']);
    $town = trim($_POST['town']);
    $postcode = trim($_POST['postcode']);
    $comments = trim($_POST['comments']);

    // Allowed file types. add file extensions WITHOUT the dot.
    $allowtypes=array("jpg", "JPG", "doc", "pdf", "docx", "png", "PNG", "gif", "GIF");

    // Require a file to be attached: false = Do not allow attachments true = allow only 1 file to be attached
    $requirefile="true";

    // Maximum file size for attachments in KB NOT Bytes for simplicity. MAKE SURE your php.ini can handel it,
    // post_max_size, upload_max_filesize, file_uploads, max_execution_time!
    // 2048kb = 2MB,       1024kb = 1MB,     512kb = 1/2MB etc..
    $max_file_size="5000";

    // Thank you message
    $thanksmessage="<h2 style='font-size:18px; font-family:'arial', helvetica, sans-serif; font-weight:bold; padding-bottom:8px'>Your message have been received! <br /> </h2>";

    $errors = array(); //Initialize error array

            //checks for vehicle registation number 
        if (empty($_POST['vehiclereg']) ) {
        $errors[]='You forgot to enter your vehicle registration number';
        }

    //checks for a name
    if (empty($_POST['namefrom']) ) {
        $errors[]='You forgot to enter your name';
        }


    //checks for an email
    if (empty($_POST['emailfrom']) ) {
        $errors[]='You forgot to enter your email';
        } else {

        if (!eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['emailfrom'])))) {
            $errors[]='Please enter a valid email address';
        } // if eregi
    } // if empty email

            //checks for contact number 
        if (empty($_POST['contactnumber']) ) {
        $errors[]='You forgot to enter your telephone number';
        }

    //checks for a message


    // checks for required file
    // http://amiworks.co.in/talk/handling-file-uploads-in-php/
    if($requirefile=="false") {
        if($_FILES['attachment']['error']==4) {
            $errors[]='You forgot to attach your Picture';
        }
    }

    //checks attachment file
    // checks that we have a file
    if((!empty($_FILES["attachment"])) && ($_FILES['attachment']['error'] == 0)) {
            // basename -- Returns filename component of path
            $filename = basename($_FILES['attachment']['name']);
            $ext = substr($filename, strrpos($filename, '.') + 1);
            $filesize=$_FILES['attachment']['size'];
            $max_bytes=$max_file_size*5000;

            //Check if the file type uploaded is a valid file type. 
            if (!in_array($ext, $allowtypes)) {
                $errors[]="Invalid file format<br /><strong>".$filename."</strong>";

        // check the size of each file
        } elseif($filesize > $max_bytes) {
                $errors[]= "Your file: <strong>".$filename."</strong> is to big. Max file size is ".$max_file_size."kb.";
            }

    } // if !empty FILES

    if (empty($errors)) { //If everything is OK

        // send an email
        // Obtain file upload vars
        $fileatt      = $_FILES['attachment']['tmp_name'];
        $fileatt_type = $_FILES['attachment']['type'];
        $fileatt_name = $_FILES['attachment']['name'];


        // Headers
        $headers = "From: $emailfrom";

        // create a boundary string. It must be unique
          $semi_rand = md5(time());
          $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

          // Add the headers for a file attachment
          $headers .= "\nMIME-Version: 1.0\n" .
                      "Content-Type: multipart/mixed;\n" .
                      " boundary=\"{$mime_boundary}\"";

          // Add a multipart boundary above the plain message
          $message ="This is a multi-part message in MIME format.\n\n";
          $message.="--{$mime_boundary}\n";
          $message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
          $message.="Content-Transfer-Encoding: 7bit\n\n";
          $message.="From: ".$subject."\n";
          $message.="Email: ".$emailfrom."\n";

          $message.="Vehicle Registration: ".$vehiclereg."\n";
          $message.="Chassis Number: ".$chassisnumber."\n";

          $message.="Address: ".$address."\n";
          $message.="Town: ".$town."\n";
          $message.="Postcode: ".$postcode."\n";
          $message.="Contact Number: ".$contactnumber."\n";
          $message.="Comment: ".$comments."\n\n";

        if (is_uploaded_file($fileatt)) {
          // Read the file to be attached ('rb' = read binary)
          $file = fopen($fileatt,'rb');
          $data = fread($file,filesize($fileatt));
          fclose($file);

          // Base64 encode the file data
          $data = chunk_split(base64_encode($data));

          // Add file attachment to the message
          $message .= "--{$mime_boundary}\n" .
                      "Content-Type: {$fileatt_type};\n" .
                      " name=\"{$fileatt_name}\"\n" .
                      //"Content-Disposition: attachment;\n" .
                      //" filename=\"{$fileatt_name}\"\n" .
                      "Content-Transfer-Encoding: base64\n\n" .
                      $data . "\n\n" .
                      "--{$mime_boundary}--\n";
        }


        // Send the completed message

        $envs = array("HTTP_USER_AGENT", "REMOTE_ADDR", "REMOTE_HOST");
        foreach ($envs as $env)
        $message .= "$env: $_SERVER[$env]\n";

        if(!mail($to,$subject,$message,$headers)) {
            exit("Mail could not be sent. Sorry! An error has occurred, please report this to the website administrator.\n");
        } else {
            echo '<div id="formfeedback"><br/><h1>Thank You!</h1>'. $thanksmessage .'</p></div>';
        } // end of if !mail

    } else { //report the errors
        echo '<div id="formfeedback"><strong>Error!</strong><br />';
        foreach ($errors as $msg) { //prints each error
                echo " - $msg<br />\n";
            } // end of foreach
        echo '</p><p>Please try again</p></div>';
        print_form();
    } //end of if(empty($errors))

    } // end of process_form()
    ?>
  • 0
    Выйдите из коробки и посмотрите, что это делает $_SESSION['myForm'] = $_POST;
Теги:
forms
file-upload

2 ответа

1

файлы передаются в php в переменной $_FILES а не переменной $_POST. http://php.net/manual/en/reserved.variables.files.php

вы можете перемещать файлы с помощью функции move_uploaded_file().

0

Также возможно одновременно загружать несколько файлов и автоматически создавать информацию в массивах для вас. Для этого вам нужно использовать тот же синтаксис представления массива в HTML-форме, что и с несколькими выборами и флажками:

    <form action="file-upload.php" method="post" enctype="multipart/form-data">
      Send these files:<br />
      <input name="userfile[]" type="file" /><br />
      <input name="userfile[]" type="file" /><br />
      <input type="submit" value="Send files" />
    </form>

и вы можете получить данные формы следующим образом:

$_FILES['userfile']['name'][0] , $_FILES['userfile']['name'][1]....

Ссылка ссылки: http://php.net/manual/en/features.file-upload.multiple.php

Ещё вопросы

Сообщество Overcoder
Наверх
Меню