Я пытаюсь установить http_response_code();
в PHP
, чтобы запустить if-statement
в ответе fetch API
. Но response.status
в JavaScript
всегда 200 OK
. Я действительно застрял с этим.
Что я делаю не так?
Вот бит JavaScript
:
fetch(url, {
method: 'POST',
body: formData
})
.then(response => {
if (response.status === 422) {
console.log(
'The upload did not work. Please make sure your files are images and no bigger than 2MB.'
);
}
})
.catch(error => {
console.log('Error: ', error);
});
}
И в PHP
:
if ($_SERVER['REQUEST_METHOD'] === 'POST' ) {
if (isset($_POST['folder'])) {
$folder = $_POST['folder'];
} else {
$folder = 'new-folder';
}
if (isset($_FILES['files'])) {
$errors = [];
$path = $_SERVER['DOCUMENT_ROOT'] . '/data/uploads/images/' . $folder . "/";
// if folder does not exist, create it
if (!file_exists($path)) {
mkdir($path, 0777, true);
} else {
// stuff
}
$extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$pattern = "#^(image/)[^\s\n<]+$#i";
$all_files = count($_FILES['files']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$tmp = explode('.', $_FILES['files']['name'][$i]);
$file_ext = strtolower(end($tmp));
$file = $path . $file_name;
$verifyimg = getimagesize($_FILES['files']['tmp_name'][$i]);
try {
if(!preg_match($pattern, $verifyimg['mime'])) {
throw new Exception("Only image files are allowed!");
}
// here goes more validation like this
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
} catch (Exception $exception) {
echo $exception->getMessage();
// Get the current response code and set a new one
http_response_code(422);
// Get the new response code
http_response_code();
}
}
}
}