473,765 Members | 2,035 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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"><in put 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 3236

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"><in put 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_st ring() 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*********@wil lglen.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"><in put type="submit>
What does your <FORM> tag look like? Does it have
ENCTYPE="multip art/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_quot es=get_magic_qu otes_gpc();
$input=parse_in coming();

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

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

if ($HTTP_POST_FIL ES['file']['name'] == "" or
!$HTTP_POST_FIL ES['file']['name'] or $HTTP_POST_FILE S['file']['name'] ==
"none" or $HTTP_POST_FILE S['config']['name'] == "" or
!$HTTP_POST_FIL ES['config']['name'] or
$HTTP_POST_FILE S['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=="a pplication/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_type s\.php/si",$CONFIG_NAM E)) {
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"><in put 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_f ile, 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******@n ews.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"><in put 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
1565
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 be retrived and be displayet ind the 6 text field/area??? can that be done? the user can then edit some of the text and leave some of it unedited..... can it be done??
0
2957
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 programmed in a while so I’m quite lost. Once I have the my database structure I will insert the corresponding fields from a web form but the database is huge and I want to be able to change the database and form without changing the ASP code all the
1
1351
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 that code and get it result its so much urgent please help me thanks in Advance
2
3098
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 "\bank\index.htm" . So what i have to do is, ill get those url and display them in textfields , The problem is , while retriving the url , the backslashes are missing , for some backslashes its generating junk values like box
1
2588
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 it, but while retriving first i have to create a temporary image file for that. and then i m able to retirve it on the web page, but i want it to be directly retrived on the web page.
2
1661
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, Somasundaram G
0
2410
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 trying to do this but running into a problem. I'm hoping someone can point me in the right direction. I first create a class library (all code in C#) and within this class library create a very simple Sql Server Express database (.mdb) file. It's...
6
1533
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 not working now.Can u tell me using link how to retrive the datas. here i pasted my script ---------------------search.php-------------- <form name="form1" method="get"> <table width="200" border="1">
9
19110
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 to do this? Thanks, Sheri sheri@mbproducts.com
0
9568
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9399
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10007
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9957
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9835
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.