Skip to content
Advertisement

Image/File upload doesn’t work with materializecss framework

I want to create a post creator which works with a database, but I can’t upload an image or a file. My web-page is using the materialize framework. This code is mostly shrunk down to the important parts.

<?php
require_once 'include/Database.php';
require_once 'include/Sessions.php';
require_once 'include/Functions.php';

if (isset($_POST['addPostButton']) || isset($_FILES['image'])) {

    $imageName = $_POST['image'];
    $imageDirectory = 'uploads/' . basename($_FILES['image']['name']);

    if (!move_uploaded_file($_FILES['image']['tmp_name'], $imageDirectory)) {
        $_SESSION['ErrorMessage'] = 'File is invalid!';
    } else {
        global $ConnectingDB;
        $stmt = $ConnectingDB->prepare("INSERT INTO posts(image) VALUES('$imageName')");
        if ($stmt->execute()) {
            $_SESSION['SuccessMessage'] = 'Post created';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Dashboard</title>
    <link type="text/css" rel="stylesheet" href="css/materialize.css">
    <link type="text/css" rel="stylesheet" href="css/styles.css">
</head>
<body>
    <form action="add-post.php" method="post">
        <div class="row">
            <div class="file-field input-field">
                <div class="btn green">
                    <span>File</span>
                    <input type="file" name="image">
                </div>
                <div class="file-path-wrapper">
                    <input type="text" class="file-path" placeholder="Choose an image">
                </div>
            </div>
        </div>
    </form>
</body>
</html>

Advertisement

Answer

From

<form action="add-post.php" method="post">

To

<form action="add-post.php" method="post" enctype="multipart/form-data">

Here need to add a form attribute enctype to send files.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement