I can’t figure out where the issue is with this script… Can you guys analyse the bug?
<?php
// Function to check if an email is valid
function isEmailValid($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
// Function to generate a random validation code
function generateValidationCode() {
$code = rand(100000, 999999);
$novaCode = "NOVA23-" . $code;
return $novaCode;
}
// Function to fetch detailed errors for debugging
function getDetailedError(Throwable $exception) {
return sprintf(
"Exception message: %s\nException code: %s\nException file: %s\nException line: %s\n",
$exception->getMessage(),
$exception->getCode(),
$exception->getFile(),
$exception->getLine()
);
}
// Database connection details (Update with your actual credentials)
$host = 'localhost';
$dbUsername = 'root';
$password = 'password';
$dbName = 'database';
// Variables for displaying messages to the user
$message = "";
$messageClass = "";
$updateMessage = "";
$updateMessageClass = "";
$name = "";
try {
// Establish a database connection using PDO with prepared statements
$db = new PDO("mysql:host=$host;dbname=$dbName;charset=utf8mb4", $dbUsername, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Handle the request form submission
if (isset($_POST["request-info"])) {
// Check if Nominee's Data is set
if (isset($_POST["c_name"], $_POST["c_cat"], $_POST["c_street"], $_POST["c_city"], $_POST["c_net"],
$_POST["name"], $_POST["last_name"], $_POST["email"], $_POST["city"])) {
// Sanitize the inputs
$c_name = htmlspecialchars($_POST["c_name"]);
$c_cat = htmlspecialchars($_POST["c_cat"]);
$c_street = htmlspecialchars($_POST["c_street"]);
$c_city = htmlspecialchars($_POST["c_city"]);
$c_net = htmlspecialchars($_POST["c_net"]);
$name = htmlspecialchars($_POST["name"]);
$last_name = htmlspecialchars($_POST["last_name"]);
$email = htmlspecialchars($_POST["email"]);
$city = htmlspecialchars($_POST["city"]);
// Handle Errors
if (!isEmailValid($email)) {
$message = "Ungültige E-Mail-Adresse!";
$messageClass = "bad";
} else {
// Check if the Nominator is in nova_nominator_24
$checkNominatorQuery = "SELECT * FROM nova_nominator_24 WHERE EMail = :email AND request_verified = 'YES'";
$checkNominatorStatement = $db->prepare($checkNominatorQuery);
$checkNominatorStatement->bindParam(':email', $email);
$checkNominatorStatement->execute();
if ($checkNominatorStatement->rowCount() > 0) {
$existingUser = $checkNominatorStatement->fetch(PDO::FETCH_ASSOC);
$existingUserName = $existingUser['Name'];
$message = "Hallo $name, du hast bereits $c_name nominiert!";
$messageClass = "bad";
} else {
// Insert Nominee data into nova_nominees_24
$insertNomineeQuery = "INSERT INTO nova_nominees_24 (Candidate_Name, Categorie_ID, Street, Internet, City)
VALUES (:c_name, :c_cat, :c_street, :c_net, :c_city)";
$insertNomineeStatement = $db->prepare($insertNomineeQuery);
$insertNomineeStatement->bindParam(':c_name', $c_name);
$insertNomineeStatement->bindParam(':c_cat', $c_cat);
$insertNomineeStatement->bindParam(':c_street', $c_street);
$insertNomineeStatement->bindParam(':c_net', $c_net);
$insertNomineeStatement->bindParam(':c_city', $c_city);
$insertNomineeStatement->execute();
// Get the last inserted nominee ID
$nomineeId = $db->lastInsertId();
$request_verified = "NO";
// Generate validation code
$validationCode = generateValidationCode();
// Insert Nominator data into nova_nominator_24
$insertNominatorQuery = "INSERT INTO nova_nominator_24 (Name, LastName, EMail, City, Validation_code, request_verified, Nominee_ID)
VALUES (:name, :last_name, :email, :city, :validation_code, :request_verified, :nominee_id)";
$insertNominatorStatement = $db->prepare($insertNominatorQuery);
$insertNominatorStatement->bindParam(':name', $name);
$insertNominatorStatement->bindParam(':last_name', $last_name);
$insertNominatorStatement->bindParam(':email', $email);
$insertNominatorStatement->bindParam(':city', $city);
$insertNominatorStatement->bindParam(':validation_code', $validationCode);
$insertNominatorStatement->bindParam(':request_verified', $request_verified);
$insertNominatorStatement->bindValue(':nominee_id', $nomineeId);
$insertNominatorStatement->execute();
// Send E-mail with Validation Code
$subject = 'Validation Code for Nominierung';
$body = "Dear $name,\n\nYour validation code is: $validationCode";
$headers = "From: [email protected]"; // Change this to your email address
mail($email, $subject, $body, $headers);
$message = "Hallo $name, im Namen von $c_name, bedanken wir uns für die Teilnahme an unserer Preisverleihung";
$messageClass = "good";
}
}
// Prepare JSON response
$response = [
'success' => true,
'message' => $message,
'messageClass' => $messageClass,
];
// Send JSON response
echo json_encode($response);
// End the script execution after sending the JSON response
}
} elseif (isset($_POST["verify-request"])) {
// Verify-Request
if (isset($_POST["email_step3"], $_POST["validation_code"])) {
$email = htmlspecialchars($_POST["email_step3"]);
$validation_code = htmlspecialchars($_POST["validation_code"]);
$request_verified = "YES";
// Check if the validation code is correct
$checkValidationCodeQuery = "SELECT * FROM nova_nominator_24 WHERE EMail = :email AND Validation_code = :validation_code";
$checkValidationCodeStatement = $db->prepare($checkValidationCodeQuery);
$checkValidationCodeStatement->bindParam(':email', $email);
$checkValidationCodeStatement->bindValue(':validation_code', $validation_code);
$checkValidationCodeStatement->execute();
if ($checkValidationCodeStatement->rowCount() > 0) {
// Update the request_verified status
$updateDataQuery = "UPDATE nova_nominator_24 SET request_verified = :request_verified WHERE EMail = :email";
$updateDataStatement = $db->prepare($updateDataQuery);
$updateDataStatement->bindParam(':request_verified', $request_verified);
$updateDataStatement->bindParam(':email', $email);
$updateDataStatement->execute();
// Send update email to service team
$serviceTeamEmail = '[email protected]'; // Change this to your service team's email address
$subject = 'Nomination Verified';
$body = "The nomination for $c_name by $name $last_name has been verified.";
$headers = "From: [email protected]"; // Change this to your email address
mail($serviceTeamEmail, $subject, $body, $headers);
$updateMessage = "Vielen Dank, deine Nominierung wurde erfolgreich verifiziert!";
$updateMessageClass = "good";
} else {
$updateMessage = "Die Verifizierung ist fehlgeschlagen. Überprüfe bitte deine Eingaben und versuche es erneut.";
$updateMessageClass = "bad";
}
}
}
// Prepare JSON response
$response = [
'success' => true,
'updateMessage' => $updateMessage,
'updateMessageClass' => $updateMessageClass,
];
// End the script execution after sending the JSON response
} catch (PDOException $e) {
// Log rotation (optional): Check log file size and rotate if needed
$errorLogPath = 'error.log';
$maxLogSize = 1048576; // 1 MB
if (file_exists($errorLogPath) && filesize($errorLogPath) > $maxLogSize) {
// Rename the current log file with a timestamp
$newLogName = 'error_' . date('YmdHis') . '.log';
rename($errorLogPath, $newLogName);
}
// Log detailed error information to a file
$errorLog = fopen('error.log', 'a');
fwrite($errorLog, getDetailedError($e));
fclose($errorLog);
// Display a generic error message to the user
$message = "Es ist ein Fehler aufgetreten. Bitte versuche es später erneut.";
$messageClass = "bad";
} finally {
// Close the database connection
$db = null;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nominierungsformular 2024</title>
<style>
/* Add your CSS styles here */
.hide-current-step {
transform: translateX(-100%);
opacity: 0;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.show-next-step {
transform: translateX(0) !important;
opacity: 1 !important;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.hide-previews-step {
transform: translateX(100%);
opacity: 0;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.show-previews-step {
transform: translateX(0) !important;
opacity: 1;
transition: transform 0.3s ease, opacity 0.3s ease;
}
</style>
</head>
<body>
<section id="nominate">
<div class="n-inf">
<h1>Nominierungsformular für 2024 in München</h1> <br>
<p>Damit eine Nominierung in Betracht gezogen werden kann, muss sie bis zum 20. Januar 2023 eingegangen sein.
Bereits die Nichterfüllung von nur drei der allgemeinen <a href="?page=terms" class="btn">Anforderungskriterien</a> kann zum Ausschluss aus der weiteren Bearbeitung führen.</p><br>
<p>Für Fragen stehen wir gerne zur Verfügung. Bitte sende eine E-Mail an: <mark> <a href="mailto:[email protected]?subject=NOVA 24 - Anfrage">[email protected]</a></mark></p>
</div>
<div id="nomination-form-group">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="request-info">
<!-- STEP ONE -->
<div class="f-steps form_step_1" style="opacity: 1;">
<span class="stp-heading"><sup>1</sup> Ich nominiere</span> <br> <br> <br>
<!-- Your existing form fields and markup for step 1 -->
<div class="input_wrap">
<input type="text" name="c_name" id="c_name" autocomplete="off" placeholder="" class="form_input">
<label for="c_name">Name / Firma:</label> <br>
<small class="emt-c-name-e-msg"></small>
</div> <br> <br>
<div class="input_wrap">
<select name="c_cat" id="c_cat">
<option value="" selected disabled hidden>Kategorie</option>
<option value="1">Club</option>
<option value="2">Bar</option>
<option value="3">Dj</option>
<option value="4">Veranstalter</option>
<option value="5">Tanzschule</option>
<option value="6">Performance Artist</option>
</select>
<br>
<small class="emt-c-cat-e-msg"></small>
</div> <br> <br>
<div class="input_wrap">
<input type="text" name="c_street" id="c_street" autocomplete="on" placeholder="" class="form_input">
<label for="c_street">Straße + Nr.:</label> <br>
<small class="emt-c-street-e-msg"></small>
</div> <br> <br>
<div class="input_wrap">
<input type="text" name="c_city" id="c_city" autocomplete="on" placeholder="" class="form_input">
<label for="c_city">Stadt:</label> <br>
<small class="emt-c-city-e-msg"></small>
</div> <br> <br>
<div class="input_wrap">
<input type="text" name="c_net" id="c_net" autocomplete="off" placeholder="" class="form_input">
<label for="c_net">Internet / Social Media / Telefon:</label> <br>
<small class="emt-c-net-e-msg"></small>
</div> <br>
<div class="btn_wrap">
<button type="button" id="showStepTwoButton">Weiter</button>
</div>
</div>
<!-- STEP TWO -->
<div class="f-steps form_step_2" style="display: none; opacity: 0; transform: translateX(100%);">
<span class="stp-heading"> <sup>2</sup> Deine Informationen</span> <br> <br> <br>
<!-- Your existing form fields and markup for step 2 -->
<div class="input_wrap">
<input type="text" name="name" id="name" autocomplete="off" placeholder="" class="form_input">
<label for="name">Vorname:</label> <br>
<small class="emt-n-name-e-msg"></small>
</div> <br> <br>
<div class="input_wrap">
<input type="text" name="last_name" id="last_name" autocomplete="off" placeholder="" class="form_input">
<label for="last_name">Nachname:</label> <br>
<small class="emt-n-l-name-e-msg"></small>
</div> <br> <br>
<div class="input_wrap">
<input type="email" name="email" id="email" autocomplete="on" placeholder="" class="form_input">
<label for="email">E-Mail:</label> <br>
<small class="emt-n-email-e-msg"></small>
</div> <br> <br>
<div class="input_wrap">
<input type="tel" name="phone" id="phone" autocomplete="on" placeholder="" class="form_input">
<label for="phone">Telefon:</label> <br>
<small class="emt-n-phone-e-msg"></small>
</div> <br> <br>
<div class="input_wrap">
<input type="text" name="city" id="city" autocomplete="on" placeholder="" class="form_input">
<label for="city">Stadt:</label> <br>
<small class="emt-n-city-e-msg"></small>
</div> <br>
<div class="btn_wrap">
<!-- Use type="button" to prevent form submission -->
<button type="button" id="showStepOneButton" >Zurück</button>
<!-- Use type="button" to prevent form submission -->
<button type="button" id="showStepThreeButton">Abschicken</button>
</div>
</div>
<div class="errors">
<span class="<?php echo $messageClass ?>">
<?php echo $message; ?>
</span>
</div>
</form>
<!-- VALIDATION STEP -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="verify-request" style="display: none">
<!-- STEP THREE -->
<div class="f-steps form_step_3" style="opacity: 0; transform:translateX(100%)">
<!-- Your existing form fields and markup for step 3 -->
<span class="stp-heading"> <sup>3</sup> Anfrage Validieren</span> <br> <br>
<p>Um sicherzustellen, dass deine Anfrage legitim ist, haben wir einen Bestätigungscode an deine E-Mail-Adresse gesendet.</p>
<br> <br>
<div class="input_wrap">
<input type="email" name="email_step3" id="email_step3" autocomplete="on" placeholder="" class="form_input">
<label for="email_step3">E-Mail:</label>
</div> <br> <br>
<div class="input_wrap">
<input type="text" name="validation_code" id="validation_code" placeholder="" required class="form_input">
<label for="validation_code">Validierungscode:</label>
</div> <br>
<div id="result"></div>
<div class="btn_wrap">
<button type="submit" name="verify">Validieren</button>
</div>
</div>
<div class="errors">
<span class="<?php echo $updateMessageClass ?>">
<?php echo $updateMessage; ?>
</span>
</div>
</form>
</div>
</section>
<!-- Add this script section to your HTML file -->
<script>
document.addEventListener('DOMContentLoaded', function (){
let isValid = true;
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function validatePhoneNumber(phone) {
const phoneRegex = /^[0-9]+$/;
return phoneRegex.test(phone);
}
const firstForm = document.getElementById('request-info');
const secondForm = document.getElementById('verify-request');
const firstStep = document.querySelector('.form_step_1');
const secondStep = document.querySelector('.form_step_2');
const thirdStep = document.querySelector('.form_step_3');
function validateField(value, errorElement, errorMessage) {
errorElement.textContent = '';
if (value === '') {
errorElement.textContent = errorMessage;
return false;
}
return true;
}
function ShowStepTwo(event) {
event.preventDefault();
const candidateName = document.getElementById('c_name').value.trim();
const candidateCat = document.getElementById('c_cat').value;
const candidateStreet = document.getElementById('c_street').value.trim();
const candidateCity = document.getElementById('c_city').value.trim();
const candidateNet = document.getElementById('c_net').value.trim();
const errors = [
validateField(candidateName, document.querySelector('.emt-c-name-e-msg'), 'Dieses Feld darf nicht leer sein!'),
validateField(candidateCat, document.querySelector('.emt-c-cat-e-msg'), 'Eine Kategorie wählen!'),
validateField(candidateStreet, document.querySelector('.emt-c-street-e-msg'), 'Bitte Straße und Hausnummer eingeben!'),
validateField(candidateCity, document.querySelector('.emt-c-city-e-msg'), 'Bitte Stadt eingeben!'),
validateField(candidateNet, document.querySelector('.emt-c-net-e-msg'), 'Kontaktdaten eintragen!'),
];
if (errors.every(Boolean)) {
firstStep.classList.add('hide-current-step');
setTimeout(() => {
firstStep.style.display = 'none';
}, 300);
secondStep.style.display = 'block';
setTimeout(() => {
secondStep.classList.add('show-next-step');
}, 300);
}
}
function ShowStepOne() {
secondStep.classList.remove('show-next-step');
setTimeout(() => {
secondStep.style.display = 'none';
}, 300);
firstStep.style.display = 'block';
setTimeout(() => {
firstStep.classList.remove('hide-current-step');
}, 300);
}
function ShowStepThree(event) {
event.preventDefault();
isValid = true;
const n_name = document.getElementById('name').value.trim();
const n_lname = document.getElementById('last_name').value.trim();
const n_email = document.getElementById('email').value.trim();
const n_phone = document.getElementById('phone').value.trim();
const n_city = document.getElementById('city').value.trim();
const NominatorNameElement = document.getElementById('name');
const NominatorLnameElement = document.getElementById('last_name');
const NominatorEmailElement = document.getElementById('email');
const NominatorPhoneElement = document.getElementById('phone');
const NominatorCityElement = document.getElementById('city');
const NominatorNameError = document.querySelector('.emt-n-name-e-msg');
const NominatorLnameError = document.querySelector('.emt-n-l-name-e-msg');
const NominatorEmailError = document.querySelector('.emt-n-email-e-msg');
const NominatorPhoneError = document.querySelector('.emt-n-phone-e-msg');
const NominatorCityError = document.querySelector('.emt-n-city-e-msg');
NominatorNameError.textContent = '';
NominatorLnameError.textContent = '';
NominatorEmailError.textContent = '';
NominatorPhoneError.textContent = '';
NominatorCityError.textContent = '';
if (n_name === '') {
NominatorNameError.textContent = 'Bitte gebe deinen Vornamen ein!';
NominatorNameElement.classList.add('error');
isValid = false;
}
if (n_lname === '') {
NominatorLnameError.textContent = 'Bitte gebe deinen Nachnamen ein!';
NominatorLnameElement.classList.add('error');
isValid = false;
}
if (n_email === '') {
NominatorEmailError.textContent = 'Bitte gebe deine E-Mail Adresse ein!';
NominatorEmailElement.classList.add('error');
isValid = false;
} else if (!validateEmail(n_email)) {
NominatorEmailError.textContent = 'Ungültige E-Mail-Adresse!';
NominatorEmailElement.classList.add('error');
isValid = false;
}
if (n_phone === '') {
NominatorPhoneError.textContent = 'Bitte gebe deine Telefonnummer ein!';
NominatorPhoneElement.classList.add('error');
isValid = false;
} else if (!validatePhoneNumber(n_phone)) {
NominatorPhoneError.textContent = 'Ungültige Telefonnummer!';
NominatorPhoneElement.classList.add('error');
isValid = false;
}
if (n_city === '') {
NominatorCityError.textContent = 'Trage deine Stadt ein!';
NominatorCityElement.classList.add('error');
isValid = false;
}
if (isValid) {
// Use Ajax to submit the second form (verify-request) and handle the response
const secondForm = document.getElementById('verify-request');
const formData = new FormData(secondForm);
const actionUrl = secondForm.getAttribute('action');
submitFormData(actionUrl, formData);
secondStep.classList.add('hide-current-step');
setTimeout(() => {
firstForm.style.display = 'none';
secondForm.style.display = 'block';
}, 300);
setTimeout(() => {
thirdStep.classList.add('show-next-step');
}, 400);
}
}
function submitFormData(actionUrl, formData) {
fetch(actionUrl, {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Handle successful submission (e.g., display success message)
console.log('Form submitted successfully:', data.message);
} else {
// Handle errors or display a message
console.error('Form submission failed:', data.updateMessage);
}
})
.catch(error => {
console.error('Error during form submission:', error);
});
}
document.getElementById('showStepTwoButton').addEventListener('click', function (event) {
event.preventDefault();
ShowStepTwo();
});
document.getElementById('showStepOneButton').addEventListener('click', function (event) {
event.preventDefault();
ShowStepOne();
});
document.getElementById('showStepThreeButton').addEventListener('click', function (event) {
event.preventDefault();
ShowStepThree(event);
});
});
</script>
</body>
</html>