-1

I am building a profile picture uploader and have a question. how would I go about changing the file name uploaded to the current session user_id + the current date.

My session variable is $_SESSION['user_id'];

Is there a way to rename the file they uploaded smiling_cat.jpg to 2_11102014.jpg while keeping the extention it has?

This is what i currently have.

<?php 
if (isset($_POST['submit']))
{
$path = '/home/marketplace/public_html/imgupload/profile_pic/';
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$upload_exts = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($upload_exts, $file_exts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// move files to the path
move_uploaded_file($_FILES["file"]["tmp_name"], $path . $_FILES["file"]["name"]);

//echo a bunch of data to use at a later time
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br><hr>";
echo "<div class='sucess'>"."Stored in: " . $path . $_FILES["file"]["name"]."</div>";
echo '<img src="profile_pic/'.$_FILES["file"]["name"].'">';
}
}
else
{
echo "<div class='error'>Invalid file</div>";
}
}
?>
Brian Cherdak
  • 105
  • 2
  • 16
  • 1
    Tried anything? All I see is *"My session variable is `$_SESSION['user_id'];`"* but no related code in your code. If something failed, show us what it is. – Funk Forty Niner Nov 11 '14 at 03:23
  • 1
    See http://stackoverflow.com/questions/18705639/how-to-rename-uploaded-file-before-saving-it-into-a-directory – Nikhil Agarwal Nov 11 '14 at 03:25
  • Thanks @NikhilAgarwal, one more little issue, after I finish the form, it gives this notice: **Strict Standards: Only variables should be passed by reference in /home/marketplace/public_html/imgupload/index.php on line 19** line 19 is **$upload_exts = end(explode(".", $_FILES["file"]["name"]));** Any reason it would be doing that? – Brian Cherdak Nov 11 '14 at 03:37

1 Answers1

1

You can do that with this:

$ext = explode(".", $_FILES["file"]["name"]);

move_uploaded_file($_FILES["file"]["tmp_name"], $path . "whatever".end($ext));

BTW you should check the operation

if(!move_uploaded_file($_FILES["file"]["tmp_name"], $path . "whatever".end($ext))){
    //deal with error
}
else{
    //rest of your code
}