473,385 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Putting/retriving files into a database

Hello, its been a while since I posted/looked here... my normal email client
doesn't handle newsgroups :( (ximian evolution)

I was wondering how you stick a file into a database, and then retrive it
again for the user with PHP/MySQL. I tried the following which apparently
didnt work...

Very quick overview of what I did...

html
------
<input type="file" name="file"><input type="submit>
PHP
------
$SQL = "INSERT INTO table (file) VALUES (" + $_REQUEST['file'] + ");";

I didn't even bother running the SQL querry, I just echoed it and I got the
location of the file (ie: /home/eric/blah...)

How do I get the file into the database, and once its there, how do i get it
back out?
Thanks,
-Eric Kincl
Jul 17 '05 #1
4 3216

On 9-Nov-2003, Eric Kincl <Er**@Kincl.net_NO_SPAM_> wrote:
I was wondering how you stick a file into a database, and then retrive it
again for the user with PHP/MySQL. I tried the following which apparently
didnt work...

Very quick overview of what I did...

html
------
<input type="file" name="file"><input type="submit>
PHP
------
$SQL = "INSERT INTO table (file) VALUES (" + $_REQUEST['file'] + ");";

I didn't even bother running the SQL querry, I just echoed it and I got
the
location of the file (ie: /home/eric/blah...)

How do I get the file into the database, and once its there, how do i get
it
back out?


1) Open the uploaded file with fopen() if it's binary, specify 'rb' instead
of 'r'
2) Read the contents of the file into a variable with fread()
3) Close the file with fclose()
4) Use mysql_escape_string() to make the contents of variable work in in the
insert statement
5) insert the contents of variable into the table with an insert sql
statement, be sure the column is a blob type.

to get it out
1) select the db row containing the data you want
2) use fopen() to create a file
3) use fwrite() to write the contents of the appropriate column to the file
4) use fclose() to close the new file.

