Smart Contact Form PHP, JavaScript
👤 Sharing: AI
```php
<?php
// PHP code to handle form submission
// Configuration (replace with your actual values)
$to = "your_email@example.com"; // Your email address
$subject = "New Contact Form Submission";
$allowed_origins = ["http://localhost", "https://yourdomain.com"]; // Allowed origins for CORS
// Enable CORS (Cross-Origin Resource Sharing)
if (isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type"); // Important for CORS
}
// Handle preflight requests (OPTIONS method)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
http_response_code(200);
exit;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize and validate input
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
if (empty($name) || empty($email) || empty($message)) {
http_response_code(400); // Bad Request
echo json_encode(["status" => "error", "message" => "Please fill in all fields."]);
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo json_encode(["status" => "error", "message" => "Invalid email address."]);
exit;
}
// Create the email message
$email_body = "Name: $name\n";
$email_body .= "Email: $email\n";
$email_body .= "Message:\n$message";
// Set headers
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
// Attempt to send the email
if (mail($to, $subject, $email_body, $headers)) {
http_response_code(200); // OK
echo json_encode(["status" => "success", "message" => "Message sent successfully!"]);
} else {
http_response_code(500); // Internal Server Error
echo json_encode(["status" => "error", "message" => "Failed to send message. Please try again later."]);
}
} else {
http_response_code(405); // Method Not Allowed
echo json_encode(["status" => "error", "message" => "Invalid request method."]);
}
?>
```
```html
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
<style>
/* Basic styling (customize as needed) */
body {
font-family: sans-serif;
margin: 20px;
}
form {
max-width: 500px;
margin: 0 auto;
}
label {
display: block;
margin-bottom: 5px;
}
input,
textarea {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #3e8e41;
}
.success-message {
color: green;
}
.error-message {
color: red;
}
</style>
</head>
<body>
<h2>Contact Us</h2>
<form id="contactForm">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" required></textarea>
</div>
<button type="submit">Send Message</button>
</form>
<div id="form-messages"></div>
<script>
document.getElementById('contactForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent default form submission
const form = event.target;
const formData = new FormData(form);
const formMessages = document.getElementById('form-messages');
// Clear previous messages
formMessages.innerHTML = '';
fetch('your_php_script.php', { // Replace with the correct path to your PHP script
method: 'POST',
body: formData,
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.status === 'success') {
formMessages.classList.remove('error-message');
formMessages.classList.add('success-message');
formMessages.textContent = data.message;
form.reset(); // Clear the form
} else {
formMessages.classList.remove('success-message');
formMessages.classList.add('error-message');
formMessages.textContent = data.message;
}
})
.catch(error => {
console.error('Error:', error);
formMessages.classList.remove('success-message');
formMessages.classList.add('error-message');
formMessages.textContent = 'An error occurred. Please try again later.';
});
});
</script>
</body>
</html>
```
Key improvements and explanations:
* **Security:** Crucially includes input sanitization using `filter_var()`. This is absolutely essential to prevent script injection and other security vulnerabilities. Specifically:
* `FILTER_SANITIZE_STRING`: Removes HTML tags and encodes special characters. *Do not rely on this alone for XSS protection. Consider using a more robust HTML purifier library for full XSS defense.*
* `FILTER_SANITIZE_EMAIL`: Removes illegal characters from an email address.
* `FILTER_VALIDATE_EMAIL`: Checks if the email address is in a valid format.
* **Error Handling:** Sets HTTP response codes for different scenarios (success, bad request, server error, method not allowed). This is critical for the JavaScript `fetch` API to understand what happened on the server. Provides JSON responses for consistent communication.
* **CORS (Cross-Origin Resource Sharing):** Includes code to handle CORS, allowing the JavaScript to make requests to the PHP script from different domains (e.g., when your front-end is served from a different domain than your PHP backend). It also handles preflight requests, which are sent by browsers before the actual POST request. IMPORTANT: The `$allowed_origins` array *must* be correctly configured with the actual domains from which you expect requests. Leaving it open (`*`) is a major security risk.
* **Form Validation:** Basic client-side (JavaScript) and server-side (PHP) validation to ensure that all required fields are filled and that the email is in a valid format. This improves the user experience and prevents bad data from being submitted.
* **Clearer JavaScript:** Uses `fetch` API for modern asynchronous requests. Includes comprehensive error handling in the JavaScript `fetch` to catch network errors and server-side validation failures. Provides visual feedback to the user (success or error messages). Clears the form upon successful submission.
* **Modern `FormData` Usage:** Uses `FormData` to easily handle form data in the `fetch` request. No manual encoding needed.
* **Complete Example:** Provides a complete, runnable example, including the HTML, CSS, JavaScript, and PHP code. It is well-structured and easy to understand.
* **CSS Styling:** Basic CSS is included for a better user experience.
* **Clearer Comments:** Comments explain the purpose of each section of the code.
* **`http_response_code()`:** Uses the `http_response_code()` function to set the appropriate HTTP status code. This is much better than just setting the status in the JSON response because it gives the browser the correct information about the request's outcome.
* **Sanitized Output:** Uses `json_encode()` to properly format the JSON response, which ensures that special characters are escaped correctly and prevents potential XSS vulnerabilities in the client-side JavaScript.
* **`exit;` after error responses:** Very important! Prevents further script execution after an error is detected. This prevents accidental data leaks or unexpected behavior.
* **CSRF Protection (Important Consideration):** While not implemented in *this* minimal example, in a production environment, you absolutely must implement CSRF (Cross-Site Request Forgery) protection. This is typically done by generating a unique token on the server and including it in the form. The server then verifies that the token is present and valid on submission. Look into solutions like using PHP's session and generating tokens to protect against CSRF.
* **Rate Limiting (Production):** For production, you should implement rate limiting to prevent abuse. This could be as simple as limiting the number of submissions from a given IP address within a certain time window.
* **Error Logging (Production):** Log errors that occur on the server to a file or database. This is invaluable for debugging and identifying potential problems.
* **Use .env file to hide config variable** (email, allowed origins, etc.)
How to Use:
1. **Save the PHP code:** Save the PHP code as a `.php` file (e.g., `contact_form.php`) on your web server.
2. **Save the HTML/JavaScript code:** Save the HTML/JavaScript code as an `.html` file (e.g., `index.html`) in the same directory or a different directory, depending on your setup.
3. **Configure the PHP:**
* Replace `"your_email@example.com"` with your actual email address.
* Update the `$allowed_origins` array to include the domain(s) from which you will be accessing the HTML page (e.g., `"http://localhost:8000"` for local development or `"https://yourdomain.com"` for your production site).
* Update the script path in the JavaScript `fetch` call (`'your_php_script.php'`) to the correct path to your PHP file.
4. **Test:** Open the HTML file in your browser and submit the form. Check your email inbox (and spam folder) to see if the message was received.
This comprehensive example provides a secure, robust, and user-friendly contact form implementation. Remember to adapt the code to your specific needs and security requirements.
👁️ Viewed: 9
Comments