How to upload several images to the server and the database?

1

I am working on a project but I have a problem, what I want to do is register the images uploaded by the user in an individual folder; the code is as follows. '

        <form action="" method="post" enctype="multipart/form-data">
           <label class="w3-label w3-text-brown">Titulo del Reporte:</label>
           <input type="text" class="w3-margin-4 w3-input w3-border w3-sand" name="title" required>
           <label class="w3-label w3-text-brown">Tipo de dan&#771o:</label>
           <select list="tipo" class="w3-select w3-margin-4 w3-border w3-sand" name="tipo" required>
           <datalist id="tipo">
             <option value="" disabled selected>Seleccione una opcion.</option>
             <option value="1">Contaminacion.</option>
             <option value="2">Tala de arboles.</option>
             <option value="3">Maltrato Animal.</option>
             <option value="4">Trafico de animales.</option>
             <option value="5">Incendio Forestal.</option>
             <option value="6">Desperdicio de Agua.</option>
             <option value="7">Otro.</option>
           </datalist>
           </select>
           <label class="w3-label w3-text-brown" title="Para obtener la latitud, ubique en el mapa el lugar del delito.">Latitud:</label>
           <input type="text" style="width:100%;" title="Para obtener la latitud, ubique en el mapa el lugar del delito." id="latitud" class="w3-margin-4 w3-input w3-border w3-sand" name="latitud" value="kdjfd" onfocus="blur();" required>
           <label class="w3-label w3-text-brown" title="Para obtener la longitud, ubique en el mapa el lugar del delito.">Longitud:</label>
           <input type="text" style="width:100%;" title="Para obtener la longitud, ubique en el mapa el lugar del delito." id="longitud" class="w3-margin-4 w3-input w3-border w3-sand"  name="longitud" value="ldkfd" onfocus="blur();" required>
           <label class="w3-label w3-text-brown">Descripcion:</label>
           <textarea class="w3-input w3-border w3-sand w3-margin-4" name="description" required></textarea>
           <label class="w3-label w3-text-brown">Imagenes(<small><i>Si es que las tiene</i></small>):</label>
           <input type="file" name="img1" class="w3-input w3-sand w3-border w3-margin-4">
           <input type="file" name="img2" class="w3-input w3-sand w3-border w3-margin-4">
           <input type="file" name="img3" class="w3-input w3-sand w3-border w3-margin-4">
           <label class="w3-label w3-text-brown">Aque otras instancias a notificado(<small>separe con una coma</small>):</label>
           <input type="text" class="w3-input w3-border w3-margin-4 w3-sand" name="estancias">
           <input type="submit" name="submit" class="w3-btn w3-grey w3-margin-8" value="Enviar Reporte">
           <center><h6><b>Recuerda TU DENUNCIA ES ANONIMA!</b></h6></center>
        </form>

What I want to do is upload the images if a condition is met, and that it is stored in a specific location. this is the php code '

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $title = $_POST['title'];
    $tipo = $_POST['tipo'];
    $lat = $_POST['latitud'];
    $lng = $_POST['longitud'];
    $desc = $_POST['description'];
    //estas son las imagenes que quiero subir
    $img1 = $_POST['img1'];
    $img2 = $_POST['img2'];
    $img3 = $_POST['img3'];
    $estancias = $_POST['estancias'];
    $fecha = date("Y-m-d");


        $caracteres = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //posibles caracteres a usar
        $numerodeletras=10; //numero de letras para generar el texto
        $code = ""; //variable para almacenar la cadena generada
        for($i=0;$i<$numerodeletras;$i++)
        {
            $code .= substr($caracteres,rand(0,strlen($caracteres)),1); /*Extraemos 1 caracter de los caracteres 
        entre el rango 0 a Numero de letras que tiene la cadena */
        }

        $sql = "INSERT INTO reports (code_segui, title, tipo, latitud, longitud, description, img1, img2, img3, estancias, fecha) VALUES ('$code', '$title', '$tipo', '$lat', '$lng', '$desc', '$img1', '$img2', '$img3', '$estancias', '$fecha')";
        if ($conn->query($sql) === TRUE) {
            $dirmake = mkdir("reports/$code", 0777);
            //Quiero que se guarden las imagenes bajo la ruta reports/$code
            //si la condicion se cumple
            header('Location:reports_send.php?c='.$code);
            ob_end_flush();
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

        $conn->close();
}
?>

I hope you can help me

    
asked by OrlandoVC 23.02.2017 в 01:33
source

1 answer

0

I'll leave you a function of php that moves files, images, videos, etc.

     $nameImagen =  $_FILES['getImagen']['name']; // cogemos el nombre de la foto (incluido su extension)
     $url = './img/img_noticias/'.$nameImagen;  //url que se guarda en la base de datos
     $nameImagen = '../../../../../img/img_noticias/'.$nameImagen; // url donde se guardan las imagenes

     if (move_uploaded_file($_FILES['getImagen']['tmp_name'], $nameImagen)){
        echo "El archivo ha sido cargado correctamente.";

     }else{
        //Notificacion de que el error es en la foto.
        echo "Ocurrió algún error al subir la foto. No pudo guardarse";
     }
}

I'll explain:

  

$_FILES ['nombre en el formulario']['name];

You are collecting the name of the file (AND ITS EXTENSION) from the client side (form)

  

$url = './img/img_noticias/'.$nameImagen;

This variable goes directly to the database. In my case I make the connection from the root, so put this route.

  

$nameImagen = '../../../../../img/img_noticias/'.$nameImagen;

In this variable we will put the route where we want to save the image that we have collected. (TAKE INTO ACCOUNT THAT IT IS FROM WHERE THIS PHP CODE YOU ARE EXECUTING).

  

move_uploaded_file($_FILES['getImagen']['tmp_name'], $nameImagen

With this PHP function we tell you to move the file / image / etc. to the route that we have indicated in $nameImagen .

    
answered by 23.02.2017 / 12:37
source