วิธีที่ปลอดภัยในการอัปโหลดภาพ php และ GIF
Aug 20 2020
ฉันกำลังสร้างเครือข่ายโซเชียลและต้องการทราบว่านี่เป็นวิธีที่ปลอดภัยในการอัปโหลดรูปภาพ / gif และวิดีโอหรือไม่
if(isset($_POST['post'])) { $uploadOk = 1;
$imageName = $_FILES['postToUpload']['name'];
$errorMessage = ""; $picdate = date('Y-m-d_H-i-s');
if($imageName != "") { $targetDir = "assets/images/posts/";
$imageName = $targetDir . uniqid() . basename($imageName); $imageFileType = pathinfo($imageName, PATHINFO_EXTENSION); if($_FILES['postToUpload']['size'] > 10971520) {
$errorMessage = "Your file is to large"; $uploadOk = 0;
}
if (strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "png" &&
strtolower($imageFileType) != "jpg" && strtolower($imageFileType) != "gif"
&& strtolower($imageFileType) != "mp4"&& strtolower($imageFileType) != "Ogg"
&& strtolower($imageFileType) != "WebM"){ $errorMessage = "File type not allowed.";
$uploadOk = 0; } if($uploadOk){
if(move_uploaded_file($_FILES['postToUpload']['tmp_name'], $imageName)) {
// image uploaded
} else{
// image did not upload
$uploadOk = 0; } } } if($uploadOk) {
$post = new Post($con, $userLoggedIn); $post->submitPost(trim(strip_tags(filter_var($_POST['post_text'], FILTER_SANITIZE_STRING))), 'none', $imageName);
} else {
echo "<div class='alert alert-danger'>
$errorMessage
</div>";
}
}
คำตอบ
2 Victor Sep 11 2020 at 20:56
รหัสของคุณไม่ปลอดภัยเนื่องจาก:
- อาศัยเฉพาะนามสกุลไฟล์ดังนั้นผู้โจมตีจึงสามารถอัปโหลดแบ็คดอร์ได้
- เข้าถึงตัวแปร
$_FILES['postToUpload']['name']
โดยไม่ต้องตรวจสอบว่ามีการกำหนดหรือไม่และอาจนำไปสู่การเปิดเผยเส้นทางแบบเต็ม - ใช้ฟังก์ชัน
uniqid()
โดยไม่มีข้อโต้แย้งใด ๆ ดังนั้นจึงไม่รับประกันความเป็นเอกลักษณ์และไฟล์ที่อัปโหลดพร้อมกันและมีชื่อไฟล์เดียวกันจะถูกเขียนทับ - จัดเก็บชื่อไฟล์ที่ผู้ใช้ให้ไว้โดยไม่ลบอักขระที่อาจเป็นอันตรายและอาจนำไปสู่ผลลัพธ์ที่ไม่คาดคิด
คำแนะนำบางประการในการปรับปรุงโค้ดของคุณ:
- กำจัด
$uploadOk
ตัวแปร คุณมีและจัดการกับ$errorMessage
ตัวแปรอยู่แล้วและนี่ก็เพียงพอแล้วที่จะตรวจสอบว่าไฟล์ถูกอัพโหลดสำเร็จหรือไม่ - คุณควรกำหนด
$imageFileType
เป็นตัวพิมพ์เล็กแทนที่จะเรียกstrtolower()
แต่ละส่วนขยาย - คุณควรกำหนดนามสกุลไฟล์ทั้งหมดที่ได้รับการยอมรับว่าเป็นตัวพิมพ์เล็กมิฉะนั้นผู้ใช้จะไม่สามารถอัปโหลดไฟล์บางคน (ในกรณีของคุณ
WebM
และOgg
เพราะstrtolower($imageFileType) != "Ogg"
และstrtolower($imageFileType) != "WebM"
มักจะเป็นFALSE
)