image output from the database

You need to output the image stored in the database (using wamserver).

It is saved to the database, you can even download it, and the format is images-image_data.bin, but it is not output.

If you change:

header('Content-type: '. $image['mime_type']);

On:

header('Content-type: image/*');

Then the browser will prompt me to download my file showImages.php.

If you completely comment out header, then a bunch of characters will be displayed on the screen (I understand that this is my image).

What should I do change it in the code so that the image is displayed in the browser?

Here is the code:

Index.html -registration form

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Форма регистрации</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <form class="content" action="regUser.php" method="POST" enctype="multipart/form-data">
        <div class="entryField">
            <label for="firsName">Ваше имя:</label>
            <input type="text" name="first_name">
        </div>

        <div class="entryField">
            <label for="SecondName">Ваша фамалия:</label>
            <input type="text" name="second_name">
        </div>

        <div class="entryField">
            <label for="pass">Пароль:</label>
            <input type="text" name="pass">
        </div>

        <div class="entryField">
            <label for="email">Емаил</label>
            <input type="text" name="email">
        </div>

        <div class="entryField">
            <input type="hidden" name="MAX_FILE_SIZE" value="200000">
            <label for="userPic">Аватар</label>
            <input type="file" name="userPic" size="30">
        </div>

        <div class="entryField">
            <label for="bio">Биография</label>
            <textarea name="bio" id="" cols="30" rows="10"></textarea>
        </div>

        <div class="entryField">
            <input type="submit" value="Регистрация">
        </div>
    </form>
</body>
</html>

RegUser.php -processing of sent data

        <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>обработка данных</title>
    </head>
    <body>
        <?php
        //подключение к БД
        require_once 'connectBD.php';

        ($_REQUEST) or
            handle_error("вы не ввели данные", mysql_error());

        $first_name = $_REQUEST['first_name'];
        $second_name = $_REQUEST['second_name'];
        $pass = $_REQUEST['pass'];
        $email = $_REQUEST['email'];
        $bio = $_REQUEST['bio'];
        $img_file_name = "userPic";

        //потенциальные ошибки отправки файла
        $php_errors = array(1 => 'Превышен максимальный размер файла',2 => 'превышен максимальный размер файла в HTML', 3 => 'Была отправлена только часть файла', 4 => 'Файл для отправки не был выбран');

        //проверка отсутствия ошибок при отправки изображения
        ($_FILES[$img_file_name]['error'] == 0)
            or handle_error("сервер не может получить выбранное изображение",$php_errors[$_FILES[$img_file_name]['error']]);

        //проверка формата файла
        @getimagesize($_FILES[$img_file_name]['tmp_name'])
            or handle_error("файл не является изображением","функция сработала");   

        //вставка изображения в таблицу
        $image = $_FILES[$img_file_name];
        $image_filename = $image['name'];
        $image_info = getimagesize($image['tmp_name']);
        $image_mime_type = $image_info['mime'];
        $image_size = $image['size'];
        $image_data = file_get_contents($image['tmp_name']);

        $insert_image_sql = sprintf("INSERT INTO images (filename, mime_type, file_size, image_data) VALUES ('%s','%s',%d,'%s');",
                            mysql_real_escape_string($image_filename),
                            mysql_real_escape_string($image_mime_type),
                            mysql_real_escape_string($image_size),
                            mysql_real_escape_string($image_data));

        mysql_query($insert_image_sql) or
            handle_error("ошибка загрузки изображения",mysql_error());

        $insert_sql = sprintf("INSERT INTO users (first_name, last_name, pass, email, bio, profile_pic_id) VALUES ('%s','%s','%s','%s','%s',%d);",
                            mysql_real_escape_string($first_name),
                            mysql_real_escape_string($second_name),
                            mysql_real_escape_string($pass),
                            mysql_real_escape_string($email),
                            mysql_real_escape_string($bio),
                            mysql_insert_id());

        mysql_query($insert_sql) or
            handle_error("ошибка записи пользователя",mysql_error());

        // перенаправление пользователя на страницу профиля
        header("Location: showUsers.php?user_id=". mysql_insert_id());
        ?>
    </body>
    </html>

