只想查看我的脚本和项目有多脆弱。从专家的博客和答案的研究,我发现可能的攻击和注射是基于
我听说过反CSRF令牌以防止会话劫持。如何从ajax表单数据传递CSRF令牌值。
我不确定我有多安全。请指导我在以下脚本中添加哪些内容以提高安全性?
<?php
if(!empty($_POST['heading']) && !empty($_POST['content']) && !empty($_POST['keytag']) && !empty($_POST['date'])){
$query = '';
if(!empty($_FILES['file']['name'])){
$target_dir = "../images/news/";
$img = basename($_FILES['file']['name']);
$verifyimg = getimagesize($_FILES['file']['tmp_name']);
$imageFileType = strtolower(pathinfo($img,PATHINFO_EXTENSION));
$img_ext = end((explode('.', $img)));
if($_FILES['file']['size'] > 200000){
echo "File is too large";
exit();
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Only jpg/png/gif image !";
exit();
}
if($verifyimg['mime'] != 'image/png' && $verifyimg['mime'] != 'image/jpg' && $verifyimg['mime'] != 'image/jpeg' && $verifyimg['mime'] != 'image/gif') {
echo "Image is not valid";
exit;
}
else{
$new_img = substr(md5(time()), 0, 10) . '.' . $img_ext;
$target_file = $target_dir .$new_img;
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
$query = $con->prepare('INSERT into news(heading, content, keytag, date, img) VALUES(:heading, :content, :keytag, :date, :new_img)');
$query->bindParam(':new_img',$new_img);
}
}
if(empty($_FILES['file']['name'])){
$query = $con->prepare('INSERT into news(heading, content, keytag, date) VALUES(:heading, :content, :keytag, :date)');
}
$query->bindParam(':heading', $_POST['heading']);
$query->bindParam(':content', $_POST['content']);
$query->bindParam(':keytag', $_POST['keytag']);
$query->bindParam(':date', $_POST['date']);
if($query->execute()){
echo "Successfully Inserted";
};
}
?>
的.htaccess
阻止直接访问
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://www\.your-domain\.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www\.your-domain\.com$ [NC]
RewriteRule .*\.(wav|swf|jpg|jpeg|gif|png|bmp|js|css)$ - [F,NC,L]
我的主要问题是如何从ajax传递CSRF令牌?
HTML
<input type="hidden" name="_token" value="<?php echo $_SESSION['_token']; ?>" />
<input type="submit" value="Upload" />
的Ajax
<script>
$(document).on('submit', '#form', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'upload.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
alert(data);
}
});
});
$("#file").change(function(){
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
alert('Please select a valid image file (JPEG/JPG/PNG).');
$("#file").val('');
return false;
}
});
</script>