How can I change the name of an image when I save the image in a folder and in the database?

0

What I want to know is how to change the name of an image that I will ask in an html form to save its name and extension in the database and the image in a corresponding folder.

What I do not want is that if a user uploads an image with the same name of another one already existing, a conflict is created when it is displayed or made use of.

    
asked by ivanrangel 13.03.2017 в 01:28
source

3 answers

0

The answer that gave @ A.Cedano is excellent to leave. I would advise that always assume that the file already exists, and therefore you have to rename it.

The problem is that if the file mi_imagen.png already exists, you can not just put mi_imagen2.png because first you have to check if mi_imagen2.png exists.

The solution in these cases is to assign a name that can not be repeated. For example, using the timestamp.

    $name = basename($_FILES["imagenes"]["name"][$key]);
    list($base,$extension) = explode('.',$name);
    $newname = implode('.', [$base, time(), $extension];
    move_uploaded_file($tmp_name, "$uploads_dir/$newname");

And in that case your files would be called as mi_imagen.1489403902.png .

According to the proposed solution, the only thing that you would need is to contemplate the case that the name of the file contains a point in between, but that remains as a task for you.

Better than the timestamp would be to use a UUID generator, but the idea is not to complicate things so much.

    
answered by 13.03.2017 / 12:20
source
0

Yes, you do it on the server. Here is the documentation

You can generate a new name, it is used, it depends on the case, the dates the users id and things like that.

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

It would be something like this:

$_FILES['userfile']['name'] //es el nombre original.

$_FILES['userfile']['tmp_name'] //es el nombre que tiene en el servidor

move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfolder.'el_nombre_que_yo_quiera.jpg')//

When I say name I mean the "path" of the file on the server

    
answered by 13.03.2017 в 01:45
0

It would be something like this more or less.

HTML  

 

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

<form method="post" enctype="multipart/form-data" id="subir-imagen" action="enviar_imagen.php">
<input type="file" name="imagenes" id="imagenes" multiple accept="image/x-png, image/gif, image/jpeg, image/jpg" />
<button type="submit" id="btn">Subir Imagenes</button>
</form>
<div id="respuesta"></div>
<ul id="imagenes-lista">
</ul>

 

PHP

This is the PHP to which Ajax will send the image and he will take care of saving it on the server. See PHP Manual

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["imagenes"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["imagenes"]["tmp_name"][$key];
        // basename() puede evitar ataques de denegación de sistema de ficheros;
        // podría ser apropiada más validación/saneamiento del nombre del fichero
        $name = basename($_FILES["imagenes"]["name"][$key]);
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

echo "<h2>Imágenes subidas con éxito</h2>";

Javascript / Ajax

(function () {
var input = document.getElementById("imagenes"), 
    formdata = false;

function showUploadedItem (source) {
    var list = document.getElementById("imagenes-lista"),
        li   = document.createElement("li"),
        img  = document.createElement("img");
    img.src = source;
    li.appendChild(img);
    list.appendChild(li);
}   

if (window.FormData) {
    formdata = new FormData();
    document.getElementById("btn").style.display = "none";
}

input.addEventListener("change", function (evt) {
    document.getElementById("respuesta").innerHTML = "Subiendo . . ."
    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];

        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                    showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("imagenes[]", file);
            }
        }   
    }

    if (formdata) {
        $.ajax({
            url: "enviar_imagen.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                document.getElementById("respuesta").innerHTML = res;
            }
        });
    }
}, false);
}());
    
answered by 13.03.2017 в 03:35