Tuesday, 4 August 2015

PHP script for file Upload

07:12


(1) remember <form >element's enctype (encoding type)attribute to "multipart/form-data"
(2)
$_FILES['userfile']['name']   The name of the file on the user's Machine
$_FILES['userfile']['size']    The  MIME TYPE OF THE FILE.
 $_FILES['userfile']['tmp_name']  The temporary filename of the  file in which the uploaded file was stored on the server. 
 $_FILES['userfile']['type']   The MIME type of the file 
 $_FILES['userfile']['error']  ther error code associated with this file upload


(1)step 1: write code for  "slider.html"

<form action="sliderupload.php"   method="post"  enctype="multipart/form-data">
UPload<input type="file"  name="image">
 <input type="submit"  name="submit"  value="Upload">


</form>

(2)step 2: write code for  "sliderupload.html"


<?php

$image=$_FILES['image']['name'];

include("connect.php");

$sql="insert into slider(image)values('$image')";

mysql_query($sql) or die(mysql_errror());

move_uploaded_file($_FILES['image']['tmp_name'],"slider/".$_FILES['image']['name']) or die(mysql_error());

?>

(3)write code to display image from slider folder :

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("data",$con);
$sql="select * from slider";

$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
 $image=$row['image'];
echo "<img  src='slider/".$image."'   height=200 width=200   border=10 >";

}
?>
==================================================================================================================================================================

Create table upload:

Create table upload
(id  int primary key   auto_increment,
Image   varchar(200)
);

(1)write    code for     upload.html    file :
<form action="sliderupload.php"   method="post"  enctype="multipart/form-data">
UPload<input type="file"  name="image">
 <input type="submit"  name="submit"  value="Upload">
</form>

(2)write     code sliderupload.php   file  :
<?php

$image=$_FILES['image']['name'];

$con=mysql_connect("localhost","root","");
mysql_select_db("om",$con);

if (file_exists("upload/" . $image))
{
echo $image . " Exists already ";
}
else
{
$sql="insert into  upload(image)values('$image')";
mysql_query($sql) or die(mysql_error());
move_uploaded_file($_FILES['image']['tmp_name'],"upload/".$_FILES['image']['name']) or die(mysql_error());
}
?>

complete example   for  uploading and updating  image with other records  :

first of create table php:
SQL>
create  table  php
(id   int primary key auto_increment,
name  varchar(200),
uploaddoc varchar(200)
);

(1)write code for  register.html :

<form action="register.php" method="post"  enctype="multipart/form-data">
Name <input type="text" name="name">
Upload Document<input type="file" name="uploaddoc">
<input type="submit" name="submit" value="submit">
</form>

(2)write code for register.php :

<?php

$name=$_POST['name'];
$uploaddoc=$_FILES['uploaddoc']['name'];

$con=mysql_connect("localhost","root","");
mysql_select_db("mandar",$con);

$sql="insert into php(name,uploaddoc)values('$name','$uploaddoc')";

$result=mysql_query($sql);

if (file_exists("../register/image/" .$uploaddoc ))
{

echo $uploaddoc . "  change your file name this file name already Exists .";

}
else{

if($result)
{
echo "Record Registred";
move_uploaded_file($_FILES['uploaddoc']['tmp_name'],"../register/image/".$_FILES['uploaddoc']['name']) or die(mysql_error());
}
else
{
echo "Record Not Registered";
}

}
?>


(3)write code for  update.php  file:

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("mandar",$con);

$sql="select * from php ";

$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo $row['uploaddoc'];
echo '
<form action="finalupdate.php" method="post" enctype="multipart/form-data">
Name <input type="text" name="name" value="'.$row['name'].'">

Uploaddoc <input type="file" name="uploaddoc">
<input type=hidden  name=hidden  value="'.$row['id'].'">
<input type="submit" name="submit" value="update_profile">
</form>';
}
?>

(4)write code for  finalupdate.php file:

<?php

$con=mysql_connect("localhost","root","");
mysql_select_db("mandar",$con);

$hidden=$_POST['hidden'];
$name=$_POST['name'];
$uploaddoc=$_FILES['uploaddoc']['name'];



if($uploaddoc==true)
{
$sql="update php set name='$name',uploaddoc='$uploaddoc' where id='$hidden'";
$result=mysql_query($sql) or die(mysql_error());

if($result)
{
echo "Record Update Successfully";
move_uploaded_file($_FILES['uploaddoc']['tmp_name'],"../register/image/".$_FILES['uploaddoc']['name']) or die(mysql_error());
}
else
{
echo "record not update";
}

}

else
{

$sql="update php set name='$name' where id='$hidden'";
$result=mysql_query($sql) or die(mysql_error());

if($result)
{
echo "Record Update Successfully";

}
else
{
echo "record not update";
}

}
?>




==================================================================================================================================================================
SIMPLE GUIDANCE  FOR   WHILE UPDATING  IMAGE  WITH  A  CONTENT :

(1) test.html  :

<form action=testimage.php  method=post  enctype="multipart/form-data">

Name <input type=text name=name>

IMAGE FILE<input type=file name=image>

<input type=submit name=submit value=upload>


</form>

(2)testimage.php    file:

<?php

$image=$_FILES['image']['name'];
if($image==true)
{
echo   $_FILES['image']['name']; 

echo  $name=$_POST['name'];

// then  wirte  update query  with image update

}
else
{


echo  $name=$_POST['name'];
  
// then  wirte  update query without  image update.

}



?>


==================================================================================================================================================================
=================================================================================
using    object oriented  php code:
=================================================================================
(4)write code for class.php file :

