File Upload With PHP and MySQL





This instructional exercise shows how you can upload a files utilizing PHP and Store transferred record into the MySQL Database.

Database Structure


CREATE DATABASE `roshan_db` ;
CREATE TABLE ` roshan_db `.`roshan_uploads` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`file` VARCHAR( 100 ) NOT NULL ,
`type` VARCHAR( 10 ) NOT NULL ,
`size` INT NOT NULL
) ENGINE = MYISAM ;


Database Configuration

dbconfig.php


$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = " roshan_db ";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the server'); 
mysql_select_db($dbname) or die('database selection problem');


index.php


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload With PHP and MySql</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">Upload</button>
</form>
</body>
</html>


above html form sends the information to the accompanying PHP script and joining this html and php script you can without much of a stretch transfer records to the database .

upload.php 

this is the main PHP Script of this tutorial which uploads the file to the server.


<?php
include_once 'dbconfig.php';
 
if(isset($_POST['btn-upload']))
{    
     
 $file = rand(100,1000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
 $file_size = $_FILES['file']['size'];
 $file_type = $_FILES['file']['type'];
 $folder="uploads/";
 
 if(move_uploaded_file($file_loc,$folder.$file)){
 $sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$file','$file_type','$file_size')";
 mysql_query($sql);

}else{
 
echo “Something Wrong !!!”;
} 
}
?>


Some parameter learn : 

After the form is submitted the we have to peruse the autoglobal $_FILES. In the case over the info name for the file is record so the substance of $_FILES are similar to this :


$_FILES['file']['name']
The original name of the file on the client machine.

$_FILES['file']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif".

$_FILES['file']['size']
The size, in bytes, of the uploaded file.

$_FILES['file'] ['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['file'] ['error']
The error code associated with this file upload. ['error'] was added in PHP 4.2.0








1 comments:

Post a Comment

Go for Best Deal