How to upload image in mysql with validation and file renaming after uploading using PHP

How-to-upload-image-in-mysql-with-validation-and-file-renaming-after-uploading-using-PHP

How to upload image in mysql with validation and file renaming after uploading using PHP

In this tutorial, you learn How to upload image in mysql with validation and file renaming after uploading using PHP

STEP:1 :- Make Database connection 

$con = mysqli_connect("localhost","username","password","databasename");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

STEP:2 :- open an editor, Paste the following code and save it as .php or the extension you want to save. ( PHP Code for Image Uploading )

<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
    $msg="";
    $temp = explode(".", $_FILES["image"]["name"]);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    $image=$_FILES['image']['name'];
    // image mime to be checked against
    $imagetype = array(image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_JPEG),
        image_type_to_mime_type(IMAGETYPE_PNG));
 
    $error_msg = "";
    $imageUploadERROR = FALSE;
    $FOLDER = "images/";
    if ($_FILES["image"]["name"] <> "" && $_FILES["image"]["error"] == 0) {
        // uploaded file is OK
        
        if (in_array($_FILES["image"]["type"], $imagetype)) {
            // get the extention of the file
            $file_extention = @strtolower(@end(@explode(".", $_FILES["image"]["name"])));
            // Setting an unique name for the file
            $file_name = date("Ymd") . '_' . rand(10000, 990000) . '.' . $file_extention;
 
            if (move_uploaded_file($_FILES["image"]["tmp_name"], "images/" . $newfilename) === FALSE) {
                $error_msg = "Error while uploading the file";
            } else {

           
 $sql="INSERT INTO images(image)VALUES('$newfilename')";
    mysqli_query($db, $sql);

    echo '<script>alert("Image uploaded successfully");</script>';


                
            }
        } else {
           
            echo '<script>alert("File is not a valid image type.");</script>';
        }
 
        if ($imageUploadERROR === FALSE) {
            // Failed to upload file, you can write your code here
            echo $error_msg;
        } else {
            // file is uploaded, you can write your code here
            echo $error_msg;
        }
    }
    
?>

STEP:3 :- open an editor, Paste the following code and save it as .php or the extension you want to save. ( HTML Code for Image Uploading )

<form method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000">
<span>Upload Image/Photo</span>
<input type="file" name="image"  accept="image/*" id="menu_images" value="Upload Image / photo" required>
<script type="text/javascript">
document.getElementById("menu_images").onchange = function () {
    var reader = new FileReader();
    if(this.files[0].size>528385){
        alert("Image Size should not be greater than 500Kb");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();     
        return false;
    }
    if(this.files[0].type.indexOf("image")==-1){
        alert("Invalid Type");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();         
        return false;
    }   
    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("menu_image").src = e.target.result;
        $("#menu_image").show(); 
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};
</script>
<input  type="submit"  name="submit" value="Upload Blog Post">
</form>

STAY CONNECTED FOR MORE :)

ADD COMMENT

Your email address will not be published. Required fields are marked *








Be the first to comment. :)

The primary motive of our company is to provide beyond satisfactory results .

Request a free consultation quote

WWW.BHAGAUTI.COM © COPYRIGHT 2018 | TERMS AND CONDITIONS | Privacy & Policy