How do I upload an image that can be updated but remains with the same name? [closed]

0

Hello. As the title of the question itself says, I'd like to know how to upload a file in png, jpg or jpeg where its name is always kept as profilepic. in the [DOCUMENT_ROOT] directory / images. How to do this? I have tried to read some tutorials right here from StackOverflow, I have not come to a conclusion. Of course I'm not looking for a ready code, but all the codes point as if there were multiple users with random names etc. Thank you in advance.

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.";
}
}
?>

Errors:

  

(!) 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.

    
asked by anonymous 05.12.2016 / 21:29

2 answers

3

In order to upload, <form> has the attribute enctype="multipart/form-data" and method="POST" , as 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 can be like this (I've used this link check):

<?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 moment of displaying the image there may be a cached version in the user's browser, to avoid you can use querystring as explained in this answer

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 resolve this filemtime like this:

<?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, so it is possible to know the last one from which the file was updated.

Pro Navigator this (this number in front is unixtime that represents April 18, 2016):

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

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

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

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

    
05.12.2016 / 21:55
0

I think there are three solutions to this:

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

  • If there are multiple users, you can use the above logic however by applying to a folder within images thus getting / image / userid / profilepic

  • 05.12.2016 / 21:45