PHP - 从数据库显示损坏的图像

时间:2017-07-25 18:32:57

标签: php mysql file pdo

每当用户为他们的“个人资料图片”提交图片时,它将显示为“已损坏的图像”,我注意到当我将图像物理插入到mysql数据库并显示它时,它完美地工作并且大小合适该文件更改为“BLOB - KiB”而不是MB。但是当我使用“上传文件”将相同的图像插入数据库时​​,该图像变为“BLOB MB”并且不会显示在网站上。我看到一些关于这个的帖子,他们说要从变量中删除“addslashes”,我这样做但是它仍然没有用。所以我不想做的是显示用户提交的数据库中的图像。它在您没有文件的情况下将其物理插入数据库时​​有效,但如果您使用一个文件将其插入数据库,则它不起作用。以下是数据库结构,上传文件和检索文件的屏幕截图。

this user contributed note

PHP上传文件

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>

检索文件

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 个答案:

答案 0 :(得分:3)

您正在存储临时文件名 - 而不是其内容。

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

应该是

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