Wednesday, October 6, 2010

php: upload file- with same name from client to server

HTML CODE:
-------------------------------------------------------------------------------


Choose a file to upload:



-------------------------------------------------------------------------------
PHP CODE
=============================================
PHP Code:

$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!";
}

=============================================
Here is a brief description of the important parts of the above code:

* enctype="multipart/form-data" - Necessary for our to-be-created PHP file to function properly.
* action="uploader.php" - The name of our PHP page that will be created, shortly.
* method="POST" - Informs the browser that we want to send information to the server using POST.
* input type="hidden" name="MA... - Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example.
* input name="uploadedfile" - uploadedfile is how we will access the file in our PHP script.

Save that form code into a file and call it upload.html. If you view it in a browser it should look like this:
-----------------------------------------
The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example.

* uploadedfile - uploadedfile is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with.
* $_FILES['uploadedfile']['name'] - name contains the original path of the user uploaded file.
* $_FILES['uploadedfile']['tmp_name'] - tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.

Now we can finally start to write a basic PHP upload manager script! Here is how we would get the temporary file name, choose a permanent name, and choose a place to store the file.