Jump to content

Archived

This topic is now archived and is closed to further replies.

CircularStopSign

renaming file during upload....

Recommended Posts

i've looked all over, but i cant figure out how i would change the file name to a randomly generated name... heres my code so far

[code]
<?php

function createRandomName() {

    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*10000000);
    $i = 0;
    $pass = '' ;

    while ($i <= 7) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }

    return $name;

}

$randomName = createRandomName();




// Where the file is going to be placed
$target_path = "images/";

/* Adding the original filename to my target path. 
Result is "uploads/filename.extension" */
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);

$_FILES['uploadedfile']['tmp_name'];


if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo htmlentities('<a href="http://www.hostmapics.com/"><img src="http://hostmapics.com/');
echo $target_path;
echo htmlentities('"></a>');
} else{
    echo "There was an error uploading the file, please try again!";
}
?>
[/code]

incorperate the random name and how to rename the file just uploaded?

thanks

Share this post


Link to post
Share on other sites
I could be wrong but i would think:

from:
[code]rename("$target_path . basename($_FILES['uploadedfile']['name'])", "$target_path . basename($_FILES['uploadedfile']['name']");[/code]

change this part:
[code]basename($_FILES['uploadedfile']['name']")[/code]

To your randomly generated number / name

Eitherway you can try it beofre someone either confirms or corrects what I've said.

Share this post


Link to post
Share on other sites
wow sorry, that code wasnt supposed to be in there, it doesnt work with the rename function the way i had it... so pretend that isnt in there please, then help me

i will take it out

thanks, pat

Share this post


Link to post
Share on other sites
Same thing still applies, just to a different line

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

reblace the whole basname() part with the generated name.

Off ,e,ory basename gets file_name.ext  or just file_name  from a string like directory/subdirectory/file_name.ext

Just in case you didn't know: directy = the name of a directory ad file_name = a files name and ext = file extension

example:  images/logo.bmp

let me know how it goes coz i'm not the brightest but i like to know when i actually help :D

Share this post


Link to post
Share on other sites
i changed it to "basename($_FILES['randomName']..." then changed the rest of the "uploadedfile" to randomName also, but im guessing that doesnt work because it doesnt recognize the file because from the form i named it "uploadedfile" so i need somehow to change it from uploadedfile to a randomName...? maybe thats not what you were saying?

Share this post


Link to post
Share on other sites

Change to this:

$target_path = " images/";


$target_path = $target_path . $randomName;

Don't use basname for the new name, no need to.

If it fails then post the code as you have it now so i can copy it and play with it.

Share this post


Link to post
Share on other sites
Is all the code in the very frist post the current code?  I have copied it to play with it.

Share this post


Link to post
Share on other sites
Your generator didn't spit out any value, so i am guessing that is where the problem was.

Below is some code that works a treat.

Keep these things in mind
1) This page was called testdelme2.php and it's form submits to itself, with no error checking for it, but just remove the form and name the file what you want or paste the code into an existing file
2) The two pieces of code that are tabbed over really far wouldn't hurt to have as seperate files (includes), infact if you want the generator can do numeric, alhpa-numeric or just alpha strings. If you want the full code just ask
3) The generators code is far larger but it works just fine. (I have a headache and didn't feel like finding the problem with your small code.

Here is the Code, I have saved this file on my machine as well, and tested it ask if you have any Questions (I also have code that will do the same thing for multiple files

CODE:
[code]<form action="testdelme2.php" method="post" enctype="multipart/form-data" name="form1">
  <br>
  <br>
  <input type="file" name="file">
  <br>
  <br>
  <input type="submit" name="Submit" value="Submit">
</form>
<?
//Retrieve the files info
$Fname=$_FILES['file']['name'];
$Ftype=$_FILES['file']['type'];
$Fsize=$_FILES['file']['size'];

//Function to strip the extension of a filename string
function strip_ext($name)
  {
  $ext = strrchr($name, '.');
  if($ext !== false)
  {
  $name = substr($name, 0, -strlen($ext));
  }
  return $name;
  }
 
// This will get the name of the filename:
$FnameName = strip_ext($Fname); //You don't need this line but i left it here in case you wanted it at a later date
// This will get the extension of the filename
$FnameExt= end(explode('.',$Fname));
//Set the Upload Directory
$uploaddir = "images";

/*
###############################################
###    Assigns Values to random numbers    ###
###############################################
*/

function assign_rand_value($num)
{
// accepts 1 - 36
  switch($num)
  {
case "1":
$rand_value = "a";
break;
case "2":
$rand_value = "b";
break;
case "3":
$rand_value = "c";
break;
case "4":
$rand_value = "d";
break;
case "5":
$rand_value = "e";
break;
case "6":
$rand_value = "f";
break;
case "7":
$rand_value = "g";
break;
case "8":
$rand_value = "h";
break;
case "9":
$rand_value = "i";
break;
case "10":
$rand_value = "j";
break;
case "11":
$rand_value = "k";
break;
case "12":
$rand_value = "l";
break;
case "13":
$rand_value = "m";
break;
case "14":
$rand_value = "n";
break;
case "15":
$rand_value = "o";
break;
case "16":
$rand_value = "p";
break;
case "17":
$rand_value = "q";
break;
case "18":
$rand_value = "r";
break;
case "19":
$rand_value = "s";
break;
case "20":
$rand_value = "t";
break;
case "21":
$rand_value = "u";
break;
case "22":
$rand_value = "v";
break;
case "23":
$rand_value = "w";
break;
case "24":
$rand_value = "x";
break;
case "25":
$rand_value = "y";
break;
case "26":
$rand_value = "z";
break;
case "27":
$rand_value = "0";
break;
case "28":
$rand_value = "1";
break;
case "29":
$rand_value = "2";
break;
case "30":
$rand_value = "3";
break;
case "31":
$rand_value = "4";
break;
case "32":
$rand_value = "5";
break;
case "33":
$rand_value = "6";
break;
case "34":
$rand_value = "7";
break;
case "35":
$rand_value = "8";
break;
case "36":
$rand_value = "9";
break;
  }
return $rand_value;
}

/*
###############################################
### GENERATES A RANDOM ALPHA-NUMERIC STRING ###
###############################################
*/

function get_rand_id($length)
{
  if($length>0)
  {
  $rand_id="";
  for($i=1; $i<=$length; $i++)
  {
  mt_srand((double)microtime() * 1000000);
  $num = mt_rand(1,36);
  $rand_id .= assign_rand_value($num);
  }
  }
return $rand_id;
}

//Get a random Alphanumeric value
$randomName = get_rand_id(7);


// Actually Upload the file and rename it
if(is_uploaded_file($_FILES['file']['tmp_name']))
{
move_uploaded_file($_FILES['file']['tmp_name'],$uploaddir.'/'.$randomName.".".$FnameExt);
}
print "<B>".$_FILES['file']['name']." has been stored succesfully as " . $uploaddir . "/" . $randomName . "." .$FnameExt . "</B>";
?>[/code]

Share this post


Link to post
Share on other sites
but wait there is more.

You can remove my generation functions because yours works if you change the line:

    return $name;

to

    return $pass;


...you still need to extension code.  (now it will look less daunting without all the code for my number generation.)

Enjoy, let me know how you go.  Infact your last lot of code should work find because your whole problem was probably that you weren't getting a name generated.

Share this post


Link to post
Share on other sites
alright, thanks a lot that really helped, i'll give you my  code just so you can see it if youd like.
[code]
<?php
$Fname=$_FILES['uploadedfile']['name'];


//Function to strip the extension of a filename string
function strip_ext($name)
  {
  $ext = strrchr($name, '.');
  if($ext !== false)
  {
  $name = substr($name, 0, -strlen($ext));
}
return $name;
}
// This will get the extension of the filename
$FnameExt= end(explode('.',$Fname));

function createRandomName() {

    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*10000000);
    $i = 0;
    $pass = '' ;

    while ($i <= 7) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }

    return $pass;

}

