0

Hey guys,

I have a form with fields and a file upload input which saves the uploaded file to a folder (/images), adds some random numbers to the filename and inserts the filename into a mysql DB.

I'm just not sure how to add file type validation into this form.

Could someone please help me?

Here is my code for handling the file upload:

    // Image Upload Script

    $uploadDir = 'images/'; //Image Upload Folder
    if(isset($_POST['submit'])) {

    $fileName = ( rand(1, 999).rand(1000,9999 ).rand(1, 999)."_". $_FILES['photo']['name']);
    $tmpName = $_FILES['photo']['tmp_name'];
    $fileSize = $_FILES['photo']['size'];
    $fileType = $_FILES['photo']['type'];
    $filePath = $uploadDir . $fileName;

    $result = move_uploaded_file($tmpName, $filePath);
    if (!$result) {
    echo "Error uploading file";
    exit;
    }
    if(!get_magic_quotes_gpc())
    {
    $fileName = addslashes($fileName);
    $filePath = addslashes($filePath);
    }
    }

Then insert the filename into the database:

    // Insert data into mysql
    $sql="INSERT INTO $tbl_name(photo)VALUES('$filePath')";
    $result=mysql_query($sql);

Thank you.

Edited by dnbmadness

2
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by diafol
0

Thanks for your reply, so how would I incoorperate file extensions in this? For example, if I only wanted to allow these file formats... jpg, jpeg, png, gif.

Thanks again.

0

Maybe something like this:

$fileparts = pathinfo($fileName);
$ext = strtolower($fileparts['extension']);

$allowed_ext = array("jpg","jpeg","png","gif");
if(in_array($ext,$allowed_ext)){
  //run code
}

Edited by diafol

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.