This is the upload form
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploaded" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
And this is the php:
<?php
$keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for ($i = 0; $i < 10; $i++) {
$photoID .= $keys[rand(0, strlen($keys)-1)];
}
//add a dot (.) to the randomly generated string so the ext can be applied to it later
$photoID2 = $photoID.".jpg";
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "uploads/";
//This combines the directory, the random file name, and the extension
$target = $target . $photoID2.$ext;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) {
echo "The file has been uploaded as ".$photoID2.$ext;
} else {
echo "Error: upload did not work";
}
?>
The problem I have is that i keep getting the error upload did not work... what am I doing wrong here ? it's really basic something that I am missing but i need to understand it because I can already do file uploads fine but want to understand how it works...
First:
make sure that there is a directory with the name uploads
second:
Try to give the suitable permissions to the directory using chmod like
chmod -R 777 /path/to/the/directory
Use below code for renaming a uploaded file
$name = $_FILES['Fixtures']['uploaded']['name'];
$tmp_name = $_FILES['uploaded']['tmp_name'];
$target_path = "images/uploads/";
$extension = end(explode('.', $name));
$randomName = 'thumbnail_' . rand(123456, 1234567890) . '.' . $extension;
/* Add the original filename to our target path.
Result is "images/uploads/filename.extension" */
$target_path = $target_path . basename($randomName);
$allowedImageTypes = array("image/jpeg", "image/jpg", "image/png", "image/x-png", "image/gif");
if (in_array($type, $allowedImageTypes)) {
move_uploaded_file($tmp_name, $target_path) or die("error in thumbnail upload!");
}
This will upload all the files with renaming the files
Check the folder permissions of uploads/ if it's writeable for apache.
And try to set the error reporting so move_uploaded_file
can tell you what's wrong.
I think I will settle with this solution, it makes more sense to me, the move_uploaded_files is the one that puts it in the directory and gives it the name.
<?php
//create random file name
$keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for ($i = 0; $i < 7; $i++)
{
$key .= $keys[rand(0, strlen($keys)-1)];
}
//get the extension
$ext = basename( $_FILES['uploaded']['type']);
//choose destination, add filename and extension
$target = "uploads/" .$key. "." . $ext;
//move the file to the des
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>