安全映像上傳腳本
簡介
安全影像上傳對於防止惡意活動內容關重要並確保您網站的完整性。本文提供了一個全面的解決方案來實現安全圖像上傳腳本,以解決各種潛在的漏洞。
主要要求
建立安全映像上傳腳本涉及幾個關鍵要求:
實作
實現
PHP程式碼(upload.php):
<pre class="brush:php;toolbar:false">// File type whitelist $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']; // Sanitize input $file_name = $_FILES['image']['name']; $file_type = $_FILES['image']['type']; $file_size = $_FILES['image']['size']; // Validate file type if (!in_array($file_type, $allowed_types)) { echo "Invalid file type. Please upload an image."; exit; } // Validate file size if ($file_size > 1000000) { echo "File too large. Maximum size allowed is 1MB."; exit; } // Verify image using GD library $image_info = getimagesize($_FILES['image']['tmp_name']); if (!$image_info) { echo "Invalid image. Please upload a valid image."; exit; } // Generate random file name and extension $new_file_name = str_replace(".", "", microtime()) . "." . pathinfo($file_name, PATHINFO_EXTENSION); // Isolated upload path outside document root $upload_directory = 'uploads/'; // Save image to secure directory if (!move_uploaded_file($_FILES['image']['tmp_name'], $upload_directory . $new_file_name)) { echo "Image upload failed. Please try again."; exit; } echo "Image uploaded successfully.";
<input type="file" name="image">