<?php


class db

{

var $host="servername";

var  $username="username";

var  $password="password";

function connect()
{

$connect=mysql_connect($this->host,$this->username,$this->password);

mysql_select_db("a1390987_om",$connect) or die(mysql_error());

if(!$connect)
{

echo "connection error ";
}





}

function display($table)
{


$sql="select * from $table ";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);




return $row;

}


}

$obj=new db();
$obj->connect();



?>


(5)use img tag to display image & write following code for displayslider.php:

<?php

include("class.php");

$table="slider";

$slider=$obj->display($table);

$image=$slider['image'];

echo $image;



echo "<img  src='slider/".$image."'   height=200 width=200   border=10 >";





?>
========================================================================
write above code with restriction of image uploading
========================================================================
(1)write code for uploadform.html:

<form id="uploadimage" action="upload.php" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>

(2)upload.php:

<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 400000)//Approx. 400kb files can be uploaded.
&& in_array($file_extension, $validextensions))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>

==================================================================================================================================================================
Create a folder name upload  Then start given  below code.
1)write code for index.php  file:
<!doctype html>
<html lang="en">
<head>
<title>Image Preview before Upload Demo - BY OM SIR</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.11.0/jquery-ui.min.js"></script>
  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/redmond/jquery-ui.css" type="text/css" />
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" type="text/css" />
<script type="text/javascript">
$(document).ready(function (event) {
// triggered when the form submitted
$("#selected_image").on('submit',(function(event) {
event.preventDefault();
$("#upload_status").empty();
$.ajax({
// URL to move the uploaded image file to server
url: "Preview_Upload.php",
// Request type
type: "POST",
// To send the full form data
data: new FormData(this),
contentType: false,     
processData:false,    
// UI response after the file upload 
success: function(data)
{
$("#upload_status").html(data);
}
});
}));

// Triggered when the image changed (browse)
$(function() {
$("#image_file").change(function(event) {
if(-1!=$.inArray($("#image_file")[0].files[0].type, ["image/jpeg","image/png","image/jpg","image/gif"])){         
var populateImg = new FileReader();
populateImg.onload = previewImg;
populateImg.readAsDataURL($("#image_file")[0].files[0]);
}
});
});

// Function to show the image as a preview
function previewImg(event) {
$('.img').css("display", "block");
$('#img_preview').attr('src', event.target.result);
$('#img_preview').attr('width', '300px');
$('#img_preview').attr('height', '250px');
};
});
</script>
</head>
<body>
<div class="container">
  <div class="row">
    <div class="span12">
      <div class="head">
        <div class="row-fluid">
            <div class="span12">
                <div class="span6">
                    <h1 class="muted"><a href="www.phpdevelopmenttricks.blogspot.com">&nbsp;&nbsp;&nbsp;Image Preview before Upload Demo | BY OM SIR</a></h1>
                </div>
            </div>
        </div>
                       
                       
        </div>
      </div>
    </div>
           
           
            <div class="jumbotron">
  <div class="container">
    



 <div class="row">
  <div class="col-sm-8">
  <label>Select Image to Upload</label>
    <div class="row">
      <div class="col-sm-6"><form id="selected_image" action="" method="post" enctype="multipart/form-data"><input type="file" name="image_file" id="image_file" class="btn btn-sm btn-primary" style="width:250px;"/></div>
      <div class="col-sm-6"><input type="submit" value="Upload" class="btn btn-sm btn-success" style="width:250px;"/></div>
    </div>
  </div>
  <div class="col-sm-4">
<div class="img"><img id="img_preview" /></div>
</form></div>
</div>
<div id="upload_status"></div>
  </div>
</div>
  </div>
</div>
</body>
</html>
(2)write   code for  Preview_Upload.php  file:
<?php
if(isset($_FILES["image_file"]["type"]))
{
$uploadedImgFileExtension = $_FILES["image_file"]["type"];
$uploadedImgFileSize = $_FILES["image_file"]["size"];
// checking the image file types and size
if(( ($uploadedImgFileExtension=="image/png") || ($uploadedImgFileExtension=="image/gif") || ($uploadedImgFileExtension=="image/jpg") || ($uploadedImgFileExtension=="image/jpeg")) ) {
// Name of the uploaded file
$uploadedImgFileName =$_FILES['image_file']['name'];
if (file_exists("upload/" . $uploadedImgFileName)) {
echo $uploadedImgFileName . " Exists already ";
}
else
{
// Temporary path to store the uploaded image
$tempPath = $_FILES['image_file']['tmp_name'];
// destination folder name where the uploaded image need to be moved
$moveFileTo = "upload/";
$destFullPath = $moveFileTo.$uploadedImgFileName;
// Moving the uploaded image file
$isMoved = move_uploaded_file($tempPath,$destFullPath) ;
if ($isMoved == true) {
    echo "Image Uploaded Successfully";
echo "<br/><b>Name:</b> " . $uploadedImgFileName . "<br>";
echo "<b>Type:</b> " . $uploadedImgFileExtension . "<br>";
echo "<b>Size:</b> " . ($uploadedImgFileSize / 1024) . " kB<br>";
} else {
     echo "ERROR: File not moved correctly";
}
}
}
else
{
echo "Invalid Image File";
}
}
?>

output:


Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

PHP Training Mumbai, PHP MySQL Training Mumbai, PHP Course Mumbai, PHP Institute Mumbai

 

© 2013 PHP TRAINING IN MUMBAI BY OM SIR . All rights resevered. Designed by OM SIR

Back To Top