I have a simple file upload function, but I can't get it to work!
I keep getting and "Error" when trying to use this!
My html-file:
<form enctype='multipart/form-data' action='upload.php'>
<input type='file' name='myfile' />
<input type='submit' value='Upload image' />
</form>
and my upload.php file:
$target = "upload_folder/";
$target = $target . basename( $_FILES['myfile']['name']) ;
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target))
{
echo "The file was uploaded";
}
else {
echo "Error";
}
..this is one of the first times I use this, so I properly did something stupid..
Any suggestions?
You're missing the method attribute in your form. Try adding it:
<form enctype='multipart/form-data' action='upload.php' method="post">
<input type='file' name='myfile' />
<input type='submit' value='Upload image' />
</form>
There are two methods of uploading a file one is via the POST & other is a PUT request. The method your trying to use is POST. Add method="POST" in the form tag and it will work.
Default in forms is to use GET
<form enctype='multipart/form-data' method="POST" action='upload.php'>
<input type='file' name='myfile' />
<input type='submit' value='Upload image' />
</form>
a) File size is too big, you should change this from php.ini
b) Sometimes some servers require a more precise path for move_uploaded_file than "upload_folder/".
Let's say your php file is in the root and you want the files to go to root/upload_folder. Then do this:
$target = realpath(dirname(__FILE__))."/upload_folder";
$target = $target . "/" . basename( $_FILES['myfile']['name']) ;
$target = "upload_folder/";
you need Write permission for target Folder or Directory.
Related
I am facing an issue with the below code, I can upload multiple files but still need that the if condition not be executed till user chooses a file as it is not good to see Unique ID and the echo message run however no files chosen!
PHP
<?php
$path = "Uploads/Files/";
if( (isset($_POST['submit'])) && (!empty ($_FILES['myFile']['name'])) ){
$countfiles = count($_FILES['myFile']['name']);
for($i=0;$i<$countfiles;$i++){
$filename = uniqid(). $_FILES['myFile']['name'][$i];
// Upload file
move_uploaded_file($_FILES['myFile']['tmp_name'][$i], $path.$filename);
echo "<h3> $filename has been uploaded Successfully!</h3>";
}
}
?>
So I want the && part above to be valid as well and not below message to appear till files be chosen.
HTML
<form method='post' enctype='multipart/form-data'>
<input type="file" name="myFile[]" id="file" multiple>
<input type='submit' name='submit' value='Upload'>
</form>
Error:
there are two parts:
add validation for required field <input type="file" name="myFile[]" id="file" multiple required>
render whatever you want instead of echo "<h3> $filename has been uploaded Successfully!</h3>";
Well pretty simple question.. But can't get it right for some reason.
What would be the html code to send a file to this?
move_uploaded_file($FILES["upload"]["tmpname"], $_POST["name"]);
Here's mine but when I used it and echo/vardump everything, I only have 'name' and not the file
<form action="uploader.php" method="post" id="myForm" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="upload" id="upload">
<input type="text" name="name" id="name">
<button name="submit" class="btn btn-primary" type="submit" value="submit">Upload File</button>
</form>
Thank you
i try to add a comment but i can't
first check if upload permission is on in php.ini
file_uploads = On
If it set to on check your upload directory which you added in uploader.php file and use if to check $_FILES['upload'] is empty
this is a simple code to uploader.php file
<?php
if(!empty($_FILES['upload']))
{
$path = "upload/"; /// directory to upload
$path = $path . basename( $_FILES['upload']['name']);
if(move_uploaded_file($_FILES['upload']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['upload']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}else {
echo 'No file selected to upload ';
}
I want to overwrite a file, if it already exists in the folder. Here is my code:
index.php
<form action="check.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" value="upload">Upload</button>
</form>
check.php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
if (file_exists($target_file)) {
echo "File already exist";
echo "<form action='overwrite.php' method='post'>
<button type='submit'> Overwrite</button>
</form>";
}
}
overwrite.php
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
echo "The file is overwritten";
Update: I did a mistake in my question. Now I changed it. On check.php there should only be the statement "File already exists" and a button which directs to the overwrite.php and overwrite the file. (No second input field)
when you are creating the form again you need to specify enctype="multipart/form-data"
echo "<form action='overwrite.php' method='post' enctype='multipart/form-data'>
<input type='file' name='file'>
<button type='submit'> Overwrite</button>
</form>";
without enctype="multipart/form-data"it wont let you perform file upload operation
other than that name should not be a value it should be static so you can use it
You're accessing $_FILES["file"] but, unless $target_file==="file", you're not finding anything.
Change the name attribute of the file upload from $target_file to just file:
echo "<form action='overwrite.php' method='post'>
<input type='file' name='file'>
<button type='submit'> Overwrite</button>
</form>";
Below is my code where the user can upload a file. What I want to know is that is there a way so that via server side is there a way to first of all restrict the file formats of the files to jpeg and png only and then when the user clicks on the submit button, if the file format is correct then display an alert on the same page stating "File is correct" else display an alert stating "File is incorrect".
Can somebody please provide coding if they know how to do this. Thank you and any help will be much appreciated :)
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" 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>
A code for a total check of file uploads, you'll have to change $allowedtypes though. (Copied instead of linking because it was from a non-English site)
<?php
if(isset($_POST["submit"])){
$allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
$filename = $_FILES['file1']['name'];
$source = $_FILES['file1']['tmp_name'];
$file_size=$_FILES['file1']['size'];
$saveloc = "uploads/" . $filename;
$maxfilesize=1024*1024*10;
$nameext=explode(".",$filename);
if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
if($file_size<=$maxfilesize){
if(!file_exists($saveloc)){
if(move_uploaded_file($source, $saveloc)) {
chmod($saveloc,644);
echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
}
else echo "Cannot move";
}
else echo "Existing file";
}
else echo "Too big file";
}
else echo "Not allowed extension";
}
else echo "Only alphanumeric files allowed";
}
else echo "<form method='post' enctype='multipart/form-data' action='secureupload.php'> File: <input type='file' name='file1' /><br /><input
name='MAX_FILE_SIZE' type='hidden' value='10485760' /> <input type='submit' value='Upload' name='submit' /></form>";
?>
You are talking about server side handler and write 'alert'...khm...
If u want to do stuff via server-side, then use php handler
http://php.net/manual/en/features.file-upload.post-method.php
If u want to do stuff via client-side, use javascript events, e.g on change event
<script>
function check() {
var file = document.getElementById('file').value;
var temp = file.split(/\.+/).pop();
alert(temp);
}
</script>
<input type="file" name="file" id="file" onchange="check();" />
You have file extension in temp var.
There are PHP functions to do this. You want to look at mime_content_type and finfo_file. These are built-in PHP commands that allow you to interpret that actual file type of a file being uploaded. You can then filter the mime types to only .gif/.jpg/etc. You want to check the mime types over the file name because the file name can be changed to mask the actual file type. If you want code samples, there are plenty on those pages as well as some excellent user-provided alternatives.
Something like this at the top of your file should work:
<?php
foreach ($_FILES as $file)
{
$tmp = explode(".", $file["tmp_name"]);
if (!in_array($tmp[count($tmp)-1], array("jpeg", "png"), true))
die("<script>alert('File is incorrect');</script>");
}
echo "<script>alert('File is correct');</script>";
?>
Right now i'm using the below method to Upload a file to PHP
<form enctype="multipart/form-data" action="http://sserver.com/fileupload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="hidden" name="filename" value="file_uploaded.gif" />
<input type="hidden" name="username" value="foobar"/>
Please choose a file:
<input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
I read the $_POST and $_FILE in php to complete upload like this.
$target = $_SERVER['DOCUMENT_ROOT']."/test/upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
echo $target;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
My questions is , can i change the above said code (HTML) to an Ajax XMLHttpRequest without changes in PHP.
You cannot send files to the server via AJAX alone. This is because Javascript (when run in a browser) does not have access to the host's file system.
There are ways to make AJAX-style upload boxes using iframes, where the whole page is not reloaded during an upload, but this is not a simple task in itself. jQuery provides a couple of libraries to make this easier.
EDIT As ThiefMaster rightly points out HTML5 provides mechanisms for doing this more neatly.