faqts : Computers : Programming : Languages : PHP : Common Problems : File Uploading

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

9 of 13 people (69%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

PHP: File: Internet: Database: MySql: How to upload and download files? (using browser, HTML, PHP)

Jan 2nd, 2006 14:03
Knud van Eeden,


----------------------------------------------------------------------
--- Knud van Eeden --- 17 Juny 2005 - 04:02 pm -----------------------
PHP: File: Internet: Database: MySql: How to upload and download 
files? (using browser, HTML, PHP)
---
Steps: Overview:
 1. -To upload
     1. -For the client side, create HTML page to choose the files to
         upload
     2. -On the computer on the web server side, create a PHP program
         which will store the received uploaded files in a MySql
         database
 2. -To download
     1. -On the computer on the web server side, create a PHP program
         which will let you select files for download, from that MySql
         database
     2. -On the computer on the web server side, create a PHP program
         which will let you download that selected files, from that
         MySql database
---
Steps: Worked out:
---
 1. -To upload
     1. -On the client side, create HTML page to choose the files to
         upload
        1. That is a form containing an input box which lets you input
           a filename, by typing or browsing to it
---
in general:
--- cut here: begin --------------------------------------------------
<!-------------------------------------------------------------------->
<FORM
  ACTION="yourServerSideFileUploadHandler"
  ENCTYPE="multipart/form-data"
  METHOD="post"
  NAME="yourFormName1"
>
<!-------------------------------------------------------------------->
<INPUT
  TYPE="file"
  NAME="yourFormFileInput1"
>
<!-------------------------------------------------------------------->
<INPUT
  TYPE="submit"
>
<!-------------------------------------------------------------------->
</FORM>
<!-------------------------------------------------------------------->
--- cut here: end ----------------------------------------------------
---
e.g.
--- cut here: begin --------------------------------------------------
<!-------------------------------------------------------------------->
<FORM
  ACTION="http://www.yourProvider.com/yourPHPFilename1.php"
  ENCTYPE="multipart/form-data"
  METHOD="post"
  NAME="yourFormName1"
>
<!-------------------------------------------------------------------->
<INPUT
  TYPE="file"
  NAME="yourFormFileInput1"
>
<!-------------------------------------------------------------------->
<INPUT
  TYPE="submit"
>
<!-------------------------------------------------------------------->
</FORM>
<!-------------------------------------------------------------------->
--- cut here: end ----------------------------------------------------
---
      2. if you then press the 'Submit' button
         it then sends it to the URL program
         mentioned in the field
         e.g.
          ACTION="yourServerSideFileUploadHandler"
         e.g.
          ACTION="http://www.yourProvider.com/yourPHPFile.php"
         3. This server side program
            (written in PHP, Perl, using CGI, ...)
              e.g.
               yourPHPFile.php
            has to further handle that bytes sent to it.
   2. Save this HTML file, e.g. as
       myTest1.htm
   -- or similarly as it can then be downloaded to any computer with 
Internet and a browser --
   2. Create and upload this page to the server, e.g. as
       myTest1.php
e.g.
--- cut here: begin --------------------------------------------------
<?PHP
print '<!--------------------------------------------------------------
------>';
print '<FORM';
print '  ACTION="http://www.yourProvider.com/yourPHPFilename1.php"';
print '  ENCTYPE="multipart/form-data"';
print '  METHOD="post"';
print '  NAME="yourFormName1"';
print '>';
print '<!--------------------------------------------------------------
------>';
print '<INPUT';
print '  TYPE="file"';
print '  NAME="yourFormFileInput1"';
print '>';
print '<!--------------------------------------------------------------
------>';
print '<INPUT';
print '  TYPE="submit"';
print '>';
print '<!--------------------------------------------------------------
------>';
print '</FORM>';
print '<!--------------------------------------------------------------
------>';
?>
--- cut here: end ----------------------------------------------------
2. -Upload: On the computer on the web server side, create a PHP
            program which will store the received uploaded files in a
            MySql database
   1. Using e.g. PHP
      1. PHP at the web server side stores this file automatically
         1. by default in the operating system's default temporary
            directory, e.g. in Microsoft Windows this could be:
          ---
    in general:
    "C:\Documents and Settings\<your username>\Local Settings\Temp\"
    ---
    e.g.
    "C:\Documents and Settings\Administrator\Local Settings\Temp\"
         2. You can change this temporary directory in the php.ini
            file (search for the variable 'upload_tmp_dir')
e.g.
--- cut here: begin --------------------------------------------------
; Temporary directory for HTTP uploaded files (will use system default
; if not specified).
upload_tmp_dir = C:\PHP\uploadtemp
--- cut here: end ----------------------------------------------------
      2. PHP at the web server side also automatically sets a few
         variables, after you pressed the 'Submit' button, to submit
         the information in this HTML form.
         1. PHP automatically creates the variables:
            $<your form input file name>_name = the name of the file as
                                                you chose on the user's
                                                machine (by browsing to
                                                it, or typing it in
                                                this 'file' input box
                                                in your HTML page)
            $<your form input file name> = the name of the file as
                                           stored in the temporary
                                           directory on your web server
                                           computer
            $<your form input file name>_size = the size of the file,
                                                in bytes
            $<your form input file name>_type = the MIME type (e.g.
                                                 image/gif
                                                 image/png
                                                 image/jpg)
         2. So on the web server computer, you could create the
            following program
in general:
--- cut here: begin --------------------------------------------------
<?php
print "you sent this file from your user machine = " . $<name of the 
INPUT file box in the HTML page>_name;
print "\n";
print "the filetype of this file = " . $<name of the INPUT file box in 
the HTML page>_type;
print "\n";
print "the filesize of this file = " . $<name of the INPUT file box in 
the HTML page>_size;
print "\n";
print "this file has now been stored in the default temporary 
directory (you can change this path in the file php.ini, change the 
variable = " . $<name of the INPUT file box in the HTML page>;
?>
--- cut here: end ----------------------------------------------------
e.g.
in this example:
--- cut here: begin --------------------------------------------------
<?php
print "you sent this file from your user machine = " . 
$yourFormFileInput1_name;
print "<BR/>";
print "the filetype of this file = " . $yourFormFileInput1_type;
print "<BR/>";
print "the filesize of this file = " . $yourFormFileInput1_size;
print "<BR/>";
print "this file has now been stored in the default temporary 
directory = " . $yourFormFileInput1;
?>
--- cut here: end ----------------------------------------------------
         3. Save this file on your web server computer, e.g.
            as
             yourPHPFilename1.php
         4. If you run the above HTML program in your browser, after
            uploading the PHP file to your web site, you could see a
            result similar to the following:
--- cut here: begin --------------------------------------------------
you sent this file from your user machine = ddd_.php
the filetype of this file = text/plain
the filesize of this file = 357
this file has now been stored in the default temporary directory 
= /www/tmp/php0qw0Qj
--- cut here: end ----------------------------------------------------
3. Upload: To put this file in your database, e.g. MySql or Oracle, 
you could create the
           following PHP file or add it to the above file, and store 
it also on
           your web server computer
4. Upload: To upload the file into the MySql database:
   1. Create a database with a BLOB field
--- cut here: begin --------------------------------------------------
-----------------------------------------------
DROP DATABASE IF EXISTS database1;
-----------------------------------------------
CREATE DATABASE database1;
-----------------------------------------------
USE database1;
-----------------------------------------------
DROP TABLE IF EXISTS table1;
-----------------------------------------------
CREATE TABLE
 table1
(
 columnNr INT PRIMARY KEY AUTO_INCREMENT,
 columnFileName VARCHAR( 50 ) NOT NULL,
 columnFileSize INT NOT NULL,
 columnFileType VARCHAR( 50 ) NOT NULL,
 columnFileContent BLOB NOT NULL
)
;
-----------------------------------------------
--- cut here: end ----------------------------------------------------
---
   2. All together create and save the following PHP
---
--- cut here: begin --------------------------------------------------
<?php
// -----------------------------------------------
//
# uploading
//
print "you sent this file from your user machine = " . 
$yourFormFileInput1_name;
print "<BR/>";
print "the filetype of this file = " . $yourFormFileInput1_type;
print "<BR/>";
print "the filesize of this file = " . $yourFormFileInput1_size;
print "<BR/>";
print "this file has now been stored in the default temporary 
directory as = " . $yourFormFileInput1;
//
// -----------------------------------------------
//
# database in which to store your uploaded file
//
$databasenameS = "<your MySql databasename>";
//
// -----------------------------------------------
//
#Connect to your database
//
// use e.g. 'localhost' if on your local computer
$hostname = "the <IP address of your MySql database>";
$username = "<your MySql user name";
$password = "<your MySql password>";
//
// -----------------------------------------------
//
# open mysql on the host computer
//
$databaselink = @mysql_connect( $hostname, $username, $password );
//
print "<BR/>";
print "<BR/>";
if ( $databaselink ) {
 print "Connected successfully to the MySql host computer";
}
else {
 die( "Could not connect to the MySql host computer:" . " " . 
mysql_error() );
}
// -----------------------------------------------
//
# connect to the specific MySql database
//
print "<BR/>";
print "<BR/>";
if ( @mysql_select_db( $databasenameS ) ) {
 print "Connected successfully to the database" . " " . $databasenameS;
}
else {
 print "<P>";
 print "Unable to locate the" . " " . $databasenameS . " " . "database 
at this time.";
 print "</P>";
 mysql_close( $databaselink );
 exit();
}
//
// -----------------------------------------------
# table and field in which to store your uploaded file
//
$tableS = "table1";
//
// -----------------------------------------------
//
// store the uploaded file in your MySql database
//
// The file is placed in the webserver's temp folder
// use the fopen method to get the file data into a variable
//
$fileNameTemporaryS = $yourFormFileInput1;
$fileNameClientS = $yourFormFileInput1_name;
$fileSizeS = $yourFormFileInput1_size;
$fileTypeS = $yourFormFileInput1_type;
//
if ( $filehandle = fopen( $fileNameTemporaryS, 'r' ) ) {
 print "Could successfully open the uploaded file" . " " . 
$fileNameTemporaryS;
}
else {
 print "Could not successfully open the uploaded file" . " " . 
$fileNameTemporaryS;
}
;
//
$fileData = fread( $filehandle, $fileSizeS );
//
// you must make it compatible with the string type of the query
//
$fileData = addslashes( $fileData );
//
fclose( $filehandle );
//
//put the data into the blob field...
//
// @mysql_query( "USE" . " " . $databaseS );
//
$queryS =
"INSERT INTO" .
" " .
$tableS .
" " .
"(" .
" " .
"columnFileName, columnFileSize, columnFileType, columnFileContent" .
" " .
") VALUES (" .
"'" . $fileNameClientS . "'" . "," .
"'" . $fileSizeS . "'" . "," .
"'" . $fileTypeS . "'" . "," .
"'" . $fileData . "'" .
")"
;
print "<BR/>";
print "<BR/>";
if ( @mysql_query( $queryS ) ) {
 print "Could successfully run the SQL query" . " " . "<BR/>" . 
$queryS;
}
else {
 die( "Could not successfully run the SQL query" . " " . "<BR/>" . 
$queryS . " " . ":" . " " . "<BR/>" . mysql_error() );
}
mysql_close( $databaselink );
?>
--- cut here: end ----------------------------------------------------
   3. If you run the HTML file, you could see a result similar to the
      following output (you see that extra '\' are added before some
      characters, by using the 'addslashes()' function of PHP)
---
--- cut here: begin --------------------------------------------------
you sent this file from your user machine = ddd_.php
the filetype of this file = text/plain
the filesize of this file = 3228
this file has now been stored in the default temporary directory as =
/<some directory>/tmp/<some filename>
Connected successfully to the MySql host computer
Connected successfully to the database <your MySql database name>
/<some directory>/tmp/<some filename>
3241
Could successfully open the uploaded file /<some directory>/tmp/<some 
filename>
Could successfully run the SQL query
INSERT INTO table1 ( columnFile) VALUES (
'
\"; print \"the filetype of this file = \" . $yourFormFileInput1_type; 
print \"
'
)
--- cut here: end ----------------------------------------------------
   3. If you check the content of your MySql database, it should show
      now something similar to
--- cut here: begin --------------------------------------------------
-----------------------------------------------------------------------
columnNr columnFileName columnFileSize columnFileType columnFileContent
-----------------------------------------------------------------------
1        ddd_.php       3228           text/plain     \"; print \"the f
-----------------------------------------------------------------------
--- cut here: end ----------------------------------------------------
5. -Download: On the computer on the web server side, create a PHP
              program which will let you select files for download
              from that MySql database
---
--- cut here: begin --------------------------------------------------
<!-------------------------------------------------------------------->
<?php
// -----------------------------------------------
//
# database in which to store your uploaded file
//
$databasenameS = "<your MySql databasename>";
//
// -----------------------------------------------
//
#Connect to your database
//
$hostname = "<IP address of the computer on which your MySql runs>";
$username = "<your MySql user name>";
$password = "<your MySql password>";
//
// -----------------------------------------------
//
# open mysql on the host computer
//
$databaselink = @mysql_connect( $hostname, $username, $password );
//
print "<BR/>";
print "<BR/>";
if ( $databaselink ) {
 print "Connected successfully to the MySql host computer";
}
else {
 die( "Could not connect to the MySql host computer:" . " " . 
mysql_error() );
}
// -----------------------------------------------
//
# connect to the specific MySql database
//
print "<BR/>";
print "<BR/>";
if ( @mysql_select_db( $databasenameS ) ) {
 print "Connected successfully to the database" . " " . $databasenameS;
}
else {
 print "<P>";
 print "Unable to locate the" . " " . $databasenameS . " " . "database 
at this time.";
 print "</P>";
 mysql_close( $databaselink );
 exit();
}
//
// -----------------------------------------------
# table and field in which to store your uploaded file
//
$tableS = "table1";
//
// -----------------------------------------------
//
# PHP filename, used to download the uploaded files
//
$fileNameS = "download1.php";
//
// -----------------------------------------------
//
$queryS =
"SELECT" .
" " .
"columnNr, columnFileName" .
" " .
"FROM" .
" " .
$tableS
;
print "<BR/>";
print "<BR/>";
$result = @mysql_query( $queryS );
if ( $result ) {
 print "Could successfully run the SQL query" . " " . "<BR/>" . 
$queryS;
}
else {
 die( "Could not successfully run the SQL query" . " " . "<BR/>" . 
$queryS . " " . ":" . " " . "<BR/>" . mysql_error() );
}
//
print "<BR/>";
print "<BR/>";
if( mysql_num_rows( $result ) == 0 ) {
 print "<BR/>";
 print "<BR/>";
 print "Table containing upload files in database" . " " . 
$databasenameS . " " . "is empty";
}
else {
 while( list( $columnNr, $columnFileName ) = mysql_fetch_array( 
$result ) ) {
 ?>
<!-------------------------------------------------------------------->
<A
  HREF="<?php print $fileNameS?>?columnNr=<?php print $columnNr; ?>"
>
 <?php print $columnFileName; ?>
</A>
<!-------------------------------------------------------------------->
 <BR/>
<!-------------------------------------------------------------------->
 <?php
 }
}
mysql_close( $databaselink );
?>
<!-------------------------------------------------------------------->
--- cut here: end ----------------------------------------------------
    1. -Save this file, e.g. as
         download.php
    2. -If you run this PHP file, and you click on any of the download
        links, the unique primary key 'columnNr' is selected, and will
        be used in the next query to select the corresponding filename
        from the MySql database
6. -Download: After you clicked on a link, you will be directed to a
              new PHP page, with the primary key of the filename and
              the filename itself to select these from the MySql
              database
--- cut here: begin --------------------------------------------------
<?php
//
// if unique primary key columnNr is set then get the file with that
// columnNr from database
//
if ( isset( $_GET['columnNr'] ) ) {
 // -----------------------------------------------
 //
 # database in which to store your uploaded file
 //
 $databasenameS = "<your MySql database name>";
 //
 // -----------------------------------------------
 //
 #Connect to your database
 //
 $hostname = "<the IP address of the computer on which your MySql 
runs>";
 $username = "<your MySql user name>";
 $password = "<your MySql password>";
 //
 // -----------------------------------------------
 //
 # open mysql on the host computer
 //
 $databaselink = @mysql_connect( $hostname, $username, $password );
 //
 print "<BR/>";
 print "<BR/>";
 if ( $databaselink ) {
  print "Connected successfully to the MySql host computer";
 }
 else {
  die( "Could not connect to the MySql host computer:" . " " . 
mysql_error() );
 }
 // -----------------------------------------------
 //
 # connect to the specific MySql database
 //
 print "<BR/>";
 print "<BR/>";
 if ( @mysql_select_db( $databasenameS ) ) {
  print "Connected successfully to the database" . " " . 
$databasenameS;
 }
 else {
  print "<P>";
  print "Unable to locate the" . " " . 
$databasenameS . " " . "database at this time.";
  print "</P>";
  mysql_close( $databaselink );
  exit();
 }
 //
 // -----------------------------------------------
 # table and field in which to store your uploaded file
 //
 $tableS = "table1";
 //
 // -----------------------------------------------
 $columnNrS = $_GET['columnNr'];
 //
 $queryS =
 "SELECT" .
 " " .
 "columnFileName, columnFileSize, columnFileType, columnFileContent" .
 " " .
 "FROM" .
 " " .
 $tableS .
 " " .
 "WHERE" .
 " " .
 "columnNr" .
 "=" .
 "'" .
 $columnNrS .
 "'"
 ;
 //
 print "<BR/>";
 print "<BR/>";
 $result = @mysql_query( $queryS );
 if ( $result ) {
  print "Could successfully run the SQL query" . " " . "<BR/>" . 
$queryS;
 }
 else {
  die( "Could not successfully run the SQL query" . " " . "<BR/>" . 
$queryS . " " . ":" . " " . "<BR/>" . mysql_error() );
 }
 //
 list( $columnFileName, $columnFileSize, $columnFileType, 
$columnFileContent ) = mysql_fetch_array( $result );
 //
 header( "Content-length: $columnFileSize" );
 header( "Content-type: $columnFileType" );
 header( "Content-Disposition: attachment; filename=$columnFileName" );
 echo $columnFileContent;
 //
 mysql_close( $databaselink );
 exit;
}
?>
--- cut here: end ----------------------------------------------------
    2. -If you run the PHP file, and select a file for download
        by clicking on the link, you will see the usual
        (e.g. Microsoft Windows) download dialog box, allowing
        you to 'Open', 'Save' or 'Cancel', after which you
        choose e.g. 'Save' to save the file on your current
        computer.
---
---
Tested successfully on
Microsoft Windows XP Professional (service pack 2),
running
MySql v4.1
PHP v5.0.3
Apache web server
Internet Explorer v6
---
---
Internet: see also:
---
Computer: Internet: File: Upload: Link: Overview: Can you give me an 
overview of links?
http://www.faqts.com/knowledge_base/view.phtml/aid/36718/fid/136
----------------------------------------------------------------------