Saturday, February 24, 2007

Upload files simple function

//
function
upload_files($path)
{
if ($_FILES["file"]["error"] > 0)
{

}
else
{

$name = md5_file($_FILES["file"]["tmp_name"]);
$lenght = strlen($_FILES["file"]["name"]);
$ext = substr($_FILES["file"]["name"],$lenght-4);
if (file_exists($path . $_FILES["file"]["name"]))
{
move_uploaded_file($_FILES["file"]["tmp_name"],
$path . $name.$ext);
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
$path . $name.$ext);
}
}
return $name.$ext;
}
//

In order to call this PHP function you must already have the value of the file object sent to the page where you are calling the function. So, basically you must have a web page that sends that information. the form must contain the enctype="multipart/form-data" in it's content in order to send the file information right.
The input will look like this:


<input type="file" name="file" id="file" />

A textbox and a
Browse Button will appear. You can select your file from there and send it with the form on your page where the function will take the data and upload it.

The function is called like this:

< ?php
upload_files("path_2_save_on_the_server"); ? >

The file will be automatically renamed to it's equivalent in HEX so it will have an unique name :).

2 comments:

Anonymous said...

Hi !

I already made an upload form for dreamweaver. i dont know how to put a link or do i need a script to instruct my form where the visitor can upload/ i read the direction you poster / somehow i dont really get it yet.

cheers,
roy reyes of manila

cy21 said...

Hi,
Yes, you must create a form...
but...as I said:
"he form must contain the enctype="multipart/form-data" in it's content in order to send the file information right." that means that the form must be something like :
< form action="file_that_contains_upload_script.php" action="POST" enctype="multipart/form-data" >

after that you need the:

< input type="file" name="file" id="file" >

and, of course, a submit button
then u can close the form and run the script.

Don't forget that you must specify the path where you want the file to be placed in the script available on the blog.

The name of the file will change into the HEXA equivalent.PHP
something like:
adha345354hjhkh564fgd4asjpou239.php
.
If u need more details, I am here to answer them.

Ciprian