see
http://www.php.net
http://www.mysql.com
--
Tom Thackrey
www.creative-light.com
tom (at) creative (dash) light (dot) com
do NOT send email to ja*********@willglen.net (it's reserved for spammers)
Jul 17 '05 #2
Eric Kincl <Er**@Kincl.net_NO_SPAM_> writes:
I was wondering how you stick a file into a database, and then retrive it
again for the user with PHP/MySQL. I tried the following which apparently
didnt work...
Have you looked at the chapter in the PHP manual entitled "Handling
File Uploads"?

http://www.php.net/manual/en/features.file-upload.php
Very quick overview of what I did...

html
------
<input type="file" name="file"><input type="submit>
What does your <FORM> tag look like? Does it have
ENCTYPE="multipart/form-data"?
PHP
------
$SQL = "INSERT INTO table (file) VALUES (" + $_REQUEST['file'] + ");";

I didn't even bother running the SQL querry, I just echoed it and I got the
location of the file (ie: /home/eric/blah...)
I suspect that you didn't specify ENCTYPE correctly or at all in
your <FORM> tag. If you had, then $_REQUEST['file'] shouldn't be
set all; instead, $_FILES['file'] should have the info you're looking
for. See the aforementioned chapter on handling file uploads for
details.

Also, *never* put user-supplied input (e.g., form data) in an SQL
statement without first making sure it's sanitized. See the Security
chapter in the PHP manual for more information, and pay particular
attention to what it says about SQL Injection in the "Database
Security" section. Even on a private server that the Bad Guys can't
get to, it's a good idea to use good programming habits so they'll
be familiar if you ever have to work on a public-facing application.

http://www.php.net/manual/en/security.index.php
How do I get the file into the database, and once its there, how do i get it
back out?


You have to get the file's contents before you can insert them into
the database. Study the "Handling File Uploads" chapter in the PHP
manual and post a follow up if it doesn't answer your questions.

Once you learn how to get the file's contents, you can store them
in a database with an INSERT statement (making sure to sanitize the
data) and retrieve them with a SELECT query. If you continue to
have problems, then please post a small but complete sample of your
code so we can see what you're doing.

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/
Jul 17 '05 #3
You need to make sure you get the content of the file properly first,
see the other replies on detials of how to do this.

I will normally base64_encode a file before putting it into the database
just to make sure that it doesn't corrupt other bits of the database.

to output, just grab the file from the database, decode (if needed) and
output to browser.

Note that it's normally pretty useful to store the incoming Mime-Type of
the data in the database if your accepting more than one type of file so
that you can output the correct headers.

On another note, make sure you watch when uploading files, Mozilla etc
have a few quirks when uploading files.

Here's an extract from one of my recent scripts that handle file uploads.

-- BEGIN --
$get_magic_quotes=get_magic_quotes_gpc();
$input=parse_incoming();

if ($input['act']=='do')
{

if (is_array($HTTP_POST_FILES['config']))
{
$CONFIG_NAME = $HTTP_POST_FILES['config']['name'];
$CONFIG_SIZE = $HTTP_POST_FILES['config']['size'];
$CONFIG_TYPE = $HTTP_POST_FILES['config']['type'];
$CONFIG_TYPE = preg_replace( "/^(.+?);.*$/", "\\1", $CONFIG_TYPE );
$CONFIG_FILE = $HTTP_POST_FILES['config']['tmp_name'];
if (is_array($HTTP_POST_FILES['file'])) {
$FILE_TYPE = $HTTP_POST_FILES['file']['type'];
$FILE_TYPE = preg_replace( "/^(.+?);.*$/", "\\1", $FILE_TYPE );
}

if ($HTTP_POST_FILES['file']['name'] == "" or
!$HTTP_POST_FILES['file']['name'] or $HTTP_POST_FILES['file']['name'] ==
"none" or $HTTP_POST_FILES['config']['name'] == "" or
!$HTTP_POST_FILES['config']['name'] or
$HTTP_POST_FILES['config']['name'] == "none" ) {
die("you must include files in both upload fields");
}
}
else
{
die("you must include files in both upload fields");
}

if ($FILE_TYPE=="" || !$FILE_TYPE)
{
die ("Your file must be less than 2Mb in size!");
}

/*if ($FILE_TYPE=="application/octet-stream") {
die("Your browser did not provide a suitable mime-type for this type
of file.<br /><br />However, your conf_mime_types.php should hold a
default entry that will allow you to upload this file.");
}*/
if (!preg_match("/^conf_mime_types\.php/si",$CONFIG_NAME)) {
die("Your config file MUST be named conf_mime_types.php");
}
$allow_upload=$input['allow_upload']? 1 : 0;
$allow_avatar=$input['allow_avatar']? ",1": "";
if ((!$input['image']) || (!$input['desc'])) die("You forgot to enter
an image name or a description");
$line=" \"$FILE_TYPE\" => array ( $allow_upload,
'{$input['image']}', '{$input['desc']}' $allow_avatar) ,";
$file=join(file($CONFIG_FILE));

--END--

Though the way I handle the file here ( $file=join(file($CONFIG_FILE)) )
is a crude way of doing things, but was best for the job at hand.

Eric Kincl wrote:
Hello, its been a while since I posted/looked here... my normal email client
doesn't handle newsgroups :( (ximian evolution)

I was wondering how you stick a file into a database, and then retrive it
again for the user with PHP/MySQL. I tried the following which apparently
didnt work...

Very quick overview of what I did...

html
------
<input type="file" name="file"><input type="submit>
PHP
------
$SQL = "INSERT INTO table (file) VALUES (" + $_REQUEST['file'] + ");";

I didn't even bother running the SQL querry, I just echoed it and I got the
location of the file (ie: /home/eric/blah...)

How do I get the file into the database, and once its there, how do i get it
back out?
Thanks,
-Eric Kincl


Jul 17 '05 #4
Hi Eric,
Might I recommend that you skip putting the binary data in the database
altogether?

If you'd like the files to be easily searchable, put the location of the
file and any metadata (upload time, uploader, author, etc) into the
database, and store the file in a plain old filesystem. Since the data is
binary, it can't be usefully searched in the database anyway. You can store
the file using move_uploaded_file, using some naming scheme to store the
file, and then write that filename into the database.

This will save you a lot of heartache dealing with addslashes and
stripslashes in PHP as well as making for one less field to verify against
SQL injection Attacks.

Hope that's helpful,

Eric

"Eric Kincl" <Er**@Kincl.net_NO_SPAM_> wrote in message
news:3f******@news.gvsu.edu...
Hello, its been a while since I posted/looked here... my normal email client doesn't handle newsgroups :( (ximian evolution)

I was wondering how you stick a file into a database, and then retrive it
again for the user with PHP/MySQL. I tried the following which apparently
didnt work...

Very quick overview of what I did...

html
------
<input type="file" name="file"><input type="submit>
PHP
------
$SQL = "INSERT INTO table (file) VALUES (" + $_REQUEST['file'] + ");";

I didn't even bother running the SQL querry, I just echoed it and I got the location of the file (ie: /home/eric/blah...)

How do I get the file into the database, and once its there, how do i get it back out?
Thanks,
-Eric Kincl

Jul 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: jeghers | last post by:
i have a page where info can be inserted in a form that consists of some textarea and some textfield. but when i get to the page, i want the last inserted info, which is saved in a database, to...
0
by: Pato Secruza | last post by:
Hi everyone! I have a really frustrating error and need help. I’m trying to do a function that gets the properties and names of the fields in a MS Access database using ASP. I haven’t...
1
by: Mian Mahboob | last post by:
Hi in my application i need to save C sharp syntax to SQL Server database then need to call that on Windows UserControl then execute that code and get there output. all i done accept to execute...
2
by: balakrishnan.dinesh | last post by:
Hi frnds, Im having a problem with retriving "\" backslash , In my javascript client side page , ill get the response from the server side , the response will contain some url like...
1
by: Kunal Nandi | last post by:
can any one give me the code for uploading and retriving image using Blob, with jsp at front end and oracle8i at the back end ??????? i have tried this using long raw datatype i was able to upload...
2
by: soma.gunasekaran | last post by:
Hi All , I've stored the Image file..... But i want to retriving the Image files from MSACCSS 2003 (JPEG,bmp,Gif and etc....) So Pls help me........ help me............... Thanking you,...
0
by: drawing in aspnet | last post by:
Question about putting the data layer in a separate class library. I keep reading that the data layer should be separated from the presentation layer and put in its own class library. I am...
6
by: kavithadevan | last post by:
Hi, I am trying to retriving some datas from the database.using submit button i am getting result but i inserted one submit image and i gave link to that image and then i run that script but its...
9
by: sheri | last post by:
Hi need your expert advice. I want to put my access database online so different users in my company can use it. I can put in on a secure directory on my website. Can you direct me the best way...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.