Hi
markosar200294,
I would like to upload my files in a different directory that html_plublic or tmp.
The secret is to move the uploaded file to your destination folder before the end of the script. PHP deletes the temporary upload after execution, so you just have to move it if you want to keep it. Doing it this way, allows you some control over what’s being uploaded.
Allowing users to upload files this way is easy but it opens very big security risk. Make sure only authorized users have access to it, and restrict as much as you can what is to be uploaded. Remember that you are the one responsible for what’s in your site.
For this example you will need to create 2
folders in your /public_html/
In the file_upload place this
form.html code:
HTML:
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
In the same folder create
upload_file.php:
PHP:
<?php
//Set the path relative to script location
$destination_path = "../materials/";
//Some restrictions to the file upload
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists($destination_path . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
$destination_path . $_FILES["file"]["name"]);
echo "Stored in: " . $destination_path . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Go to your browser and open
http://www.batepapoworkshops.x10.mx/file_upload/form.html and upload a small gif image. It will end up on
http://www.batepapoworkshops.x10.mx/materials/
Tested this on my free hosting (server: chopin) and it works with no problems.
Code source and more information:
http://www.w3schools.com/php/php_file_upload.asp