How do I upload the image and delete the old one?

Asked

Viewed 90 times

-4

How do I delete old image and upload new image?
The code I’m using uploads, only the old and current image is in the folder...

$novoNome = $img;

if(isset($_POST['edit_profile_avatar']))
{
    if(!empty($_FILES['img']['name']))
    {
    // INICIO UPLOAD IMG
    //INFO IMAGEM
    $file       = $_FILES['img'];
    $numFile    = count(array_filter($file['name']));

    //PASTA
    $folder     = 'upload/users/';

    //REQUISITOS
    $permite    = array('image/jpeg', 'image/png');
    $maxSize    = 1024 * 1024 * 1;

    //MENSAGENS
    $msg        = array();
    $errorMsg   = array(
        1 => 'O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.',
        2 => 'O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário HTML',
        3 => 'o upload do arquivo foi feito parcialmente',
        4 => 'Não foi feito o upload do arquivo'
        );

    if($numFile <= 0)
    {
        /*echo '<div class="alert alert-danger">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        Selecione uma imagem!
        </div>';*/
    }
    else if($numFile >=2)
    {
        echo '<div class="alert alert-danger">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        Você ultrapassou o limite de upload. Selecione apenas uma foto e tente novamente!
        </div>';
    }
    else
    {
        for($i = 0; $i < $numFile; $i++)
        {
            $name   = $file['name'][$i];
            $type       = $file['type'][$i];
            $size       = $file['size'][$i];
            $error  = $file['error'][$i];
            $tmp        = $file['tmp_name'][$i];

            $extensao = @end(explode('.', $name));
            $novoNome = rand().".$extensao";

            if($error != 0)
                $msg[] = "<b>$name :</b> ".$errorMsg[$error];
            else if(!in_array($type, $permite))
                $msg[] = "<b>$name :</b> Erro imagem não suportada!";
            else if($size > $maxSize)
                $msg[] = "<b>$name :</b> Erro imagem ultrapassa o limite de 5MB";

            else
            {

                if(move_uploaded_file($tmp, $folder.'/'.$novoNome))
                {
                    $archive = "upload/users/" .$img;
                    unlink($archive);
                    //$msg[] = "<b>$name :</b> Upload Realizado com Sucesso!";
                }
                else
                $msg[] = "<b>$name :</b> Desculpe! Ocorreu um erro...";
            }
            foreach($msg as $pop)
                echo '';
                //echo $pop.'<br>';
            }
        }
    } // input de img vazio
    else
    {
        $novoNome = $img;
    }

    try
    {
        $atualizarUsuario = $conexao->prepare("UPDATE users SET avatar=:img WHERE id=:id");
        $atualizarUsuario->bindParam(':id', $idUsuario, PDO::PARAM_INT);
        $atualizarUsuario->bindParam(':img', $novoNome, PDO::PARAM_STR);
        $atualizarUsuario->execute();

        if($atualizarUsuario->rowCount() == 1)
        {
            echo '<script language= "JavaScript">
            location.href="/profile/'.$apelidoUsuario.'/avatar-updated";
            </script>';
        }
        else
        {
            echo '<script language= "JavaScript">
            location.href="/profile/'.$apelidoUsuario.'/perfil-updated-error";
            </script>';
        }
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}
  • 1

    The command to delete files is unlink.

  • Preload the current file name and after changing delete it

  • Tip that might explain the negative votes: when asking other people for help, put the minimum possible code to demonstrate his problem. It’s nice to help others, but having to read a lot of stuff that has nothing to do with the problem discourages you a lot and makes you want to press -1 and look for cooler things to solve... This guide is important: http://answall.com/help/mcve

  • @brasofilo I edited the post saying that ta solved already.. 5hours ago and was already solved then I posted the code working.. if anyone wants to see what I’ve changed just click on edited there..

  • Answer the question with the code that solved your problem

  • how do I mark when @brasofilo is solved

  • 2
Show 2 more comments

2 answers

2

In that case, go through POST the old and new image:

$image     = $_POST['nova'];
$image_old = $_POST['old'];

/* Faça upload da nova imagem normalmente */

$clear = unlink($image_old); // apaga imagem antiga
  • I don’t understand.. Look at the code that I edited the topic, it’s already working

-1


$novoNome = $img;

if(isset($_POST['edit_profile_avatar']))
{
    if(!empty($_FILES['img']['name']))
    {
    // INICIO UPLOAD IMG
    //INFO IMAGEM
    $file       = $_FILES['img'];
    $numFile    = count(array_filter($file['name']));

    //PASTA
    $folder     = 'upload/users/';

    //REQUISITOS
    $permite    = array('image/jpeg', 'image/png');
    $maxSize    = 1024 * 1024 * 1;

    //MENSAGENS
    $msg        = array();
    $errorMsg   = array(
        1 => 'O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.',
        2 => 'O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário HTML',
        3 => 'o upload do arquivo foi feito parcialmente',
        4 => 'Não foi feito o upload do arquivo'
        );

    if($numFile <= 0)
    {
        /*echo '<div class="alert alert-danger">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        Selecione uma imagem!
        </div>';*/
    }
    else if($numFile >=2)
    {
        echo '<div class="alert alert-danger">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        Você ultrapassou o limite de upload. Selecione apenas uma foto e tente novamente!
        </div>';
    }
    else
    {
        for($i = 0; $i < $numFile; $i++)
        {
            $name   = $file['name'][$i];
            $type       = $file['type'][$i];
            $size       = $file['size'][$i];
            $error  = $file['error'][$i];
            $tmp        = $file['tmp_name'][$i];

            $extensao = @end(explode('.', $name));
            $novoNome = rand().".$extensao";

            if($error != 0)
                $msg[] = "<b>$name :</b> ".$errorMsg[$error];
            else if(!in_array($type, $permite))
                $msg[] = "<b>$name :</b> Erro imagem não suportada!";
            else if($size > $maxSize)
                $msg[] = "<b>$name :</b> Erro imagem ultrapassa o limite de 5MB";

            else
            {

                if(move_uploaded_file($tmp, $folder.'/'.$novoNome))
                {
                    $archive = "upload/users/" .$img;
                    unlink($archive);
                }
                else
                $msg[] = "<b>$name :</b> Desculpe! Ocorreu um erro...";
            }
            foreach($msg as $pop)
                echo '';
                //echo $pop.'<br>';
            }
        }
    } // input de img vazio
    else
    {
        $novoNome = $img;
    }

    try
    {
        $atualizarUsuario = $conexao->prepare("UPDATE users SET avatar=:img WHERE id=:id");
        $atualizarUsuario->bindParam(':id', $idUsuario, PDO::PARAM_INT);
        $atualizarUsuario->bindParam(':img', $novoNome, PDO::PARAM_STR);
        $atualizarUsuario->execute();

        if($atualizarUsuario->rowCount() == 1)
        {
            echo '<script language= "JavaScript">
            location.href="/profile/'.$apelidoUsuario.'/avatar-updated";
            </script>';
        }
        else
        {
            echo '<script language= "JavaScript">
            location.href="/profile/'.$apelidoUsuario.'/perfil-updated-error";
            </script>';
        }
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}
  • 1

    Gosh, the only difference of this code pro of the question is line 69 that has been removed and does nothing... is a comment: //$msg[] = "<b>$name :</b> Upload Realizado com Sucesso!"; . . . Yes, I circled a diff in both codes...

  • Yes, I removed this, but it was not just that the change I made to work such objective relative to question @brasofilo

  • @brasofilo gave me a question here, how do I define a standard image that cannot be excluded ? I left a default.jpg image there by default and I want it not to be deleted

  • Uai, if(image==default) nao-excluir()? I would leave in another folder that PHP does not touch...

  • @brasofilo I don’t understand..

  • @brasofilo Resolvido = if (Empty($avatarUser)) {$avatarUser = "default.jpg"; }

Show 1 more comment

Browser other questions tagged

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