|
Subject:
|
upload files
|
|
Posted By:
|
joeore
|
Post Date:
|
2/7/2004 7:04:43 PM
|
how can upload files (images in this case)in mysql databse with php?
|
|
Reply By:
|
richard.york
|
Reply Date:
|
2/8/2004 8:37:59 PM
|
Hi Joeore,
1.) Set up a field containing a unique ID 2.) Set up a BLOG field for the file data. 3.) Set up a VARCHAR mime type field if you will be storing more than one type of file.
Optional.. add fields for file name or other details.
Basically you need to extract the binary data from the file using a few PHP functions, addslashes, file will be kept in a normal variable, and then inserted like you would insert any other type of data.
// Read the contents of the file into a variable, addslashes for DB insertion // where 'userfile' is the name of the upload field // file_get_contents PHP 4 >= 4.3.0
$file = addslashes(file_get_contents($_FILES['userfile']['tmp_name'])); $mime = $_FILES['userfile']['type'];
if (false === ($query = mysql_query("INSERT INTO `files` VALUES(null, '{$file}', '{$mime}')"))) { echo 'insertion failed'; }
Here is another method which does the same as the above: // Read the contents of the file into a variable, addslashes for DB insertion. $file = addslashes(fread(fopen($_FILES['userfile']['tmp_name'], 'r'), filesize($_FILES['userfile']['tmp_name'])));
The following is what you do to retrieve the contents of the file:
<?php // if passing the ID via GET if (isset($_GET['id'])) { $id = $_GET['id']; }
// get_file.php // Make SELECT query $data = mysql_fetch_array(mysql_query("SELECT `file`, `mime` FROM `files` WHERE `id` = '{$id}'"), MYSQL_ASSOC);
// Set the content type header header('Content-type: {$data['mime']}');
// Also notice that I am not stripping the slashes, // Doing so may corrupt data in certain file types, // while you may need to do so for others. echo $data['file']; ?>
Then simply include a link to the PHP file... For images, <img src='get_file.php?id=5' />
Be extra careful about resource consumption here, it may be both more efficient and practical to simply store the file in a directory file system!
: ) Rich
::::::::::::::::::::::::::::::::: Smiling Souls http://www.smilingsouls.net :::::::::::::::::::::::::::::::::
|
|
Reply By:
|
nikolai
|
Reply Date:
|
2/9/2004 12:03:54 AM
|
"BLOG" type, eh Rich? =)
(I think he meant "BLOB"...)
Take care,
Nik http://www.bigaction.org/
|
|
Reply By:
|
richard.york
|
Reply Date:
|
2/9/2004 1:13:05 PM
|
HaHa! Yes I meant BLOB.
: ) Rich
::::::::::::::::::::::::::::::::: Smiling Souls http://www.smilingsouls.net :::::::::::::::::::::::::::::::::
|
|
Reply By:
|
joeore
|
Reply Date:
|
2/9/2004 5:31:16 PM
|
thank you..but..i'm not very expert in php..can you tell me an example?:)..
joeore
|
|
Reply By:
|
richard.york
|
Reply Date:
|
2/9/2004 7:09:21 PM
|
Joeore,
1.) Set up the MySQL table
CREATE TABLE `files` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT , `file` MEDIUMBLOB NOT NULL , `mime` VARCHAR( 50 ) NOT NULL , PRIMARY KEY ( `id` ) );
2.) Write HTML/PHP
Basically only two fields are required to upload a file, a 'file' input field, and a 'MAX_FILE_SIZE' hidden field.The latter isn't really required, but will prevent the user from trying to upload a file that is too large on the client-side.This can be easily circumvented by the user and should be accompanied by server-side file validation.It accepts a file size in Bytes, I have set this to accept a file of 10000 bytes, or roughly 10KB.And one attribute *must* appear in the form tag to get the browser to upload data, enctype='multipart/form-data'.
The following should be pretty straight forward.It has been tested and works for me!
<?php
//upload2db.php
if (!isset($_POST['do_action']))
{
echo "<html>\n",
" <head>\n",
" <title>UPLOAD TO DATABASE</title>\n",
" </head>\n",
" <body>\n",
" <form action='{$_SERVER['PHP_SELF']}' method='post' enctype='multipart/form-data'>\n",
" <input type='file' name='userfile' />\n",
" <input type='hidden' name='MAX_FILE_SIZE' value='10000' />\n",
" <input type='submit' name='do_action' value='Upload' />\n",
" </form>\n",
" </body>\n",
"</html>";
}
else
{
if (isset($_FILES['userfile']['tmp_name']))
{
if (($_FILES['userfile']['size'] <= 10000) && ($_FILES['userfile']['type'] == 'image/jpeg' || $_FILES['userfile']['type'] == 'image/pjpeg'))
{
// Make a database connection here!
$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('test', $link);
// file_get_contents() PHP >= 4.3.0
$file = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
// If using PHP < 4.3.0 use the following:
// $file = addslashes(fread(fopen($_FILES['userfile']['tmp_name'], 'r'), filesize($_FILES['userfile']['tmp_name'])));
if (!mysql_query("INSERT INTO `files` VALUES(null, '{$file}', '{$_FILES['userfile']['type']}')", $link))
{
// do database error reporting here...
echo 'Upload failed: Unable to insert image into database.';
}
else
{
echo "Upload successful! <a href='viewdbfile.php?id=".mysql_insert_id()."'>Click here to view the file!</a>\n";
}
}
else
{
echo 'Upload failed: File must be a JPEG file type and 10KB or less in size';
}
}
else
{
echo 'Upload failed: A valid file has not been uploaded!';
}
}
?>
<?php
// viewdbfile.php
// if passing the ID via GET
if (isset($_GET['id']))
{
$id = $_GET['id'];
}
$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('test', $link);
// Make SELECT query
$data = mysql_fetch_array(mysql_query("SELECT `file`, `mime` FROM `files` WHERE `id` = '{$id}'", $link), MYSQL_ASSOC);
// Set the content type header
header('Content-type: '.$data['mime']);
// Also notice that I am not stripping the slashes,
// Doing so may corrupt data in certain file types,
// while you may need to do so for others.
echo $data['file'];
?>
Also have a look at: http://www.php.net/manual/en/features.file-upload.php#features.file-upload.post-method
Which explains the $_FILES superglobal and the information available in it.
The 'file' link may also be included in the 'src' attribute of an <img> tag.
: ) Rich
::::::::::::::::::::::::::::::::: Smiling Souls http://www.smilingsouls.net :::::::::::::::::::::::::::::::::
|
|
Reply By:
|
joeore
|
Reply Date:
|
2/14/2004 6:55:32 PM
|
thank you..but..this is the cose that i used to visualizing the image (excuse me for my english:-))
<?php //dopo l'inserimento dell'immagine, controllo che l'id sia stato passato correttamente. if (isset($_GET['ID'])) { $id = $_GET['ID']; } //quindi mi collego al database $collegamento = mysql_connect('localhost', 'joe', 'joe'); mysql_select_db('santadi', $collegamento);
//ora creo la query $risultati = mysql_query("SELECT DatiBinari FROM filebinari", $collegamento); $data = mysql_fetch_assoc ($risultati); echo "<table border=1>"; echo "<tr><td>"; echo "<img src=\"" . $data ['DatiBinari'] . "\">"; echo "</td></tr>"; echo "</table>"; ?>
When i insert $data ['DatiBinari'] inside a table..e result is this:
I#dGxpdܚ̺W7/mP *壃w[zہ2;|DB%![ T 8juiLDMNh˩ ]HɥZi_rt 4]z:shf.d1g)E] ;OC#25Ym.1夬]G^'č>;jn([bޯY_",E GɦCa[2oYĩ1)Mp 8/4DT%vsئ=}Qu>I mU`(\>:4Ns29 TljX "E,O<@q^JEB*MzmJi!Xpܲ7uK7!?eBX~fvDة-stR). qߊi(0vmv_ jل%l%KRKucqDj)!xQ & T6p3 '@ZZĕsl<,'o{T7qTT[TRA%*? V6m?w& $=r! ҕWUCmIEݸd7e#_5E9*<JS[U/Im=d!+.s֦aZ jSQ$`boXU A]持P E (<`M 0K2tкOu <_j4yFjcZQ|mD #Q>V%@pJ2& ....ecc...ecc.
Can you help me?
|
|
Reply By:
|
richard.york
|
Reply Date:
|
2/14/2004 7:49:02 PM
|
quote: Originally posted by joeore echo "<img src=\"" . $data ['DatiBinari'] . "\">";
Well you aren't supposed to dump the binary data into the <img> tag. You must refer to an external php script via the img tag to get the browser to display the image.
$risultati = mysql_query("SELECT ID FROM filebinari", $collegamento); $data = mysql_fetch_assoc ($risultati);
Where is your WHERE clause?? Are you selecting *all* of the rows in the database? Select the unique ID and pass it to another, a second, PHP script to output the image. This is the same as you would use to reference a .jpg or .gif.. file. The PHP script essentially mimicks everything neccessary for the image to be displayed. I suggest you have another look at my last example. In the second script, you must make a content-type header change for the images's MIME type, such as, image/jpeg, image/x-png, image/gif, etc.. whichever one corresponds to your image type being used. This header change will tell the browser that the content coming along is an image and trigger it to process it as one.
If you use my original script as is, you need only modify this line to the following... and the query above to SELECT the ID field instead of the binary data...
echo "<img src='viewdbfile.php?ID={$data['ID']}' />";
hth, Rich
::::::::::::::::::::::::::::::::: Smiling Souls http://www.smilingsouls.net :::::::::::::::::::::::::::::::::
|
|
Reply By:
|
joeore
|
Reply Date:
|
2/14/2004 8:22:47 PM
|
excuse me..:-(((--but i don't understand well :-( can you help me with an example?...
|
|
Reply By:
|
richard.york
|
Reply Date:
|
2/15/2004 4:51:38 PM
|
Look at my original example again, this time modify the following line: echo "Upload successful! <a href='viewdbfile.php?id=".mysql_insert_id()."'>Click here to view the file!</a>\n";
To say the following: echo "Upload successful!<br />Image inserted:<br /><img src='viewdbfile.php?id=".mysql_insert_id()."' style='border: 1px solid black; margin: 10px;' />";
The mysql_insert_id() refers to the unique ID just assigned to the field, in this case an auto-incrementing integer. Without the ID you would not be able to distinguish one image from another.
If that doesn't make sense to you then I suggest you explain what doesn't make sense about it.
: ) Rich
::::::::::::::::::::::::::::::::: Smiling Souls http://www.smilingsouls.net :::::::::::::::::::::::::::::::::
|