Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image using ajax mysql php

I want to try uploading an image using php and mysql. I'm using a form to send data using ajax.

My Html Code:

<input type="file" name="logo" id="logo" class="styled">
<textarea rows="5" cols="5" name="desc" id="desc" class="form-control"></textarea>
<input type="submit" value="Add" id="btnSubmit" class="btn btn-primary">

Ajax Code:

var formData = new FormData($("#frm_data")[0]);
$("#btnSubmit").attr('value', 'Please Wait...');
$.ajax({
    url: 'submit_job.php',  
    data: formData,
    cache: false,
    contentType:false,
    processData:false,
    type: 'post',
    success: function(response)

my php code (submit_job.php):

$desc =  mysqli_real_escape_string($con, $_POST['desc']);
$date = date('Y-m-d H:i:s');
$target_dir = "jobimg/";
$target_file = $target_dir . basename($_FILES["logo"]["name"]);
move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file);
like image 483
Meena patel Avatar asked Feb 27 '26 22:02

Meena patel


2 Answers

Try this:

Jquery:

$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();  // Create a FormData object
        form_data.append('file', file_data);  // Append all element in FormData  object

        $.ajax({
                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the input type file */
    });

Php:

<?php
    if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }

?>
like image 81
Mayank Pandeyz Avatar answered Mar 02 '26 10:03

Mayank Pandeyz


Security is a major part in the web designing. Try following validations for more security.

Checking for the file in $_FILES

if (empty($_FILES['image']))
    throw new Exception('Image file is missing');

Checking for upload time errors

if ($image['error'] !== 0) {
    if ($image['error'] === 1) 
        throw new Exception('Max upload size exceeded');

    throw new Exception('Image uploading error: INI Error');
}

Checking the uploaded file

if (!file_exists($image['tmp_name']))
    throw new Exception('Image file is missing in the server');

Checking the file size

$maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
if ($image['size'] > $maxFileSize)
    throw new Exception('Max size limit exceeded'); 

Validating the image

$imageData = getimagesize($image['tmp_name']);
if (!$imageData) 
    throw new Exception('Invalid image');

Validating the Mime Type

$mimeType = $imageData['mime'];
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes)) 
    throw new Exception('Only JPEG, PNG and GIFs are allowed');

Hope this helps others to create an upload PHP script without security issues.

Source

like image 38
Supun Kavinda Avatar answered Mar 02 '26 10:03

Supun Kavinda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!