0

Every time a user submits a picture for their "profile pic" it will display as a "broken image" and I noticed that when I physically insert an image into the mysql data base and display it, it works perfectly and the size of the file changes to "BLOB - KiB" instead of MB. But when I insert that same image into the database using my "upload file", that image turns to "BLOB MB" and doesn't display on the website. I saw some post about this and they said to remove the "addslashes" from the variable and i did that but it still didn't work. So what i wan't to do is display the image from the database that was submitted by the user. It works when you physically insert it into the database without a file but if you do it with one, it doesn't work. Here is a screen shot of the database structure, upload file, and retrieving file.

enter image description here

PHP Upload file

session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post') { //catch file overload error...
    $postMax = ini_get('post_max_size'); //grab the size limits...
    echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
    return $postMax;
}
if(isset($_COOKIE['username'])) {
    if($_SESSION['came_from_upload'] != true) {
        setcookie("username", "", time() - 60 * 60);
        $_COOKIE['username'] = "";
        header("Location: developerLogin.php");
        exit;
    }
    error_reporting(E_ALL & ~E_NOTICE);
    if($_SERVER['REQUEST_METHOD'] == "POST") {
        $token = $_SESSION['token'];
        $userid = $_SESSION['id'];
        $fullname = addslashes(trim($_POST['fullname']));
        $username = addslashes(trim($_POST['username']));
        $email = addslashes(trim($_POST['email']));
        $password = addslashes(trim($_POST['password']));
        $storePassword = password_hash($password, PASSWORD_BCRYPT, array(
            'cost' => 10
        ));
        $file_tmp = addslashes(trim($_FILES['file']['tmp_name']));
        $file_name = addslashes(trim($_FILES['file']['name']));
        try {
            // new php data object 
            $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
            //ATTR_ERRMODE set to exception
            $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e) {
            die("There was an error connecting to the database");
        }
        $stmtChecker = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = ?");
        $stmtChecker->execute(array(
            $userid
        ));
        if($result = !$stmtChecker->fetch()) {
            setcookie("username", "", time() - 60 * 60);
            $_COOKIE['username'] = "";
            header("Location: developerLogin.php");
            exit;
        }
        if(!empty($fullname)) {
            $stmtFullname = $handler->prepare("UPDATE generalusersdata SET fullname = ? WHERE user_id = ?");
            $stmtFullname->execute(array(
                $fullname,
                $userid
            ));
        }
        if(!empty($username)) {
            $stmtCheckerUsername = $handler->prepare("SELECT * FROM generalusersdata WHERE username = ?");
            $stmtCheckerUsername->execute($username);
            if($resultCheckerUsername = $stmtCheckerUsername->fetch()) {
                die("Username Already in use! Please try again");
            }
            $stmtUsername = $handler->prepare("UPDATE generalusersdata SET username = ? WHERE user_id = ?");
            $stmtUsername->execute(array(
                $username,
                $userid
            ));
        }
        if(!empty($email)) {
            if(filter_var($email, FILTER_VALIDATE_EMAIL) == false) {
                die("Email is Not Valid!");
            }
            $stmtCheckerEmail = $handler->prepare("SELECT * FROM generalusersdata WHERE email = ?");
            $stmtCheckerEmail->execute($email);
            if($resultCheckerEmail = $stmtCheckerEmail->fetch()) {
                die("Email Already in use! Please try again");
            }
            $stmtEmail = $handler->prepare("UPDATE generalusersdata SET email = ? WHERE user_id = ?");
            $stmtEmail->execute(array(
                $email,
                $userid
            ));
        }
        if(!empty($password)) {
            if(strlen($password) < 6) {
                die("Password has to be GREATER than 6 characters!");
            }
            //Check if password has atleast ONE Uppercase, One Lowercase and a number
            if(!preg_match("(^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$)", $password)) {
                echo 'Password needs to be at least ONE uppercase, ONE lowercase, and a number!';
                exit;
            }
            $stmtPassword = $handler->prepare("UPDATE generalusersdata SET password = ? WHERE user_id = ?");
            $stmtPassword->execute(array(
                $storePassword,
                $userid
            ));
        }
        if($_FILES['file']['error'] == UPLOAD_ERR_OK) {
            $mime = mime_content_type($_FILES['file']['tmp_name']);
            if(strstr($mime, "video/")) {
                die("Please note that this file is NOT an image... Please select an image for your Profile Picture");
            } else if(strstr($mime, "image/")) {
                $allowedTypes = array(
                    IMAGETYPE_PNG,
                    IMAGETYPE_JPEG
                );
                $detectedType = exif_imagetype($_FILES['file']['tmp_name']);
                if($extensionCheck = !in_array($detectedType, $allowedTypes)) {
                    die("Failed to upload image; the format is not supported");
                }
                $dir = "devFiles/";
                $uploadedFile = $dir . basename($_FILES['file']['name']);
                if(is_dir($dir) == false) {
                    mkdir($dir, 0700);
                }
                if(!move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile)) {
                    die("There was an error moving the file... Please try again later!");
                }
                $stmtFile = $handler->prepare("UPDATE generalusersdata SET profile_image = ?, file_tmp = ? WHERE user_id = ?");
                $stmtFile->execute(array(
                    $file_name,
                    $file_tmp,
                    $userid
                ));
            }
        }
        $_SESSION['token'] = $token;
        header("Location: developerUpload.php");
        exit;
    }
} else {
    header("Location: developerLogin.php");
    exit;
}

