Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using following code to store images on my webserver:

function SavePic()
{
    $allowedExts = array("jpeg", "jpg");
    $temp = explode(".", $_FILES["UserPic"]["name"]);
    $extension = end($temp);

    if ((($_FILES["UserPic"]["type"] == "image/jpeg")
    || ($_FILES["UserPic"]["type"] == "image/jpg"))
    //&& ($_FILES["UserPic"]["size"] < 2097152)
    && in_array($extension, $allowedExts))
    {
        if ($_FILES["UserPic"]["error"] > 0)
        {
            echo json_encode("Error: ".$_FILES["UserPic"]["error"]);
        }
        else
        {    
            $folder = "/home5/username/public_html/Project/Users/Images/";                
            echo move_uploaded_file($_FILES["UserPic"]["tmp_name"],$folder.$_REQUEST["email"].".".$extension);
        }
    }
    else
    {
        echo json_encode("Invalid file");
    }
}

And Following code to retrieve image:

function RetrievePic()
{
    $handle = fopen('php://input','r');
    $jsonInput = fgets($handle);
    // Decoding JSON into an Array
    $retrieveParameters = json_decode($jsonInput,true);        

    $UserPic = array("UserPic" => "http://www.mysite.com/Project/Users/Images/".$retrieveParameters['email']."."."jpg");
    echo json_encode($UserPic);
}

For Example if my email is [email protected] then image will be stored as "[email protected]". The problem is that when I try to overwrite image in order to replace old one with new one, server is returning old one everytime.

Update: When I place url in browser e.g http://www.mysite.com/Project/Users/Images/[email protected] latest image is shown and after that I start receiving latest image.

share|improve this question
2  
You might want to look at how the webserver is caching your data, you can always add a timestamp to the url (maybe file modified time?) http://www.mysite.com/Project/Users/Images/[email protected]?modifiedtime – hank 42 mins ago
Just like @hank has just written: try $UserPic = array("UserPic" => "http://www.mysite.com/Project/Users/Images/".$retrieveParameters['email']."."."‌​jpg?".time()); – Marcin Krawiec 40 mins ago
1  
@MarcinKrawiec using time() will force a reload every time, which is a waste of bandwidth, better to use the actual modified time of the file. – hank 36 mins ago
@hank yup, you're right. Btw: @ChampTaurus using $_REQUEST["email"] as a filename without any validation is VERY, VERY dangerous. – Marcin Krawiec 33 mins ago

2 Answers

This looks like an caching issue. Did you verify that the new picture is saved correctly on the server?

If the picture is saved correctly, then you should add some headers in the RetrievePic routine to prevent it from being cached. See also: disable cache for some images

share|improve this answer
Yes new picture is being saved on my server. – ChampTaurus 38 mins ago
  • I don't recommend you handle files with its extension. It can be camouflaged easily.
    Also $_FILES['UserPic']['type'] isn't dependable.
  • Under PHP Version 5.4.1, there are serious security holes concerning $_FILES.
    • Directory Traversal Attack
    • $_FILES Collapse Attack

You should do like this:

<?php

// Configure
$upload_key     = 'UserPic';
$max_filesize   = 2097152; // Bytes
$save_directory = '/home5/username/public_html/Project/Users/Images';

if (version_compare(PHP_VERSION, '5.4.1') < 0) {
    die('This PHP Version has serious security hole concerning $_FILES.');
}

if (isset($_FILES[$upload_key])) {

    try {

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

        if (is_array($error)) {
            throw new Exception('This script can\'t accept multiple files');
        }

        switch ($error) {
            case UPLOAD_ERR_INI_SIZE:
                throw new Exception('Exceeded upload_max_filesize');
            case UPLOAD_ERR_FORM_SIZE:
                throw new Exception('Exceeded MAX_FILE_SIZE');
            case UPLOAD_ERR_PARTIAL:
                throw new Exception('Incomplete file uploaded');
            case UPLOAD_ERR_NO_FILE:
                throw new Exception('No file uploaded');
            case UPLOAD_ERR_NO_TMP_DIR:
                throw new Exception('No tmp directory');
            case UPLOAD_ERR_CANT_WRITE:
                throw new Exception('Couldn\'t write data');
            case UPLOAD_ERR_EXTENSION:
                throw new Exception('Extension error');
        }

        $name     = $_FILES[$upload_key]['name'];
        $tmp_name = $_FILES[$upload_key]['tmp_name'];
        $size     = $_FILES[$upload_key]['size'];

        if ($name === '') {
            throw new Exception('Invalid filename');
        }

        if ($size > $max_filesize) {
            throw new Exception(sprintf('Exceeded %d bytes limit', $max_filesize));
        }

        if (!is_uploaded_file($tmp_name)) {
            throw new Exception('Not an uploaded file');
        }

        $finfo = new finfo(FILEINFO_MIME);
        $type = $finfo->file($tmp_name);

        if ($type === false) {
            throw new Exception('Failed to get MimeType');
        }

        if (substr($type, 'image/jpeg') !== 0) {
            throw new Exception('Only JPEG images available');
        }

        if (!isset($_REQUEST['email']) || !is_string($email = $_REQUEST['email']) || $email === '') {
            throw new Exception('E-mail address required');
        }

        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            throw new Exception('Invalid E-mail address');
        }

        $new_name = $save_directory.'/'.$email.'.jpg';

        if (is_file($new_name)) {
            throw new Exception('The file already exists');
        }

        if (!@move_uploaded_file($tmp_name, $new_name)) {
            throw new Exception('Failed to move uploaded file');
        }

        $msg = "File successfully uploaded as {$new_name}";

    } catch (Exception $e) {

        $msg = 'Error: '.$e->getMessage();

    }

} else {

    $msg = 'No file sent';

}

echo json_encode($msg);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.