Question

I have an upload system which will upload files then record in my database. Anyways it works all fine, though how can i make it so that IMAGES only are uploaded and nothing else?

My code:

if($_POST[add]){



$dataType = $_POST["dataType"];
$title = $_POST["title"];
$fileData = pathinfo(basename($_FILES["image"]["name"]));
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = ("userfiles/profilepic/" . $fileName);

while(file_exists($target_path))
{
    $fileName = uniqid() . '.' . $fileData['extension'];
    $target_path = ("userfiles/profilepic/" . $fileName);
}

if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_path))
{

  $sql = $dbh->prepare("UPDATE users SET `profilepic` = 'userfiles/profilepic/$fileName' WHERE `id` = '".$member["id"]."'");

    $sql->execute();
    $retval = $sql->fetch(PDO::FETCH_ASSOC);

    echo "Your profile picture has successfully been updated";


}
else
{
    echo "oh noes.. there was an error :( Please do try again!";
}

}
Was it helpful?

Solution

Based on this answer

if($_POST[add]){

$file_type = $_FILES['image']['type']; //returns the mimetype

$allowed = array("image/jpeg", "image/gif", "image/png");
if(!in_array($file_type, $allowed)) {
  $error_message = 'Only jpg, gif, and png files are allowed.';

  echo $error_message;

  exit();

}

$dataType = $_POST["dataType"];

... rest of your code below

Footnotes:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top