// Usage
$randomName = createRandomName();

//retrieve file name



// Where the file is going to be placed
$target_path = "images";

/* Add the original filename to our target path. 
Result is "uploads/filename.extension" */
$target_path = "images";
$_FILES['uploadedfile']['tmp_name'];



if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path.'/'.$randomName.".".$FnameExt)) {

//show the user their link
    echo htmlentities('<a href="http://www.hostmapics.com/"><img src="http://hostmapics.com/');
    echo $target_path.'/'.$randomName.".".$FnameExt;
    echo htmlentities('"></a>');
} else{
    echo "There was an error uploading the file, please try again!";
}
?>
[/code]

heres what i need to work on now:
-an extension verification script
-use a database or random selection for dir 1-1000 for the images/****/name.ext
what else do i need?

and should i use classes or should i just do everything on this page like i am now?



Share this post


Link to post
Share on other sites
I like to keep things in the same file until I know they work correctly, e.g. I'd now put the functions in a different file and then include them.

Other people may tell you different, I have a mate who includes just about everything, but to me it makes it harder to track while developing and debugging.  Maybe you could open a seperate thread asking about that, suck-in all the answers and find something that suits you.

I am a self taught programmer so a lot of my coding styles have been considered poor. I also would much rather do something over 40 lines and understand it later then do it over 10 lines and not have clue later.

I'll leave the image directory decision up to you, by all means ask if you have a problem though.

As for the extensions verification do mean that for example only certain file types will be accepted? (e.g. .BMP, .JPG, .ZIP anything else like .PDF and .EXE won't be accepted?)

If so then you can use [code]accept="image/jpeg, image/gif"[/code] in the tag for the file prompt.  I have notice that you can still select *.* from the drop down box, if the page allows *.* files though I haven't tested.  I don't know what the types for other extensions will be, but you have a head start on that knowing that "accept" is a valid tag property.

If you're doing images let me know if you ever get around to working out how to resize the actual file itself.  I've had a brief look but got confused and haven't actually tested anything yet as i don't need it.

Let me know if any other queries, or if any other posts on this similar post you started. (as said before happy i can help)

Share this post


Link to post
Share on other sites
for the extensions i just built a simple if statement... i dunno if its safe or w/e but its whati go fo rnow

[code]
if($FnameExt==$ext_array[0] || $FnameExt==$ext_array[1] || $FnameExt==$ext_array[2] || $FnameExt==$ext_array[3] || $FnameExt==$ext_array[4]){


if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path.'/'.$randomName.".".$FnameExt)) {
    echo htmlentities('<a href="http://www.hostmapics.com/"><img src="http://hostmapics.com/');
echo $target_path.'/'.$randomName.".".$FnameExt;
echo htmlentities('"></a>');
}
else{
    echo "There was an error uploading the file, please try again!";
}
}
else{
echo "Not a valid file extension";
}
[/code]

when i get to the directories i am either going to use a database or do a random 1-1000 to pick which folder the image is going in

Share this post


Link to post
Share on other sites
if you have problems with that if...then try replacing the || for OR but you'll need to change the brackets.

I believe || and OR work slightly differently and I've had issues with || before and had to use OR instead, unsure of the situation though.

If you change this is the OR syntax

if ((var1="one") OR (var2="two") OR (IDNumber=1)){


...you have to serperate them with the brackets to work proprerly ...or so I've found......this is only if using OR.

Share this post


Link to post
Share on other sites

×

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.