Jason Paddle
Jason Paddle

Reputation: 1103

Unable to upload image with php

I am trying to upload an image with php; but seems doesn't work, and I can't figure out why. When I try to insert only text without an image, it is working fine (I mean if I remove from php part all code for the image uploads); so I guess the error is in this part, but I can't find it. This is the upload code that I currently use. Any help with this is appreciated.

if (isset($_POST['add'])) {

$text = $_POST['text'];
$title = $_POST['title'];
$category = $_POST['category'];

$fileName = $_FILES['userfile']['userfile'];
$tmpName = $_FILES['userfile']['tmp_name'];

// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());

// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = "/img/" . $myFile;

    $result = move_uploaded_file($tmpName, $path);

    if (!$result) {
        echo "Error uploading image file <br />";
        var_dump($_FILES);
        exit;
    } else {
        $db = new mysqli("localhost", "user", "mypass", "mydb");

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s<br/>", mysqli_connect_error());
        }
        mysqli_set_charset($db, "UTF8");

        $query = "INSERT INTO posts (post_text, image_name, post_image, post_title, category) VALUES (?, ?, ?, ?, ?)";
        $conn = $db->prepare($query);
        if ($conn == TRUE) {
            $conn->bind_param("ssssi",$text, $myFile, $path, $title, $category);
            if (!$conn->execute()) {
                echo 'error insert';
            } else {

                header("Location: index.php");
                exit;
            }
        } else {
            die("Error preparing Statement");
        }
    }
} else {
   echo 'error';
}

And here is the form for the upload

<form method="post" action="postblog.php" enctype="multipart/form-data">
Title: <input type="text" name="title" id="title">
Category: <select name="category" id="category"> 
Desc :<br />
<textarea id="text" name="text" rows="15" cols="80" style="width: 80%"></textarea>
Image: <input type="file" name="userfile" />
<input type="submit" name="add" id="add" value="Добави">
</form>

The error is from here:

if (!$result) { echo "Error uploading image file
"; }

Upvotes: 1

Views: 150

Answers (1)

Junius L
Junius L

Reputation: 16122

change $fileName = $_FILES['userfile']['userfile']; to $fileName = $_FILES['userfile']['name'];

Upvotes: 1

Related Questions