3

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);

3 Answers 3

6

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";
        }
    }

?>
Sign up to request clarification or add additional context in comments.

9 Comments

move_uploaded_file(jobimg/banner-_pipe-_puzzle.png): failed to open stream: No such file or directory in C:\wamp\www\jobPortalplus\Admin\submit_job.php on line 37
but i also want to store image name in database. how get i image name in variable
You can do this in If where ** "File Uploaded Successfully"; ** this message is placed by firing an insert query on db
how to get name of image in variable ?
$_FILES['file']['name']
|
2

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

Comments

1
<script type="text/javascript">
    $(document).ready(function () {
        $("form").submit(function (event) {
           event.preventDefault();
            var formdata = new FormData($('form')[0]);
            var url = $("form").attr('action');
            $.ajax({
                url: url,
                type: "POST",
                data: formdata,
                dataType: "json",
                processData: false,
                contentType: false,
                success: function (data) {
                    console.log(data);
                }
            });
        });
    });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.