duankua3620 2013-11-30 23:38
浏览 49

具有多个文件上载的PHP表单

I have the following code for a contact form with file upload and it works perfectly, but I don't know how to make it work with multiple file uploads.

The form

<?php
               <form id="formulario" name="formulario" method="POST" action="" enctype="multipart/form-data">                    <p>
                    <label for="nombre">Nombre</label><span class="requerido"></span>
                    <input type="text" name="nombre" id="nombre" size="30" required>
                </p>
                <p>
                    <label for="email">E-mail</label><span class="requerido"></span>
                    <input type="text" name="email" id="email" required>
                </p>
                <p>
                    <label for="ciudad">Ciudad</label><span class="requerido"></span>
                    <input type="text" name="ciudad" id="ciudad" required>
                </p>
                <p>
                    <label for="telefono">Teléfono</label><span class="requerido"></span>
                    <input type="text" name="telefono" id="telefono" required>
                </p>
                <p>
                    <label for="comentarios">Comentarios</label><span class="requerido"></span>
                    <textarea id="comentarios" name="comentarios" cols="30" required></textarea>
                </p>
                <p>
                    <label for="asunto">Subir Foto</label>
                    <input type="file" name="adjunto" id="adjunto" />
                </p>
                <p>
                    <label for="asunto2">Subir Foto</label>
                    <input type="file" name="adjunto2" id="adjunto2" />
                </p>
                <p>
                    <label for="asunto3">Subir Foto</label>
                    <input type="file" name="adjunto3" id="adjunto3" />
                </p>
                <p class="submit">
                    <input type="submit" id="submit" name="submit" class="form-button btn" value="Enviar Consulta" />
                </p>
            </form>
?>

The PHP

<?php

