Upload PHP and Mysql image array

Asked

Viewed 400 times

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, which is better, to create a table in the database for the images, so when I need these images in some form I do one to many interaction, or turn the array into a string?

Does it have another solution too?

1 answer

0

I would save everything in a JSON, much faster to read and you can insert Keys to link to records also...staying at your discretion, but at first only savaria in JSON same:

$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 can even stay in the same directory as images, you can increment other image information that is required in the array as well...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.