I have the following issue that I’ve been struggling with for hours now and just can’t seem to get past: I have an HTML form that, upon submission, saves the entered data to a database. After submission, a redirection should occur using the header function in the PHP script. The form includes an option to upload a file. The problem now is that the redirection no longer works once a file is uploaded. The file is indeed saved correctly in the target folder, and the file path is also saved in the database, but instead of redirecting to the URL specified in the header function, only the form is reset. When the form is submitted without selecting a file, the redirection works without any issues.
I’ve also tried using output buffering and checking for whitespaces etc. but without success. Also the community thread here on stackoverflow regarding problems with redirects didn’t help.I don’t get any error messages and the ‘Headers already sent’ check gives no output.
I hope someone can help me solve the problem. Thanks in advance. Here is the PHP code:
<?php
include '../data/testconnect.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fotoPath = NULL;
if (isset($_FILES['foto']) && $_FILES['foto']['error'] == UPLOAD_ERR_OK) {
$uploadDir = '../assets/img/passbilder/';
$tmpName = $_FILES['foto']['tmp_name'];
$fileName = basename($_FILES['foto']['name']);
$safeFileName = preg_replace('/[^a-zA-Z0-9-_.]/', '', $fileName);
$uploadFile = $uploadDir . $safeFileName;
if (move_uploaded_file($tmpName, $uploadFile)) {
$fotoPath = $uploadFile;
} else {
die("An error occured.");
}
}
$name = $_POST['name'];
$birthdate = $_POST['birthdate'];
$ort = $_POST['ort'];
$street = $_POST['street'];
$hausnummer = $_POST['hausnummer'];
$stadt = $_POST['stadt'];
$plz = $_POST['plz'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$type = $_POST['type'];
$bauart_typ = $_POST['bauart_typ'];
$exam_date = $_POST['exam_date'];
$reg_nr = $_POST['reg_nr'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (name, birthdate, ort, foto, street, hausnummer, stadt, plz, phone, email, type, bauart_typ, exam_date, reg_nr, password)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
if (false === $stmt) {
die('MySQL prepare error: ' . $conn->error);
}
$stmt->bind_param("sssssssisssssss", $name, $birthdate, $ort, $fotoPath, $street, $hausnummer, $stadt, $plz, $phone, $email, $type, $bauart_typ, $exam_date, $reg_nr, $password);
$stmt->execute();
$stmt->close();
$conn->close();
header("Location: https://www.google.de");
exit;
}
?>