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>";
?>
Related
Re asking how to check if $_POST[FILE] isset
I have a file input and if I submit my form without an image I want something to happen if I uploaded a file in the input I want something different to happen.
if (!isset($_POST[image])) { }
seems to trigger regardless of whether or not I have uploaded a file in the input or not.
<label>
<p>Profile Picture:</p>
<input type="file" name="image" value="" />
</label>
My last question was marked as a duplicate of this answer Check whether file is uploaded however
if (!file_exists($_FILE['image'])) { }
didn't work either it is still showing truthy even when an image is uploaded. So not the answer I need.
To check if there is a file uploaded is you need to check the size of the file.
Then to check if its an image or not is you need to use the getimagesize() function. See my script below:
HTML:
<form action="index.php?act=s" method="post" enctype="multipart/form-data">
<input type="file" name="image" value=""/>
<input type="submit">
</form>
PHP:
<?php
if(isset($_GET['act'])){
// Check if there is a file uploaded
if($_FILES["image"]["size"]>0){
echo "There is a file uploaded<br>";
// Check if its an image
$check_if_image = getimagesize($_FILES["image"]["tmp_name"]);
if($check_if_image !== false) {
echo "Image = " . $check_if_image["mime"] . ".";
} else {
echo "Not an image";
}
}
else{
echo "There is NO file uploaded<br>";
}
}
?>
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.
I would like to have the user upload a pdf to a folder on my website. (note:this is for learning purposes, so security is not necessary) The code I have below does not do echo a response when submitted. The folder I would like to have the pdf uploaded to is in the same directory as the php script, is it possible I'm incorrectly referencing that folder? I appreciate it.
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
Email:<br /> <input type = "text" name="email" value=""/><br />
Resume:<br /><input type = "file" name="resume" value=""/><br />
<p><input type="submit" name ="submit" value="Submit Resume" /></p>
</form>
if(isset($_POST['submit']))
{
define ("FILEREPOSITORY","./resume/");
if (is_uploaded_file($_FILES['resume']['tmp_name'])) {
if ($_FILES['resume']['type'] != "application/pdf") {
echo "<p>Resume must be in PDF Format.</p>";
}
}else {
$name = $_POST['email'];
$result = move_uploaded_file($_FILES['resume']['tmp_name'], FILEREPOSITORY."/$name.pdf");
if ($result == 1) {
echo "<p>File successfully uploaded.</p>";
}
else {
echo "<p>There was a problem uploading the file.</p>";
}
}
}
You have a logical error. Your else statement should be part of the inner if statement -- not the outer one.
would suggest you check the permissions for the upload folder and the max size for file uploading in your php.ini... its happened to me many times uploading a file exceeding the limits and not getting an error message.. also the logic of your if else doesn't match as suggested by your previous post..
IT would be of great help to give the error you receive.
move_uploaded_file()
only works if you have the rights to write to the destination folder.
I am building a php application.
I can easily upload an image or any other type of data, but not a .jar. Below my code:
Upload.php
<form action="getfile.php" method="post" name="uploadForm" id="uploadForm" enctype="multipart/form-data" ><br>
<?php echo gettext("Image "); ?>
<input name="imagen" value="" type="file" id="imagen" />
<?php echo gettext("Jar "); ?>
<input name="jarFile" value="" type="file" id="jarFile" />
</form>
getfile.php
$fileName = $_FILES['jar']['name'];
$fileType = $_FILES['jar']['type'];
//Check the extension
if (!strpos($fileType, "jar") ) {
echo gettext("The simulation must be jar extension. Try again.");
}else{
if (move_uploaded_file($_FILES['jar']['tmp_name'], $path)){
echo gettext("Simulation stored succesfully.");
}else{
echo gettext("Something happened. Try again. ");
}
}
For images I am following the same aproach, but when I try to upload a jar file, I am always getting the error
The simulation must be jar extension. Try again
and $fileType is empty. Is there some restriction at this point? Am I missing something??
Thanks in advance
The type property is unreliable (and populated by the browser). Your best bet is to retrieve the MIME file type:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle, $_FILES['jar']['tmp_name']);
The $mime_type should be application/java-archive.
PHP >= 5.3.0
I can't get any files to upload successfully, it's just going to echo 'error';
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value = "2000000">
Upload this file: <input name ="userfile" type="file">
<input type="submit" value="Send File">
</form>
PHP:
<?php
if ($_FILES['userfile']['error']>0)
{
echo 'Problem.';
exit;
}
$upfile='/uploads/'.$_FILES['userfile']['name'];
if (is_uploaded_file($_FILES['userfile']['name']))
{
if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile))
{
echo 'Problem: could not move file';
exit;
}
}
else
{
echo 'Error';
exit;
}
echo 'File uploaded successfully.';
?>
I'm sure it's something simple I'm messing up, but I've spent about an hour trying to find it. Thanks.
if (is_uploaded_file($_FILES['userfile']['tmp_name']))
tmp_name instead of name
$_FILES['userfile']['tmp_name'] is the name of the uploaded file. $_FILES['userfile']['name'] is just the name that the file had when it was on the computer of the user.
For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the client's machine $_FILES['userfile']['name'] does not work.