pruoccojr
pruoccojr

Reputation: 482

Unique file name when uploading using uniqid()

I am trying to upload images from a cell phone and display them on a gallery page. I need each file name to be unique or images will overwrite themselves. I have the following code where $new_image_name is suggested from this topic but I can't seem to get it to work:

if ($_FILES["image"]["error"] > 0) {

    //Bad Output for form results red text
    echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
    echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";

} else {
    $new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
    move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
    $file="images/".$new_image_name);
    $image_title = addslashes($_REQUEST['image_title']);
    $sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
    if (!mysql_query($sql)) {
        die('Error: ' . mysql_error());
    }

    //Good Output for form results green text   
    echo '
     <form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
        <div style="padding:10px;">
            <h2 style="font-size: 28px;">Success!</h2>
            <p style="font-size: 18px;">Your file has been successfully uploaded!</p>
        </div>     
    </form>';
}
mysql_close();

This was my code prior to adding uniqid() which worked fine except the images overwrote each other

    } else {

    move_uploaded_file($_FILES["image"]["tmp_name"],"images/" . $_FILES["image"]["name"]);
    $file="images/".$_FILES["image"]["name"];
    $image_title = addslashes($_REQUEST['image_title']);
    $sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
    if (!mysql_query($sql)) {
        die('Error: ' . mysql_error());
    }

    //Good Output for form results green text   
    echo '
     <form enctype="multipart/form-data" action="insert_image.php" method="post" name="changer">
        <div style="padding:10px;">
            <h2 style="font-size: 28px;">Success!</h2>
            <p style="font-size: 18px;">Your file has been successfully uploaded!</p>
        </div>     
    </form>';
}
mysql_close();

Upvotes: 0

Views: 1701

Answers (2)

Kuya
Kuya

Reputation: 7310

You should really get into the habit of using error checking. As your code sits right now I can upload ANYTHING and your code will save it as a jpg image.

Start by checking to see if the user even selected a file for upload.

Then compare the file type to a predetermined list of allowed file types.

Then save it as the file type that was uploaded. Which may not always be a jpg. As your code sits right now, if I upload a gif or png file... it will save it as a jpg. Thereby rendering the image useless because it is not a jpg.

Your upload process with error checking...

<?php
$FormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $FormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if(isset($_POST["upload"]) && $_POST["upload"] == 'changer') {

// set some basic variables
$fileName = $_FILES["image"]["name"]; // The file name
$fileTempLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$type = strtolower(substr(strrchr($fileName,"."),1));
if($type == 'jpeg' || $type == 'jpe') { $type = 'jprg'; } // make a jpeg or jpe file a jpg file

if (!$fileTempLoc) { // if no file selected
    die ('<div align="center" style="color:#ff0000;"><br /><h3>ERROR: Please select an image before clicking the upload button.<br /><br /><a href="javascript:history.go(-1);">Try again</a></h3></div>');
} else {

// This is the allowed list (images only)
$acceptable = array(
        'image/jpeg',
        'image/jpg',
        'image/jpe',
        'image/gif',
        'image/png'
);

// check to see if the file being uploaded is in our allowed list
if(!in_array($_FILES['image']['type'], $acceptable) && !empty($_FILES["image"]["type"])) { // Is file type in the allowed list
        die ('<div align="center" style="color:#ff0000;"><br /><h3>Invalid file type. Only JPEG, JPG, JPE, GIF and PNG types are allowed.<br /><br /><a href="javascript:history.go(-1);">Try again</a></h3></div>');

} else {

if ($_FILES["image"]["error"] > 0) {

    //Bad Output for form results red text
    echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
    echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";

} else {
    $new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.'.$type;
    move_uploaded_file($_FILES["image"]["tmp_name"],"images/".$new_image_name);
    $file="images/".$new_image_name;
    $image_title = addslashes($_REQUEST['image_title']);
    $sql="INSERT INTO images (name, image, description) VALUES ('','$file','$image_title')";
    if (!mysql_query($sql)) {
        die('Error: ' . mysql_error());
    }

    //Good Output for form results green text   
    echo '
        <div style="padding:10px;">
        <h2 style="font-size: 28px;">Success!</h2>
        <p style="font-size: 18px;">Your file has been successfully uploaded!</p>
        </div>';
mysql_close();
} // end if no errors
} // end if in allowed list
} // end if no file selected
} // end if form submitted
?>

The form...

<form enctype="multipart/form-data" action="<?php echo $FormAction ?>" method="post" name="changer">
<input type="file" name="image" id="image" />
<input name="submit" type="submit" value="Upload">
<input type="hidden" name="upload" id="upload" value="changer" />
</form>

One final note... Do yourself a favor and stop using mysql. Start using pdo_mysql instead. mysql was deprecated in PHP version 5.5 and totally removed in PHP version 7. If you're using mysql code, your code will soon stop functioning completely.

Upvotes: 1

Jitendra Kumar. Balla
Jitendra Kumar. Balla

Reputation: 1213

I am assuming your posted working code, then maybe because of bellow line,

$file="images/".$new_image_name);

You added extra ')' remove that line, it may work fine.

$file="images/".$new_image_name;

Let me know issue is resolved.

Upvotes: 0

Related Questions