I am setting up a file upload service on my website. Here is what I got so far,
upload.php
<form action="uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<br>
<input type="submit" value="Upload">
</form>
uploader.php
<?php
define("UPLOAD_DIR", "/uploads");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// verify the file is a GIF, JPEG, or PNG
$fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
// file type is not permitted
echo "<p>Unable to save file.</p>";
exit;
}
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
There is a folder in my directory called uploads, I want my files to upload to there.
However when running it using XAMMP, I try and upload a image called example.png and it comes up with the following errors.
Warning: move_uploaded_file(/uploadsexample.png): failed to open stream: Permission denied in C:\xampp\htdocs\assembly\uploader.php on line 37
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpBAE5.tmp' to '/uploadsexample.png' in C:\xampp\htdocs\assembly\uploader.php on line 37
Unable to save file.
If you could help me solve my issue I would be very grateful! thanks.
Add a trailing slash / for
define("UPLOAD_DIR", "/uploads");
^ missing slash
change it to:
define("UPLOAD_DIR", "/uploads/");
Notice the error you got => to '/uploadsexample.png'
and in
Warning: move_uploaded_file(/uploadsexample.png):
^
it's missing a slash after uploads, between uploads and the filename.
Plus, just to be on the safe side, if that still throws you an error that it won't let you upload with another "permission denied" message, make sure that the folder is indeed writeable with proper write permissions set for it.
N.B.:
You may need to modify /uploads/ to uploads/ or ../uploads/ depending on the script's execution location.
Related
i'm trying to upload mp3 format file in to a folder using PHP. But this following coding is not working.Please can some one help my?
define("UPLOAD_DIR", "mp3_upload_folder/");
if (!empty($_FILES["myFile"]))
{
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK)
{
echo "<p>An error occurred.</p>";
exit;
}
// verify the file is a GIF, JPEG, or PNG
$fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$parts = pathinfo($name);
$sanjiv=$_POST['user_id'];
$name= $sanjiv.".".$parts["extension"];
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
This works, and make sure that it has permissions to write to the mp3_upload_folder. I think it's still short of a complete solution, but I am lacking a full view of the problem.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
define("UPLOAD_DIR", "./mp3_upload_folder/");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = $myFile["name"]; //preg_replace("/[^A-Z0-9\.\-]/i", "_", $myFile["name"]); //this is pointless if you're not using it
// don't overwrite an existing file
$parts = pathinfo($name);
$name= $_POST['user_id'].".".$parts["extension"];
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR .$name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="text" value="testUserId" name ="user_id"/>
<input type="file" name="myFile"/>
<input type="submit"/>
</form>
</body>
</html>
Also make sure that you edit your server settings as well as your php settings for uploading file sizes(in the php.ini):
Post_max_size
Upload_max_size (probably your offender default is 2M)
I'm not sure what server you are using, but information can be found easily enough by googling the server type and "max upload size"
I've set up an XAMPP server and trying to upload image files using a custom admin page. The page works fine when I set it up on a online server running ubuntu.
But when trying the same script in localhost gives me the following error.
Warning : move_upload_file(../img/products/fw000001.jpg) : failed to open stream. No such file or directory in C:\xampp\htdocs\OBS\store\kish\bin\functions.php on line 64
Here is the file upload part of functions.php
function upload_image($image,$code)
{
define("UPLOAD_DIR", "../img/products/");
if (!empty($image)) {
$myFile = $image;
if ($myFile["error"] !== UPLOAD_ERR_OK) {
return null;
}
//check if the file is an image
$fileType = exif_imagetype($_FILES["image"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
exit();
}
// ensure a safe filename
$name = $myFile["name"];
$parts = pathinfo($name);
$extension = $parts["extension"];
$savename = $code . "." . $extension;
// don't overwrite an existing file
$i = 0;
if(file_exists(UPLOAD_DIR . $savename)) {
unlink(UPLOAD_DIR . $savename);
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $savename);
if (!$success) {
exit();
}
else
{
return $savename;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
}
I'm not pretty sure about directory separator. Directory separator is represent with (/) on Linux based OS. Widows is using ( \ ) for directory separator. So, please change this line and tested it.
define("UPLOAD_DIR", "../img/products/");
to
define("UPLOAD_DIR", "..".DIRECTORY_SEPARATOR."img".DIRECTORY_SEPARATOR."products".DIRECTORY_SEPARATOR.");
Change this line
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["image"]["tmp_name"],UPLOAD_DIR . $savename);
This is my code for html
<form enctype="multipart/form-data" action="L.CoursePage.php?id=<?php echo $id;?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" /><br>
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" name="upasg">
</form>
This is my php code:
if(isset($_POST['upasg'])) {
//folder to save in
$targetPath = $id."/download/assignment";
if (!is_dir($targetPath)){
mkdir($targetPath);
}
$targetPath = $targetPath . basename($_FILES['uploadedfile']['name']);
$_FILES['uploadedfile']['tmp_name'];
if ($_FILES['uploadedfile']['size'] < 2000) {
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$targetPath)){
echo "The file ". basename($_FILES['uploadedfile']['name'])." has been uploaded.";
} else {
echo "There was an error uploading the file, please try again.";
}
} else {
echo "The file is too big";
}
}
?>
What I'm trying to do is to upload file into different directory when the pageid is different.
For example:
in /L.CoursePage.php?id=1, the file I trying to upload in this page should be save in the 1/download/assignment path.
And I get this error:
Warning: mkdir(): No such file or directory in D:\xampp\htdocs\xampp\foundation\L.CoursePage.php on line 148
Warning: move_uploaded_file(TTT1234/download/assignment1.txt): failed to open stream: No such file or directory in D:\xampp\htdocs\xampp\foundation\L.CoursePage.php on line 153
Warning: move_uploaded_file(): Unable to move 'D:\xampp\tmp\phpBF13.tmp' to 'TTT1234/download/assignment1.txt' in D:\xampp\htdocs\xampp\foundation\L.CoursePage.php on line 153
There was an error uploading the file, please try again.
The error says that PHP does not recognize targetPath, because you forget the $ sign in mkdir(targetPath);
For the uploadedfile index, in your first code you say name="uploaded file" with a space.
These PHP errors are quite explicit :D
Looks like the problem is with construction of $targetPath. You set $targetPath to $id."/download/assignment";. And then you concatenate it with the name of the file:
$targetPath = $targetPath . basename($_FILES['uploadedfile']['name']);
But $targetPath doesn't have a trailing directory separator, so the concatenated string will look like /download/assignmentfilename. Use a directory separator:
$targetPath = $targetPath . '/' . basename($_FILES['uploadedfile']['name']);
I am fairly new to PHP coding, but I am trying to do something that is quite simple.
When someone on my website uploads a picture, the image will get renamed to random numbers and moved to my directory 'uploads/'
In my script below, Everything has been working up until :
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
I have all of the variables defined.
not sure what the problem is here. Should I post my whole script for the uploader?
Here is the form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Choose a file to upload:
<br>(Only .jpg, .png, & .gif are allowed. Max file size = 1MB)</br></p>
<input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>
Here is my 'uploader.php'
<?php
header('Refresh: 3; URL=index.html');
$path = $_FILES['uploadedfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$ran = rand () ;
//This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
$ran2 = $ran.".";
//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 . $ran2.$ext;
$ext = ".".$ext;
$upload_path = "uploads/";
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
?>
You're resetting $filename to the original name of the file, undoing all your random name generation:
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// this line circumvents the random filename generation
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
Given that, I'd expect to see the above error if you upload a file with the same name twice.
Just get rid of that last $filename = .... line and see if your error goes away.
You try to move $_FILES['userfile']['tmp_name'] to another destination, but it seems your file is stored in $_FILES['uploadedfile']['tmp_name'] (as uploadedfile is the name of the file input in your form, and you correctly check it at the beggining of the script).
Also, I'd strongly recommend assigning all variables and using/modifying them in one place, otherwise you are vulenrable to such simple mistakes which are hard to track down.
Here's how I'd re-write your PHP code, it's a bit more clear I think:
<?php
header('Refresh: 3; URL=index.html');
//check if file uploaded correctly to server
if ($_FILES['uploadedfile']['error'] != UPLOAD_ERR_OK)
die('Some error occurred on file upload');
$filename = $_FILES['uploadedfile']['name'];
$uploadedFile = $_FILES['uploadedfile']['tmp_name'];
$ext = '.' . pathinfo($filename , PATHINFO_EXTENSION);
$upload_path = "uploads/";
//prepare random filename
do {
$newName = md5(rand().rand().rand().microtime()) . $ext;
} while (file_exists($upload_path . $newName));
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($uploadedFile) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($uploadedFile, $upload_path . $newName))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed
?>
I just starting upload file with the script in my localhost,
but every time I want to upload file I giving an error:
Warning: chmod() [function.chmod]: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/admin/upload.php on line 5
Warning: chmod() [function.chmod]: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/admin/upload.php on line 6
I guess the problem with permission and path but I don't know how to solve it,
my code:
<?php
define("UPLOAD_DIR",realpath(dirname(__FILE__)).'/uploads' );
// set proper permissions on the new file
chmod(realpath(dirname(__FILE__)).'/uploads', 0777);
chmod(realpath(dirname(__FILE__)).'/uploads/'.$name, 0777);
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
}
?>
chmod(realpath(dirname(__FILE__)).'/uploads', 0777);
chmod(realpath(dirname(__FILE__)).'/uploads/'.$name, 0777);