How to upload an image that can be updated but still has the same name?

Asked

Viewed 135 times

0

Hello. As the title of the question already says, I would like to know how to upload a file in png, jpg or jpeg in which your name is always maintained as profilepic. in the directory ['DOCUMENT_ROOT']/images. How to do this? I’ve tried to read some tutorials so far from Stackoverflow, I haven’t come to a conclusion. Evidently I am not looking for a code ready, only that all the codes point as if there were multiple users with random names etc. I thank you already.

My code:

<?php
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/gh-pages/images/profilepic.png';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo "File is not an image.";
    $uploadOk = 0;
}
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "File is too large!";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !="jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
}
?>

Mistakes:

( ! ) Notice: Undefined index: fileToUpload in C: wamp64 www Gh-pages installation uploadprofilepic.php on line 3 Call Stack Time Memory Function Location 1 0.0011 241736 {main}( ) ... uploadprofilepic.php:0

( ! ) Notice: Undefined index: fileToUpload in C: wamp64 www Gh-pages installation uploadprofilepic.php on line 18 Call Stack Time Memory Function Location 1 0.0011 241736 {main}( ) ... uploadprofilepic.php:0

( ! ) Notice: Undefined index: fileToUpload in C: wamp64 www Gh-pages installation uploadprofilepic.php on line 33 Call Stack Time Memory Function Location 1 0.0011 241736 {main}( ) ... uploadprofilepic.php:0

Sorry, there was an error uploading your file.

  • Why not generate a random name and connect it to the user by saving the name generated in the database?

  • My project doesn’t work that well. I don’t have multiple users. I need only one file with an invariable name. also looking for an alternative completely without SQL @Leoletto

  • I think you’re missing an enctype="Multipart/form-data" in your upload form (is this or the file upload is disabled in your php.ini)

2 answers

4

To upload it is necessary that the <form> has the attribute enctype="multipart/form-data" and method="POST", as I explained in:

So for example:

<form action="upload.php" method="POST">
    <input type="file" name="foto_profile">
    <input type="submit" value="Upload">
</form>

The upload might look like this (I used this file type check /a/73497/3635):

<?php

$name = 'profilepic'; //Sem extensão

/*
Troque aqui conforme a necessidade
Se o arquivo de upload estiver na mesma pasta que a pasta
./gh-pages pode fazer isso:

$caminhosite = 'gh-pages/images/';
*/
$caminhosite = 'http://localhost/gh-pages/images/';

$location = $_SERVER['DOCUMENT_ROOT'] . '/gh-pages/images/';
$folderexists = is_dir($location);

function mimeType($file)
{
    $mimetype = false;

    if (class_exists('finfo')) {//PHP5.4+
        $finfo     = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {//php5.3 ou inferiror
        $mimetype = mime_content_type($file);
    }

    return $mimetype;
}

//Tenta criar a pasta se ela não existir
if (!$folderexists) {
    //Usei o 0644 para acaso o servidor seja linux
    $folderexists = mkdir($diretorio, 0644, true);
}

if (!$folderexists) {
    echo 'A pasta não existe e não foi possível cria-la';
} else if (isset($_FILES['foto_profile'])) {
    $tmp_name = $_FILES['foto_profile']['tmp_name'];

    $error = $_FILES['foto_profile']['error'];

    if ($error !== UPLOAD_ERR_OK) {
        echo 'Erro ao fazer o upload:', $error;
    } else {

        $permitidos = array(
            'jpeg', 'png', 'gif'
        );

        $info = mimeType($rowData['imagem']);

        //Transforma image/jpeg em jpeg por exemplo
        $info = str_replace('image/', '', $infos);
        $info = str_replace('x-', '', $infos);

        /*
         * Adiciona extensão ao nome da foto, podendo ficar como:
         * profilepic.jpeg ou profilepic.png ou profilepic.gif
         */
        $name .= '.' . $info;

        if (!in_array($infos, $permitidos)) {
            echo 'O tipo de arquivo enviado é inválido, permitido somente imagens';
        } else if (move_uploaded_file($tmp_name, $location . $name)) {
            echo 'Upload completado, veja a foto<br>';

            $urlfoto = $caminhosite . $name . '?' . filemtime($location . $name);

            echo '<img src="' . $urlfoto . '">';
        } else {
            echo 'Erro ao mover o arquivo';
        }
    }
} else {
    echo 'Selecione um arquivo para fazer upload';
}

Avoiding the cache

At the time of displaying the image there may be a cached version in the user’s browser, to avoid you can use querystring as I explained in this reply

In this format:

http://site.com/images/profilepic.jpg?{unixtime da última atualização da foto}

For example:

http://site.com/images/profilepic.jpg?102992929292

To solve this filemtime thus:

<?php
//Supondo que o caminho seja relativo
$caminho = '/gh-pages/images/profilepic.jpg';
$urlfoto = '/gh-pages/images/profilepic.jpg?' . filemtime($caminho);
?>

<img src="<?php echo $urlfoto; ?>">

Each time you update the file the file incorporates a modification date, this makes it possible to know which last of the file was updated.

Pro browser this (that number on the front is unixtime representing 18 April 2016):

http://site.com/gh-pages/images/profilepic.jpg?1460971238595

It is different from this (represents December 5, 2016):

http://site.com/gh-pages/images/profilepic.jpg?1480971302550

But it will still be the same photo, however each time you upload the proper function will detect the new date and will change the unixtime in querystring.

  • Explain this $camiodosite? Do you mean I have to edit it to match the domain or can I use relative/absolute paths? @Guilhermenascimento

  • 1

    @Mucap this absolute path can be easily exchanged for relative, it will only depend on where this the call from the upload page, then you can exchange this line $urlfoto = $caminhosite . $name . '?' . filemtime($location . $name); by just $urlfoto = $name . '?' . filemtime($location . $name);, actually this $camioabsoluto has nothing to do with the upload, only put to facilitate the understanding of what is "logical" and "http path" ;)

  • Unfortunately, I have errors on lines 53, 56, 57, 65 and 23.

0

I think there are three solutions to this:

  1. If there is only one user: When the user changes the image you would have to delete the current photo and renew the new one with the name profilepic

  2. If there are several users, you can use the logic from above but applying in a folder inside the images thus getting /image/id_do_usuario/profilepic

  3. and last but not least, I don’t know if it applies right to what I said, I could have a file called profilepic.php that would receive the user id as a parameter.

  • 2 and 3 are useless, excuse the expression. A 1, ok, I know delete the image, but how to make the name always the same?

Browser other questions tagged

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