PHP and MySQL image array upload

0

I have the following code:

<?php


if(isset($_FILES['files'])){
    $errors = array();

    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size = $_FILES['files']['size'][$key];
        $file_tmp = $_FILES['files']['tmp_name'][$key];
        $file_type = $_FILES['files']['type'][$key];        
        $file_parts = pathinfo($file_name);//Returns an associative array containing file information       
        $extensions = array("jpeg","jpg","png");//Allowed file

    if($file_size > 2097152){

            echo 'Tamanho do arquivo de ser menor que 2MB';

    }else{

    if(in_array ($file_parts['extension'],$extensions)){

        //Rename file
        $file_parts = ".".$file_parts['extension'];
        $file_name = uniqid().$file_parts;



            if(empty($errors)==true){
            //Move the file to a specific folder    
            move_uploaded_file($file_tmp, "img/".$file_name);   

            }else{
                print_r($errors); 
            }//if(empty($errors)==true){

        }else{

            echo'Extens&atilde;o n&atilde;o permitida';

        }//if(in_array ($file_parts['extension'],$extensions))

    }//if($file_size > 2097152){    

    if(empty($errors)){

        print_r("<pre>".$file_name."</pre>");


    }//if(empty($errors))

    }//foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name)


}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Upload</title>
</head>
<body>
    <form action="" method="POST" enctype="multipart/form-data">
        <input type="file" name="files[]" multiple>
        <input type="submit" value="Enviar">
    </form>
</body>
</html>

My question is, what is better, to create a table in the database for the images, so when I need these images in some form I make one-to-many interaction, or turn the array into a string? >

Do you have another solution too?

    
asked by anonymous 09.09.2016 / 15:05

1 answer

0

I would save everything in a JSON, much faster reading and you can insert keys to link to records too ... being at your discretion, but at first it would only be JSON savvy:

$file = "img/images.json";
$json = json_decode(file_get_contents($file), true);
array_push($json, $file_name);
file_put_contents($file, json_encode($json));

As in this example, json may even be in the same directory as the images, you can increment other image information as needed in the array too ...

    
09.09.2016 / 16:22