Where are the phpmyadmin BLOB files stored?

1

I'm doing a program where I send images from any device to my computer's database on phpmyadmin, and it shows me the images in the browser.

I am using the type longblob for the images and the images are saved in .bin format.

I store the images with php in this way:

<?php
    include("conexion.php");

    $nombre = $_POST['nombre'];
    $Imagen = addslashes(file_get_contents($_FILES['Imagen']['tmp_name']));
    $query = "INSERT INTO tabla_imagen(nombre,Imagen) VALUES('$nombre','$Imagen')";
    $resultado = $conexion->query($query);

    if($resultado)
    {
        header("Location: mostrar.php");
    }
    else
    {
        echo "No se inserto";
    }
?>

This is the database where I keep the images:

My doubt is that I want another program to look for and print that image, the problem is:

  • I do not know where those files are stored.
  • If from php or c ++, is it possible to download the images from the database?
  • Any comments are welcome.

        
    asked by José T. 22.05.2017 в 05:04
    source

    2 answers

    1

    The title of your question is ambiguous, but I will try to explain the most appropriate answers.

    Where are the phpmyadmin Blob files stored?

    Obviously they are saved in the tablespace of the table and MySQL database that phpMyAdmin is using.

    In turn, MySQL hosts the information contained in the tables (metadata) in its tablespace innoDB which, by default, is a file called ibdata1 .

    If you have activated the option innodb_file_per_table ( activated by default from MySQL 5.7) the metadata of the table space is saved in a directory with the name of the database using the same name as the table with extension .ibd .

    As all the metadata are saved in the same file (all the files that you upload to the table) it is not possible to access them in a simple and individual way, it is only easy to do it through SQL queries.

    Why%% co_download my file with phpMyAdmin extension?

    .bin knows only the format of the field, phpMyAdmin , and its contents. When you download it, you have no knowledge of the original file name, so it automatically generates one composed of the table name, the text LONGBLOB and the extension blob .

    How can I fix the file download with the original name?

    To perform this task you must first provide a hosting to the file name when it is stored in the database.

    For this you must change the schema and add the file name to the table (you can do it using the "SQL" tab of .bin ):

    ALTER TABLE 'tabla_imagen'
    ADD COLUMN 'nombre_archivo' TEXT DEFAULT ''
    

    By doing this, a new field with phpMyAdmin value will be created for the existing records, so we can fill in an initial value (to facilitate your editing later) as follows:

    UPDATE 'tabla_imagen' SET 'nombre_archivo' = CONCAT(nombre, '.jpg')
    

    I have estimated that the images are NULL , but could be another format or be another type of file, it is up to you to manually modify the name in those you need.

    IMPLEMENTATION: How do I upload a file to keep its name?

    You have to modify the PHP that receives the form to support this:

    <?php
    if (isset($_FILES['Imagen'])) {
        include 'conexion.php';
    
        /* Preparamos la consulta */
        $consulta = $conexion->prepare('
          INSERT INTO tabla_imagen (nombre, Imagen, nombre_archivo)
          VALUES (?, ?, ?)
        ');
        if ($consulta === false) {
            die('Error: ' . $conexion->error);
        }
        /* Asignamos los parámetros: "s"tring, "b"lob, "s"tring */
        $null = NULL;
        $consulta->bind_param(
          'sbs',
          $_POST['nombre'],
          $null, /* Importante con longblog y debe ser variable (por referencia) */
          $_FILES['Imagen']['name']
        );
        /* Importante si es tipo longblob */
        $consulta->send_long_data(1, file_get_contents($_FILES['Imagen']['tmp_name']));
        /* Ejecutamos la consulta */
        if ($consulta->execute() === true) {
          header('Location: mostrar.php');
          die();
        } else {
          die('No se inserto');
        }
    }
    ?><form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">
        <input type="text" name="nombre" />
        <input type="file" name="Imagen" />
        <input type="submit">
    </form>
    

    IMPLEMENTATION: How do I download a file with its original name?

    It is necessary to obtain the file from the database and generate a header that includes that name so that it is understood by the browser and does not save it with the name and extension ( JPEG ) of the script that obtains the image:

    <?php
    include 'conexion.php';
    
    if (isset($_GET['id'])) {
      /* Preparamos la consulta buscando por id */
      $consulta = $conexion->prepare('
        SELECT Imagen, nombre_archivo
        FROM tabla_imagen
         WHERE id = ?
      ');
      if ($consulta === false) {
          die('Error: ' . $conexion->error);
      }
      /* Asignamos la id proporcionada desde el parámetro a la consulta */
      $consulta->bind_param(
        'i',
        $_GET['id']
      );
      /* Realizamos la consulta */
      $consulta->execute();
      /* Almacenamos los datos (importante en el caso del blob) */
      $consulta->store_result();
      /* Asignamos la salida a dos variables */
      $consulta->bind_result($datos, $nombre);
      /* Obtenemos el registro y lo asignamos a las variables */
      if ($consulta->fetch() === false) {
          die('Archivo no encontrado');
      }
      /* Generamos las cabeceras para forzar la descarga de un archivo con nombre */
      header('Content-Type: application/octet-stream');
      /* Enviamos el tamaño de archivo */
      header('Content-Length: ' . strlen($datos));
      /* Limpiamos del nombre de archivo caracteres extraños */
      header('Content-Disposition: attachment; filename="' .
        addslashes(preg_replace('/[^[:alnum:].,\-_ ]/', '_', $nombre)) . '"');
      /* Enviamos al navegador el archivo */
      die($datos);
    }
    /* Mostramos listado de archivos */
    $consulta = $conexion->query('
      SELECT id, nombre, nombre_archivo
      FROM tabla_imagen
    ');
    if ($consulta !== false) {
      while ($resultado = $consulta->fetch_assoc()) { ?>
    <p>
      <a href="<?= $_SERVER['PHP_SELF'] ?>?id=<?= urlencode($resultado['id']) ?>">
        <?= htmlspecialchars($resultado['nombre']) ?>
        (<?= htmlspecialchars($resultado['nombre_archivo']) ?>)
      </a>
    </p>
      <?php }
    } else {
      die('Error: ' . $conexion->error);
    }
    
        
    answered by 24.05.2017 / 09:34
    source
    2

    I do not recommend accessing the archived images directly. It is better to download the images from the database through a client connection. For example, in PHP, you can use ...:

    $statement = $mysqli->prepare("SELECT image FROM images WHERE whatever=?"); 
    $statement->bind_param("i", $image_id);
    $statement->execute();
    $statement->store_result();
    $statement->bind_result($image);
    $statement->fetch();
    

    Now the image is in $image ; you can archive it by file_put_contents() .

    (Please forgive my poor Spanish, I'm still learning ...)

    I added 2017-05-23 : If you want to archive the image, you use code like ...:

    $path = "/Users/johndoe/Desktop/my_image.png"; // replace with your own path
    if (!file_put_contents($image, $path)) {
        echo("Something went wrong.");
    }
    
        
    answered by 22.05.2017 в 11:54