Page 1 of 1

Uploading an Image Help

Posted: Mon Apr 10, 2006 5:22 am
by sampage
I'm trying to allow users to upload an image for use as there avatar.

At the moment I have this script, very basic and no limitations on file size or type at the moment!!!

Code: Select all

<?php
if($submit)
{

$_FILES["file"]["name"]="FILEONE";

  echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
  echo "Uploading " . $_FILES["file"]["name"];
  echo " (" . $_FILES["file"]["type"] . ", ";
  echo ceil($_FILES["file"]["size"] / 1024) . " Kb).<br />";
  echo "File is temporarily stored as ". $_FILES["file"]["tmp_name"];

    move_uploaded_file($_FILES["file"]["tmp_name"], 
    "uploads/" . $_FILES["file"]["name"]);
    echo "File has been stored in your uploads directory.";

}
?> 
<html>
<body>

<form action="<? echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
  <p>File Upload</p>
  <input type="file" name="file" id="file" /> 
  <br />
  <input type="submit" name="submit" value="Submit" />
</form> 

</body>
</html>
I need to be able to rename the image so that it matches a users Primary Key before it is saved to the correct folder. I have there primary key in a variable: $user_number.

How do I go about doing this?

Posted: Mon Apr 10, 2006 5:44 am
by phpScott
change

Code: Select all

#
    move_uploaded_file($_FILES["file"]["tmp_name"],
#
    "uploads/" . $_FILES["file"]["name"]);
to

Code: Select all

#
    move_uploaded_file($_FILES["file"]["tmp_name"],
#
    "uploads/" . $user_number);

Posted: Mon Apr 10, 2006 5:51 am
by Oren
Replace line 13 in your code with this code:

Code: Select all

$file_info = pathinfo($_FILES['file']['name']);

    move_uploaded_file($_FILES['file']['tmp_name'], "uploads/{$user_number}." . $file_info['extension']);
Of course this is not the best way and more checks need to be done to ensure that we get the real and correct file type but this is only a general idea and in a real application I will never do this like this without more serious checks.

Edit: What about the file extension phpScott?

Posted: Mon Apr 10, 2006 6:13 am
by s.dot
I wrote an image uploading tutorial. I guess it's in review by the tutorial team, or something.

Posted: Mon Apr 10, 2006 6:39 am
by phpScott
Edit: What about the file extension phpScott?
dope!!

Was just so happy I got to answer a post first I overlooked the simple stuff.

Monday, CSS, X-cart doing my head in.

Posted: Mon Apr 10, 2006 8:22 am
by Oren
LOL... that's ok.