CSC220 uploadFile Form and Php Code
Revision as of 23:42, 2 November 2010 by Thiebaut (talk | contribs) (moved CSC220 uploadFile0.htm to CSC220 uploadFile Form and Php Code)
--D. Thiebaut 14:38, 1 November 2010 (UTC)
Contents
UploadFile0.htm
<html>
<body>
<form action="uploadFile0.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
Upload Image: <input type="file" name="imgfile">
<P>
<input type="submit" value="Upload Image">
</form>
</body>
</html>
UploadFile1.php
// uploadFile1.php
// D. Thiebaut
// Assumes a table of this form to receive the images:
// CREATE TABLE IF NOT EXISTS `images` (
// `Id` int(1) NOT NULL auto_increment,
// `Name` varchar(100) NOT NULL,
// `Size` int(1) NOT NULL,
// `Contents` longblob NOT NULL,
// `Misc` varchar(100) NOT NULL,
// PRIMARY KEY (`Id`),
// KEY `Name` (`Name`)
// ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
include 'accessinfo.php';
$database = "220a_example7";
function displayArray( $table ) {
print "<pre>";
print_r( $table);
print "</pre>";
}
//--- connect to mysql server ---
$link = mysql_connect( $hostName, $userName, $password );
if ( ! $link )
die( "Could not connect to server: " . $mysql_error() );
print "Connected to " . $hostName . "\n<br />";
//--- select database ---
$db = mysql_select_db( $database, $link );
if ( ! $db )
die( "Could not connect to database " . $database . ": "
. mysql_error() );
print "Database ". $database . " selected\n<br />";
//displayArray( $_FILES );
//--- upload file ---
if ( isset( $_FILES['imgfile'] ) ) {
displayArray( $_FILES );
$fileName = $_FILES['imgfile']['name'];
if ( ! get_magic_quotes_gpc() )
$fileName = addslashes( $fileName );
$type = $_FILES['imgfile']['type'];
$tmpName = $_FILES['imgfile']['tmp_name'];
$error = $_FILES['imgfile']['error'];
$fileSize = $_FILES['imgfile']['size'];
//--- read the file ---
$content = mysql_real_escape_string( file_get_contents( $tmpName ) );
//--- insert file info in mysql table `images` ---
if ( ! $error ) {
$query = "INSERT INTO `images` (`Name`, `Size`, `Type`, `Contents` ) "
. "VALUES ( '$fileName', '$fileSize', '$type', '$content' )";
$result = mysql_query( $query, $link );
if ( ! $result )
printf( "Upload of %s in database unsuccessful: %s\n<br />",
$fileName, mysql_error() );
else
printf("<h4>Successful Upload!</h4>" );
}
}
//--- close database ---
mysql_close( $link );
?>
</body>
</html>