//-------------------------------------------------------------------
// VARIABLES DEL MENSAJE
$comentarios = preg_replace('/
/','<br>',htmlspecialchars(urldecode($_POST['comentarios'])));
$nombre = urldecode($_POST['nombre']);
$email = urldecode($_POST['email']);
$ciudad = urldecode($_POST['ciudad']);
$telefono = urldecode($_POST['telefono']);
$fecha = date('c');

// Título del mensaje
$titulo = "Nuevo mensaje de $nombre desde el formulario de contacto";

// El cuerpo del mensaje
$data = "";


// Definir si es una solicitud AJAX
define('IS_AJAX', isset($_GET['ajax']) && $_GET['ajax'] === 'true');

// Aquí almacenaremos los errores
$errores = array();

// Variables para manejar el adjunto
$hay_adjunto = false;
$adjunto = null;
$boundary = null;

/*
 * Si hay archivos, hay que cambiar el inicio del mensaje y crear un separador (boundary)
 */
if( isset($_FILES['adjunto']) && $_FILES['adjunto']['error'] === 0) {
    $hay_adjunto = true;
    $adjunto = $_FILES['adjunto'];
    $boundary = md5(time());
    $data = "--".$boundary. "
";
    // Y el comienzo del HTML
    $data .= "Content-Type: text/html; charset=\"utf-8\"
";
    $data .= "Content-Transfer-Encoding: 8bit

";
}

/*
 * Comprobaciones de los campos requeridos
 */
if( ! filter_var($email, FILTER_VALIDATE_EMAIL) )
    $errores[] = $mensajes_error['email'];

if( ! isset($_POST['comentarios']) )
    $errores[] = $mensajes_error['comentarios'];

if( ! isset($_POST['nombre']) )
    $errores[] = $mensajes_error['nombre'];

// El mensaje HTML
$data .= "<div class='mensaje'>
        <h1>Nuevo mensaje de $nombre</h1>
        <p><strong>Fecha:</strong> $fecha</p>
        <p><strong>Ciudad:</strong> $ciudad</p>
        <p><strong>Teléfono:</strong> $telefono</p>
        <p><strong>Comentarios:</strong><br>$comentarios</p>
        <p><strong>Email:</strong> <a href='mailto:$email'>$email</a></p>
    </div>";

// Las cabeceras empiezan igual
$cabeceras = "MIME-Version: 1.0
";
$cabeceras .= "From: $nombre<$email>
";
$cabeceras .= "To: $receptor
";

// Si no hay errores probamos a enviar el archivo
if( count($errores) === 0 ) {

    // Content-Type dependiente de si hay adjunto
    if( $hay_adjunto ) {
        $cabeceras .= "Content-Type: multipart/mixed; boundary=\"".$boundary."\"";

        // Si hay archivo
        // También añadimos al cuermo del mensaje un separador 
        $data .= "
";
        $data .= "--" . $boundary . "
";
        // Y el archivo con su correspondiende Content-Type (octet-stream para aplicaciones) y nombre
        $data .= "Content-Type: application/octet-stream; name=\"".$adjunto['name']."\"
";
        $data .= "Content-Transfer-Encoding: base64
";

        // Indicamos que es un adjunto
        $data .= "Content-Disposition: attachment

";

        // Vamos con el adjunto: chunk_split transforma la cadena en base64 en estandar
        $data .= chunk_split(base64_encode(file_get_contents($adjunto['tmp_name']))) . "
";

        // Acabamos el mensaje
        $data .= "--" . $boundary . "--";
    } else {
        // Si no lo hay nos bastará con decir que es un mensaje HTML
        $cabeceras .= "Content-type: text/html; charset=utf-8
";
    }

    // Enviamos nuestro email y damos cuenta si hay algún error
    if(mail($receptor, $titulo, $data, $cabeceras, '-f kharown@gmail.com')) {
        // Si no hay ningún error, lo indicamos con null
        $errores = null;
    } else {
        // Si no indicamos que hubo un error
        $errores[] = "Hubo un error al enviar el e-mail";
    }
}

// Si es una solicitud AJAX, enviamos el JSON y no ejecutamos más código
if( IS_AJAX ) {
    echo json_encode(array(
        'success' => $errores === null,
        'errors' => $errores,
        'has_files' => $hay_adjunto
    ));
    exit;
}
// Si no ahora vendría el documento (index.php)

and the JS

(function(window, document) {
if( ! document.querySelectorAll ) {
    return false;
}

window.ec_form_messages = window.ec_form_messages || { error: {} };
// Abreviar document.getElementById
function $(id){
    return document.getElementById(id);
}
function log() {
    return window.console && console.log(arguments);
}

/*
    Variables para evitar acceder al DOM muchas veces,
    y abreviar
*/
var form = $('formulario'),
    error = $('error'),
    success = $('success'),
    inputs = form.querySelectorAll('input[name], textarea[name], select[name]'),
    elements = {},
    i = 0;

for(; inputs[i]; i++) {
    elements[inputs[i].getAttribute('name')] = inputs[i];
}

function getValue(element) {
    switch(element.nodeName.toLowerCase()){
        case 'input':
            return element.getAttribute('type').toLowerCase() === "file" ? element.files[0] : element.value;
            // No hace falta break; (se ha acabado la funcion)
        case 'select': 
            return element.options[element.selectedIndex].value;
        case 'textarea':
        default:
            return element.value;
    }
}

function getElementsData() {
    var ret = {},
        i;
    // Creamos un objeto con los valores de cada elemento
    for( i in elements ) {
        if( elements.hasOwnProperty(i) ) {
            ret[i] = getValue(elements[i]);
        }
    }
    return ret;
}

// Comprobar e-mail y cadena vacía
function emailVerification(valor){
    // Expresión regular para validar el email (http://stackoverflow.com/questions/46155/validate-email-address-in-javascript)
    // Yo había hecho una propia, pero no estoy en mi ordenador, y esta parece funcionar bien
    var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

    return regex.test(valor);
}
function estaVacio(valor){
    return valor === "";
}

// Función que sucederá cada vez que el formulario se envía
function onsubmit(e){
    var errores = [],
        valores = getElementsData(),
        hasFile;

    e = e || window.event;

    if( ! e.preventDefault ) {
        e.preventDefault = function() {
            e.returnValue = false;
        }
    }

    // comprobamos errores (prefiero mostrarlos normalmente quitando el required)
    if( estaVacio(valores.nombre)){
        errores.push(window.ec_form_messages.error.nombre);
    }
    if( ! emailVerification(valores.email)){
        errores.push(window.ec_form_messages.error.email);
    }
    if( estaVacio(valores.mensaje) ){
        errores.push(window.ec_form_messages.error.mensaje);
    }

    // Si hay errores no enviamos el formulario
    if(errores.length){
        error.innerHTML = '<ul><li>' + errores.join('</li><li>') + '</li></ul>';
        e.preventDefault();
        return false;
    }

    // Si no hay errores, ponemos la lista de errores vacíos
    error.innerHTML = '';

    hasFile = !! valores.adjunto;


    // Si no hay la tecnología necesaria para enviar el formulario con el archivo via AJAX,
    // Lo enviamos via HTTP (dejamos que se ejecute normalmente)
    if( hasFile && ! window.FormData ) {
        return true;
    }

    if( window.FormData ) {
        valores = new FormData(form);
    } else {
        valores = convertirObjeto(valores);
    }

    enviarform(valores, hasFile);

    e.preventDefault();

    return false;
}

// Función mediante la que enviámos el formulario
function enviarform(data, hasFile){
    var request = new window.XMLHttpRequest();

    request.open("POST", '?ajax=true', true);
    if( ! hasFile && ! window.FormData ) {
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    }
    request.onreadystatechange = function(){
        var response;
        if( request.readyState === 4 ){
            response = JSON.parse(request.responseText);
            if( response.errors ){
                return error.innerHTML = "<ul><li>" + response.errors.join("</li><li>") + "</li></ul>"
            }
            // Si está todo correcto mostramos el mensaje y ocultamos el formulario
            correcto.innerHTML = window.ec_form_messages.correcto;
            form.style.display = "none";
        }
    }
    request.send(data);
}

// Convierte un objeto en una cadena de texto preparada para ser enviada al servidor
function convertirObjeto(obj){
    var ret = '',
    key, current = 0;
    for (key in obj){
        ret += ((current === 0 ? '' : '&') + key + '=' + encodeURIComponent(obj[key]) );
        current++
    }
    return ret;
}

/*
    Si no está javascript activado y es un navegador moderno, el navegador comprobará los campos por nosotros
    Si sí lo está, prefiero comprobarlos y mostrar los errores en conjunto.
*/
elements.nombre.required = elements.email.required = elements.mensaje.required = false;
elements.email.type = "text";

// Añadimos el evento cuando el formulario va a ser enviado
form.addEventListener ? form.addEventListener('submit', onsubmit, false): form.attachEvent('onsubmit', onsubmit)

})(window, document, undefined)
  • 写回答

1条回答 默认 最新

  • duandange7480 2013-11-30 23:51
    关注

    Every input field can be accessed by its name after the form was submitted. So just like you accessed the file content of the adjunto field via the $_FILES superglobal array, you can retrieve the contents of the others: $_FILES['adjunto2'], etc.

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?