File upload - change file name

Hi,

I’m sure there are thousands of things I should be doing to this code to check that the file extension is correct, check that the size is small enough etc and I’d appreciate any advice, however right now I’m trying to change the name of the file uploaded to one that fits into my system.

$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}

At the moment the file uploads fine however it keeps the original file name. I want to change it to a string of letters and numbers which are in a variable called $newFileName, but I want to keep the same file extension.

I’d also later like to limit it to only image file formats (jpg, gif, png I guess) and limit it to 100k maximum size, plus any other checks I should be doing before uploading files to my server. If anyone can help with this as well that would be lovely, but the file name is my main issue right now.

Cheers :slight_smile:

You can do something like this:


<?php
if (isset($_POST['submit']))
{
    $img = "uploads/" . basename($_FILES['uploadedfile']['name']);
    $t = 1;
    while (file_exists($img))
    {
        $img = substr($img, 0, strpos($img, ".")) . "-$t" . strstr($img, ".");
        $t++;
    }
    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $img))
    {
        echo "The file " . basename($_FILES['uploadedfile']['name']) .
            " has been uploaded";
    }
    else
    {
        echo "There was an error uploading the file, please try again!";
    }
}
?>
<form action="test.php" method="post" enctype="multipart/form-data">
<p>
  <b>Choose photo:</b>
    <input name="uploadedfile" type="file" /><br />
    <input type="submit" name="submit" />
    <input type="reset" />
</p>
</form>

or


<?php
function random()
{
    $r = array_merge(range('A', 'Z'), range('a', 'z'));
    $tmp = array();
    for ($i = 0; $i < 5; $i++)
    {
        $tmp[] = $r[array_rand($r)];
        $tmp[] = mt_rand(0, 9);
    }
    shuffle($tmp);
    return join($tmp);
}
$t = random();
if (isset($_POST['submit']))
{
    $img = "uploads/" . basename($_FILES['uploadedfile']['name']);
    $img = substr($img, 0, strpos($img, ".")) . "-$t" . strstr($img, ".");
    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $img))
    {
        echo "The file " . basename($_FILES['uploadedfile']['name']) .
            " has been uploaded";
    }
    else
    {
        echo "There was an error uploading the file, please try again!";
    }
}