cys
cys

Reputation: 173

Creating link to stored file on server in MySQL

It should be easy to do, but I have no clue even after days of googling.

I've create a simple web form using PHP which allows users to upload image files to server, and the information e.g. date, filename (unique, automatically renamed when uploaded), etc. is input into MySQL table create.

Can I know how to create a link on the 'unique filename' uploaded in MySQL field when displayed, so when user clicked, it will automatically open the server stored file per the unique filename?

Appreciate if anyone can help me on this. Thanks in advance.

Upvotes: 0

Views: 3439

Answers (1)

Lekensteyn
Lekensteyn

Reputation: 66465

Assuming your table contains fields id, type (MIME type) and data (binary data), this is a PHP script for that:

<?php //dispimg.php
//example usage: dispimage.php?id=123
$my = new MySQLi('localhost', 'user', 'pass', 'db');
$sql = sprintf('SELECT type, data FROM table WHERE id="%s" LIMIT 1', $my->real_escape_string($id));
if(!$queryResult=$my->query($sql)){
   //query failed, log mysqli_error() somewhere
}
elseif(!$queryResult->num_rows){
   header('HTTP/1.1 404 Not Found');
   echo 'File not found';
}
else($res=$queryResult->fetch_assoc()){
   //optionally, use application/octet-stream instead of a field from database
   header('Content-Type: '.$res['type']));
   // uncomment following line if you want to present the file as download
   //header('Content-Disposition: attachment;filename=download');
   echo $res['data'];
}
?>

Upvotes: 2

Related Questions