write images to postgresql database with php

Asked

Viewed 786 times

0

I intend to upload images through the browser to a postgresql database using php. I tested with lo_import but it gives me an error indicating that it has to be via superuser on the server side. Any suggestions?

My table:

create table tabela as (id serial unique, imagem oid)
  • Experiment with the lo_import client, not server. In this case, the PHP implementation is pg_lo_import. As large functions server Object Postgresql, when manipulating files in the filesystem, tend to run with Postgres' own OS user permissions, which creates a number of filesystem permissioning problems and the need for PHP to connect as superuser, q is not a good one.

  • have any example? I researched and the examples I found did not work at all, got confused.

1 answer

0


After a lot of head bumping and seeing unclear examples, most copies of the manual are also not very clear, I was able to upload the client image to the database on the server without having the superuser problem in postgresql.

First, send the image to a temporary folder on the server, then take the image in the local folder and click on the database. Complete code:

postgresql

create table testeimg as (id serial unique, imagem oid)

form

<form method="post" enctype="multipart/form-data">         
<input type="file" name="imagem">            
<button formaction="upload.php">UPLOAD</button>                
</form>

upload.php

/* postgresql conexão */
$dbconn = pg_connect("host=localhost port=5432 dbname=teste user=usuario password=pass") or die('Não foi possível conectar: ' . pg_last_error()); 

/* recebe a imagem do formulário, define a pasta de destino, renomeia o arquivo para nome único e envia para a pasta indicada */
define('UPLOAD_DIR', '_tmp/'); 
$img = $_FILES["imagem"]["name"];
$img = str_replace('data:image/jpeg;base64,', '', $img); 
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);

/* pega a imagem na pasta tmp e grava a imagem no banco */
pg_query($dbconn, "begin");
$oid = pg_lo_import($dbconn, '_tmp/'.$data . '.jpg');
$sql1 = "insert into testeimg (img) values('$oid')";
$res1 = pg_query($dbconn,$sql1) or die(pg_last_error($dbconn));
pg_query($dbconn, "commit");

/* elimina a imagem temporária */
unlink(UPLOAD_DIR . $idcliente . '.jpg'); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.