Jump to content

If Exists, Add "_01"


Recommended Posts

Here is my current code:
[code]<html><form method='post' action='' enctype='multipart/form-data'>
    <input name="MAX_FILE_SIZE" value="999999999999" type="hidden">
      Choose a file to upload
      <input name="uploadedfile" type="file">
      <input name="submit" type="submit" value="Upload">

<?php
//if the file types are bad, display an error
if(eregi('.php$', $_FILES['uploadedfile']['name'])) {
    echo "That File type is not supported.";
}
else
{
//otherwise, upload!
$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. here is the link to your file: <a href='uploads/".  basename( $_FILES['uploadedfile']['name']). "'>".  basename( $_FILES['uploadedfile']['name'])."</a><br>";
    } else{
        echo "Error!";
    }
}
?>
</body> </html>[/code]

I need to make it so that IF the file exists, (example: test.gif) then it adds "_01" (example: test_01.gif). and then if name+_01 exists, delete the _01 and add _02 (example: test_02.gif).

now i know this will be hard because i will have to remove the extention, do that code, and then put it on

can anyone get me started?
Link to comment
Share on other sites

file_exists() http://us2.php.net/file_exists

This isn't exactly the same, but its all I got... Maybe you can work of this instead of adding a number... It does time() in front of the filename if you move that to the end... Maybe it will work for you.
[code]<?php
if(isset($_POST['upload_images'])){
foreach ($_FILES["pictures"]["error"] as $key => $error){
if($error === 0){
$filename = time().$_FILES["pictures"]["name"][$key];
move_uploaded_file($_FILES["pictures"]["tmp_name"][$key], "images/userimages/$filename");
}
}
}
?>[/code]
Thats all I got, Maybe it will help.
Link to comment
Share on other sites

Try this:
[code]
$target_path = "uploads/";
$file = basename( $_FILES['uploadedfile']['name'];
$i = 1;
while (file_exists($target_path . $file)) {
$nfile = ereg_replace('(.*)(\.[a-zA-Z]+)$', '\1_' . sprintf('%02d',$i) . '\2', $file);
$i++;
}
$target_path = $target_path.$nfile;
[/code]
Link to comment
Share on other sites

It's not always possible or desirable to leave the old file intact.  Let's say you were writing an edit feature and allowing the user to replace an image, you certainly wouldn't want an old file hanging around on your webserver if it's not linked to anything in the DB.
Link to comment
Share on other sites

[quote]
haaglin, i tried your code and i get this error:

Parse error: syntax error, unexpected ';' in /website_path/upload.php on line 59
[/quote]
Sorry about that! Forgot to add a ) at the end of a line. try it now:

[code]$target_path = "uploads/";
$file = basename( $_FILES['uploadedfile']['name'] );
$i = 1;
while (file_exists($target_path . $file)) {
$nfile = ereg_replace('(.*)(\.[a-zA-Z]+)$', '\1_' . sprintf('%02d',$i) . '\2', $file);
$i++;
}
$target_path = $target_path.$nfile;[/code]
Link to comment
Share on other sites

ok now it does atleast something:

when it's a file that does NOT exist, it simply times out

if the file DOES exists, it says this:

[quote]Warning: move_uploaded_file(uploads/) [function.move-uploaded-file]: failed to open stream: Is a directory in /website_path/upload.php on line 72
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpYiQ56B' to 'uploads/' in /website_path/upload.php on line 72
There was an error uploading the file, please try again![/quote]
Link to comment
Share on other sites

[quote author=roopurt18 link=topic=115619.msg471045#msg471045 date=1164056666]
It's not always possible or desirable to leave the old file intact.  Let's say you were writing an edit feature and allowing the user to replace an image, you certainly wouldn't want an old file hanging around on your webserver if it's not linked to anything in the DB.
[/quote]

?? I dont know what you are talking about to be honest...
Link to comment
Share on other sites

ok.... yea.... can we focus on my error please? (lol)

when it's a file that does NOT exist, it simply times out

if the file DOES exists, it says this:

[quote]Warning: move_uploaded_file(uploads/) [function.move-uploaded-file]: failed to open stream: Is a directory in /website_path/upload.php on line 72
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpYiQ56B' to 'uploads/' in /website_path/upload.php on line 72
There was an error uploading the file, please try again![/quote]
Link to comment
Share on other sites

Sure thing ;D


Well, you could do something like this: (Note: the code does not check what kind of file is being uploaded!)

ex:

[hr]
[code=php:0]<?php

function unique_filename($dir, $fname) {

$nr = 1;
$fname = preg_replace('/(\.[a-z0-9]{2,4})$/i', "_0{$nr}\\1", $fname);


while(file_exists($dir .'/'. $fname) == true) {

$nr++;

if ($nr < 10) $nr = 0 . $nr;
$fname = preg_replace('/_\d+/', "_$nr", $fname);

}

return $fname;

}






if (isset($_POST['submit'])) {


$folder = "test"; // no trailing slash...
$fname = unique_filename($folder, $_FILES['uploadedfile']['name']);
$path = $folder .'/'. $fname;


if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $path)) {

echo "<p>The file has been successfully uploaded and renamed to: <b>$fname</b></p>";

} else {

echo "Something went wrong!";

}


}

?>

<form method="post" action="" enctype="multipart/form-data">
<input name="MAX_FILE_SIZE" value="999999999999" type="hidden">
Choose a file to upload
<input name="uploadedfile" type="file">
<input name="submit" type="submit" value="Upload">[/code]
[hr]
Link to comment
Share on other sites

Sorry. Must be sleeping or something  :P try this again.

[code]
$target_path = "uploads/";
$file = $nfile = basename( $_FILES['uploadedfile']['name'];
$i = 1;
while (file_exists($target_path . $nfile)) {
$nfile = ereg_replace('(.*)(\.[a-zA-Z]+)$', '\1_' . sprintf('%02d',$i) . '\2', $file);
$i++;
}
$target_path = $target_path.$nfile;[/code]
Link to comment
Share on other sites

ok nicklas, AWESOME job, but unless it uses the blocking of extentions code, i can't use it :/

Hagglin, it displayed that ";" error again, but i noticed that here:
$file = $nfile = basename( $_FILES['uploadedfile']['name'];
you were missing the ")" so i put that in, making this:
$file = $nfile = basename( $_FILES['uploadedfile']['name'][b])[/b];

and now it works almost perfectly!
the only problem is when it displays the file link, it displays the "test.gif" link instead of the "test_01.gif" link.

how do i fix that?
Link to comment
Share on other sites

[quote author=JustinMs66@hotmail.com link=topic=115619.msg471222#msg471222 date=1164078627]
ok nicklas, AWESOME job, but unless it uses the blocking of extentions code, i can't use it :/[/quote]

No, the code I posted does not block anything. But you might want to add some validation to it so you cant upload PHP scripts.

If I would upload a file called [b]nicklas.jpg[/b], the code checks if the file exists, if not, it renames the file to [b]nicklas_01.jpg[/b]. Let´s say I´d upload another picture with the same name, [b]nicklas.jpg[/b], the code checks for the filename and since [b]nicklas_01.jpg[/b] already exists, it renames the new file to [b]nicklas_02.jpg[/b] and so on.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.