HTML

<form method="post" enctype="multipart/form-data" autocomplete="off">
    Information Changer<br>
    Fullname: <input type="text" name="fullname" placeholder="Full Name.....">
    <br/>
    <br/>
    Username: <input type="text" name="username" placeholder="User Name.....">
    <br/>
    <br/>
    Email: <input type="text" name="email" placeholder="Email.....">
    <br/>
    <br/>
    Password: <label><input type="password" name="password" placeholder="Password....." ></label>
    <br></br>
    Profile Picture: <input type="file" name="file">
    <br/>
    <input type="submit" name="submit">
</form>

Retrieving file

try {
    // new php data object
    $handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
    //ATTR_ERRMODE set to exception 
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    die("There was an error connecting to the database");
}
$stmt = $handler->prepare("SELECT * FROM generalusersdata WHERE user_id = :userid");
$stmt->bindValue(':userid', '61', PDO::PARAM_INT);
$stmt->execute();
while($result = $stmt->fetch()) {
    echo '<img src="data:image/jpeg;base64,' . base64_encode($result['file_tmp']) . '"/>';
}
1
  • You're using prepared statements with placeholder values, which is the proper way to do it, but you're also adding addslashes on top of that which will mangle your data and break things.That method should not be used in this code, it just causes chaos. Commented Jul 25, 2017 at 18:41

1 Answer 1

3

You are storing the temporay filename - not its contents.

$file_tmp = addslashes(trim($_FILES['file']['tmp_name']));

Should be

$file_tmp = file_get_contents($_FILES['file']['tmp_name']);
Sign up to request clarification or add additional context in comments.

4 Comments

Ohhh wow i thought that was the way you store the content. Thank you and if i can ask another quick question, when i use "getPath()" for the "directoryIterator" and echo it, it gives me the actual path of an image in the directory. But i want to take the image not the path and submit to database. Is that possible?
Oh so i just get the path and set it equal to a variable like "$test = file_get_contents($path)" ?and then submit into database?
Yep, when storing an image to a database you are actually storing the contents of the image-file. So you need a way to retrieve that contents (where file_get_contents is the most convenient way).
I am trying it for my other upload file but its not working, for this one i have a "for loop" and when i put "$file_tmp = file_get_contents($_FILES['file']['tmp_name'])[$key];" it gives me an error "file_get_contents() expects parameter 1 to be a valid path, array given"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.