1

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> 
user1181690
  • 1,093
  • 2
  • 9
  • 12

4 Answers4

2

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>";
?>
Travesty3
  • 14,336
  • 6
  • 52
  • 95
axiomer
  • 2,060
  • 1
  • 16
  • 26
  • 1
    Not very readable. Instead of a bunch of if-else statements, I would go with something more like `if (/* error condition */) die(/* error message */);`. – Travesty3 Feb 29 '12 at 18:16
  • If I want an alert box, I am guessing that cannot be done by php, only javascript? – user1181690 Feb 29 '12 at 18:16
  • 1
    alert box is javascript. You could change `echo "Not allowed extension";` to `echo "alert('Not allowed extension');";` – axiomer Feb 29 '12 at 18:18
  • Ok thanks, I will use this example and work on it :), I will get back to you if there are any problems. Thank you :) – user1181690 Feb 29 '12 at 18:25
1

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.

Pave
  • 2,119
  • 4
  • 18
  • 22
  • Thought I remembered something about javascript not being able to access the filename from a `file` input type. Maybe that was just in IE or something, but it's still something to think about. – Travesty3 Feb 29 '12 at 18:11
  • My mistake. I remember now that my problem was not being able to initialize it - http://stackoverflow.com/a/5903347/259457 – Travesty3 Feb 29 '12 at 18:18
0

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.

thepip3r
  • 2,523
  • 6
  • 28
  • 32
0

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>";
?>
Travesty3
  • 14,336
  • 6
  • 52
  • 95
  • I am guessing an alert box cannot be done in php, can I ask a quick question, is it bad checking files through client side or doesn't it matter if server side or client side? – user1181690 Feb 29 '12 at 18:19
  • See updated answer for a client-side alert generated by a server-side check. It might be best to check on the server side, because someone else could potentially create a client that uploads files to your server-side script, and their client may not check the file types. – Travesty3 Feb 29 '12 at 18:40