ShowImage.php -separate page for getting the image

       <?php
    // подключение БД
        mysql_connect("localhost","root","") or 
            handle_error("Ошибка подключения к базе данных",mysql_error());
        mysql_select_db("testBd") or
            handle_error("Ошибка выбора базы данных",mysql_error());


                if(!isset($_REQUEST['image_id'])) {
                    handle_error("не указано изображения для загрузки.","");
                }

                $image_id = $_REQUEST['image_id'];

                $select_query = sprintf("SELECT * FROM images WHERE image_id = %d",$image_id);
                $result = mysql_query($select_query);

                if (mysql_num_rows($result) == 0) {
                    handle_error("не удалось найти изображение", "изображение с ID {$image_id} не найдено");
                }

                $image = mysql_fetch_array($result);

                //загрузка изображения
                header('Content-type: '. $image['mime_type']);
                header('Content-length: ' . $image['file_size']);
                echo $image['image_data'];

            ?>

ShowUsers.php - data output

    <!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <title>Ваш профиль</title>
</head>
<body>
    <?php
    //подключение к БД
    require_once 'connectBD.php';

    if(!isset($_REQUEST['user_id'])) {
            handle_error("не указан пользователь.","");
        }

    $userId = $_REQUEST['user_id'];
    $select_user = "SELECT * FROM users WHERE user_id = " . $userId;
    //mysql_query("SET NAMES utf8"); принудительно меняем кодировку
    $result = mysql_query($select_user);

    if ($result) {
        $row = mysql_fetch_array($result);
        $first_name = $row['first_name'];
        $second_name = $row['last_name'];
        $email = $row['email'];
        $bio = $row['bio'];
        $image_id = $row['profile_pic_id'];

    }   else {
        handle_error("возникла ошибка с поиском вашей информации","ползователь с ID {$userId} не найден");
    }

    ?>
    <h1>Добро пожаловать <?php echo "{$first_name}"; ?></h1>    
    <div class="content">
        <h2>профиль</h2>
        <p class="leftCont borderBot"><?php echo "{$first_name} {$second_name}"; ?></p>
        <div class="clear leftCont">
            <img src="showImage.php?image_id=<?php echo $image_id; ?>" alt="фото">
            <p class="bio leftCont"><?php echo "{$bio}"; ?></p>
        </div>
        <p class="leftCont">связаться с пользователем:</p>
        <ul><li><?php echo "{$email}"; ?></li></ul>
        <a class="buttonBack" href="index.html">Назад</a>
    </div>
</body>
</html>

Database images table images table

Table users enter a description of the image here

Author: aleksandr barakin, 2015-07-31

2 answers

In the header, it is desirable to specify correct format: Content-type: image/формат.

Follow the example from of this answer.


Update

And the error is in the way the array elements are accessed.

You get an ordinary array:

$image = mysql_fetch_array($result);

And then you refer to its elements not by numbers, but by names, as to the elements of the associative array:

$image['mime_type']
$image['file_size']
$image['image_data']

For such a request, you need to create an associative array using the function mysql_fetch_assoc():

$image = mysql_fetch_assoc($result);
 1
Author: aleksandr barakin, 2017-05-23 12:39:15

Thank you for your help, but it did not solve the problem:) In general, I was tired of all this and I decided to put the good old denwer instead of wampserver and lo and behold, everything worked. Don't know what specifically didn't like wamp(maybe due to the fact that there is a newer version of php). ps on the page of reqUsers.php I accidentally stuck the html blocks, that denwer was yelling because on that page uses header(), and wamp somehow missed this moment(and so did I also). Thank you again for helping me!

 0
Author: Алексей, 2015-08-01 07:30:23