Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples/php-xhr: add filename sanitation and file size check before saving #4432

Merged
merged 1 commit into from
May 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions examples/php-xhr/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Get the maximum upload file size
$max_size = ini_get('upload_max_filesize');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
Expand All @@ -18,14 +21,31 @@
exit(0);
}

if ($_POST && !empty($_FILES["file"])) {
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES["file"])) {
$target_dir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads';
$target_file = $target_dir . DIRECTORY_SEPARATOR . basename($_FILES['file']['name']);
$file_name = basename($_FILES['file']['name']);
$file_size = $_FILES['file']['size'];
$target_file = $target_dir . DIRECTORY_SEPARATOR . $file_name;

// Validate file size
if ($file_size > $max_size) {
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
$data = ['message' => 'File size exceeds the maximum allowed size of ' . $max_size . '.'];
http_response_code(400);
echo json_encode($data);
exit;
}

// Sanitize file name to prevent directory traversal attacks
$file_name = preg_replace('/[^a-zA-Z0-9._-]/', '', $file_name);
$target_file = $target_dir . DIRECTORY_SEPARATOR . $file_name;

try {
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
$data = ['url' => $target_file, 'message' => 'The file ' . basename($_FILES['file']['name']) . ' has been uploaded.'];
$data = ['url' => $target_file, 'message' => 'The file ' . $file_name . ' has been uploaded.'];
http_response_code(201);
echo json_encode($data);
} else {
Expand All @@ -39,4 +59,10 @@
http_response_code(400);
echo json_encode($data);
}
} else {
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
$data = ['message' => 'Please upload a file.'];
http_response_code(400);
echo json_encode($data);
}