I want to try uploading an image using php and mysql. I'm using a form to send data using ajax.
我想尝试使用php和mysql上传图像。我正在使用表单使用ajax发送数据。
My Html Code:
我的Html代码:
<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):
我的PHP代码(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 个解决方案
#1
2
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 file container */
});
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";
}
}
?>
#2
0
<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>
#3
0
Security is a major part in the web designing. Try following validations for more security.
安全性是网页设计的重要组成部分。请尝试以下验证以获得更高的安全性
Checking for the file in $_FILES
在$ _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
验证Mime类型
$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.
希望这有助于其他人创建一个没有安全问题的上传PHP脚本。
#1
2
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 file container */
});
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";
}
}
?>
#2
0
<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>
#3
0
Security is a major part in the web designing. Try following validations for more security.
安全性是网页设计的重要组成部分。请尝试以下验证以获得更高的安全性
Checking for the file in $_FILES
在$ _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
验证Mime类型
$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.
希望这有助于其他人创建一个没有安全问题的上传PHP脚本。