I'm about to make a contact form with reCaptcha but when I apply the reCaptcha and make validation on that, my other validation on the forms won't work and I just can't seem to find out why? I have tried other ways to make the recaptcha validate but nothing works?
OLD CODE START:
if(isset($_POST['submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "MY SECRET CODE GOES HERE";
$response = file_get_contents($url."? secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
header('Location:contact.php?CaptchaPass=True');
}else{
header('Location:contact.php?CaptchaFail=True');
}
}
?>
OLD CODE END ^
^ CODE HAS BEEN REPLACED WITH:
<?php
$valid_recaptcha = false;
if(isset($_POST['submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "MY SECRET CODE GOES HERE";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
$valid_recaptcha = true;
}
if($valid_recaptcha){
}else{
}
}
?>
NEW CODE END ^
<?php
// Set email variables
$email_to = 'MY MAIL GOES HERE';
$email_subject = 'Formular: Kontakt os';
// Set required fields
$required_fields = array('navn', 'postnr', 'by', 'email', 'telefon', 'besked');
// set error messages
$error_messages = array(
'navn' => 'Skriv venligst dit navn',
'postnr' => 'Skriv venligst et gyldigt post nr',
'by' => 'Skriv venligst et gyldigt bynavn',
'email' => 'Skriv venligst en gyldig e-mail adresse',
'telefon' => 'Skriv venligst et gyldigt telefon nr',
'besked' => 'Skriv venligst en besked'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'Ny besked fra kontaktformular: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Kontakt os</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/contactform.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui- compressed.js"></script>
<script type="text/javascript" src="validation/validation.js"></script>
<script type="text/javascript">
var navnError = '<?php echo $error_messages['navn']; ?>';
var postnrError = '<?php echo $error_messages['postnr']; ?>';
var byError = '<?php echo $error_messages['by']; ?>';
var emailError = '<?php echo $error_messages['email']; ?>';
var telefonError = '<?php echo $error_messages['telefon']; ?>';
var beskedError = '<?php echo $error_messages['besked']; ?>';
</script>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<div id="formWrap">
<h3>Kontakt os</h3>
OLD CODE START:
<?php if(isset($_GET['CaptchaPass'])){ ?>
<div class="detail" style="margin-left: 200px;" align="center">Din besked er nu sendt</div><br />
<?php } ?>
<?php if(isset($_GET['CaptchaFail'])){ ?>
<div class="detail" style="margin-left: 200px;" align="center">reCaptcha fejlede, prøv venligst igen</div><br />
<?php } ?>
OLD CODE END ^
^ CODE HAS BEEN REPLACED WITH:
<?php
if(isset($_POST['submit'])){
if($valid_recaptcha){
?>
<?php
}else{
?>
<div class="detail" style="margin-left: 200px;" align="center">Kontrol fejlede, prøv venligst igen</div><br />
<?php
}
}
?>
NEW CODE END ^
REST OF THE CODE HAS NOT BEEN EDITED.
<div id="form">
<?php if($form_complete === FALSE): ?>
<form action="contact.php" method="post" id="comments_form">
<div class="row">
<div class="label">Navn</div><!-- slut .label -->
<div class="input">
<input type="text" id="navn" class="detail" name="navn" value="<?php echo isset($_POST['navn'])? $_POST['navn'] : ''; ?>" /><?php if(in_array('navn', $validation)): ?><span class="error"><?php echo $error_messages['navn']; ?> </span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">Post nr.</div><!-- slut .label -->
<div class="input">
<input type="text" id="postnr" class="detail" name="postnr" value="<?php echo isset($_POST['postnr'])? $_POST['postnr'] : ''; ?>" /><?php if(in_array('postnr', $validation)): ?><span class="error"><?php echo $error_messages['postnr']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">By</div><!-- slut .label -->
<div class="input">
<input type="text" id="by" class="detail" name="by" value="<?php echo isset($_POST['by'])? $_POST['by'] : ''; ?>" /><?php if(in_array('by', $validation)): ?><span class="error"><?php echo $error_messages['by']; ?></span> <?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">E-mail adresse</div><!-- slut .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">Telefon</div><!-- slut .label -->
<div class="input">
<input type="text" id="telefon" class="detail" name="telefon" value="<?php echo isset($_POST['telefon'])? $_POST['telefon'] : ''; ?>" /><?php if(in_array('telefon', $validation)): ?><span class="error"><?php echo $error_messages['telefon']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">Besked</div><!-- slut .label -->
<div class="input">
<textarea id="comment" name="besked" class="mess"><?php echo isset($_POST['besked'])? $_POST['besked'] : ''; ?>
</textarea><?php if(in_array('besked', $validation)): ?><span class="error"> <?php echo $error_messages['besked']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<br /><div class="g-recaptcha" data- sitekey="6LfEZw0TAAAAAEsi1Gba_D98TgEIN3tw0YUfeB63" style="margin-left: 200px;"> </div>
<div class="submit">
<input type="submit" id="submit" name="submit" value="Send besked" /><br /> <br />
</form>
</div><!-- .submit -->
<?php else: ?>
<p style="font-size:25px; font-family:Arial, sans-serif; margin- left:25px;">Tak for din besked</p>
<script type="text/javascript">
setTimeout('ourRedirect()',5000)
function ourRedirect(){
location.href='http://www.apple.dk'
}
</script>
<?php endif; ?>
</div><!-- slut #form -->
</div><!-- slut formWrap -->
</body>
</html>
Problem
Your header inside if(isset($_POST['submit'])){ ... } is causing this error. header() is used to send a raw HTTP header to the browser. Whenever browser requests a page to the server, before server responds, it first sends the headers i.e what browser can expect next and browser can render itself accordingly, and then server sends the actual page.
if(isset($_POST['submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "MY SECRET CODE GOES HERE";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
header('Location:contact.php?CaptchaPass=True'); // this is causing the error
}else{
header('Location:contact.php?CaptchaFail=True'); // this might cause the same problem in near future
}
}
Solution
Instead of validating recaptcha using superglobal $_GET, you can use a simple boolean variable to validate it.
$valid_recaptcha = false;
if(isset($_POST['submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "MY SECRET CODE GOES HERE";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
$valid_recaptcha = true;
}
if($valid_recaptcha){
// you should do all your input validation and form processing here
}else{
// user has entered wrong recaptcha
}
}
And then you can render your page accordingly.
Edited:
Instead of this:
<?php if(isset($_GET['CaptchaPass'])){ ?>
<div class="detail" style="margin-left: 200px;" align="center">Din besked er nu sendt</div><br />
<?php } ?>
<?php if(isset($_GET['CaptchaFail'])){ ?>
<div class="detail" style="margin-left: 200px;" align="center">reCaptcha fejlede, prøv venligst igen</div><br />
<?php } ?>
you can do something like this to display the message:
<?php
if(isset($_POST['submit'])){
if($valid_recaptcha){
?>
<div class="detail" style="margin-left: 200px;" align="center">Din besked ernu sendt</div><br />
<?php
}else{
?>
<div class="detail" style="margin-left: 200px;" align="center">reCaptcha fejlede, prøv venligst igen</div><br />
<?php
}
}
?>
Re-edited:
I've typed and tested the entire code on my local machine, and it's working just as you had expected. I didn't touch validation.js because I think you can do browser side validation later on your own. Replace the $private_key with your secret private key, add a valid email address to $email_to and run the code on your system.
<?php
/*
* I don't know Danish language, but somehow I managed to understand your input field names.
* Thanks to google translate. :)
*/
function validate_email_address($email = false) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? true : false;
}
function remove_email_injection($field = false) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
// Set email variables
$email_to = 'MY MAIL GOES HERE';
$email_subject = 'Formular: Kontakt os';
// Set required fields
$required_fields = array('navn', 'postnr', 'by', 'email', 'telefon', 'besked');
// set error messages
$error_messages = array(
'navn' => 'Skriv venligst dit navn',
'postnr' => 'Skriv venligst et gyldigt post nr',
'by' => 'Skriv venligst et gyldigt bynavn',
'email' => 'Skriv venligst en gyldig e-mail adresse',
'telefon' => 'Skriv venligst et gyldigt telefon nr',
'besked' => 'Skriv venligst en besked'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// boolean variable to validate recaptcha
$valid_recaptcha = false;
if(isset($_POST['submit'])){
// First validate recaptcha
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "MY SECRET CODE GOES HERE";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if($data->success) {
$valid_recaptcha = true;
}
if($valid_recaptcha){
// now process your form here. sanitize and validate input fields
// Sanitise POST array
foreach($_POST as $key => $value){
$_POST[$key] = remove_email_injection(trim($value));
}
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)){
array_push($validation, $field);
}
// check there is information in the field?
if($_POST[$field] == ''){
array_push($validation, $field);
}
// validate the email address supplied
if($field == 'email'){
if(!validate_email_address($_POST[$field])){
array_push($validation, $field);
}
}
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'Ny besked fra kontaktformular: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value){
if($key != 'submit' && $key != 'g-recaptcha-response') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Kontakt os</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/contactform.css" rel="stylesheet" type="text/css" />
<!--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui- compressed.js"></script>-->
<!--<script type="text/javascript" src="validation/validation.js"></script>-->
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<div id="formWrap">
<h3>Kontakt os</h3>
<?php
if(isset($_POST['submit'])){
if(!$valid_recaptcha){
// error
?>
<div class="detail" style="margin-left: 200px;" align="center">Kontrol fejlede, prøv venligst igen</div><br />
<?php
}
}
?>
<div id="form">
<?php if($form_complete === FALSE): ?>
<form action="contact.php" method="post" id="comments_form">
<div class="row">
<div class="label">Navn</div><!-- slut .label -->
<div class="input">
<input type="text" id="navn" class="detail" name="navn" value="<?php echo isset($_POST['navn'])? $_POST['navn'] : ''; ?>" /><?php if(in_array('navn', $validation)): ?><span class="error"><?php echo $error_messages['navn']; ?> </span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">Post nr.</div><!-- slut .label -->
<div class="input">
<input type="text" id="postnr" class="detail" name="postnr" value="<?php echo isset($_POST['postnr'])? $_POST['postnr'] : ''; ?>" /><?php if(in_array('postnr', $validation)): ?><span class="error"><?php echo $error_messages['postnr']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">By</div><!-- slut .label -->
<div class="input">
<input type="text" id="by" class="detail" name="by" value="<?php echo isset($_POST['by'])? $_POST['by'] : ''; ?>" /><?php if(in_array('by', $validation)): ?><span class="error"><?php echo $error_messages['by']; ?></span> <?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">E-mail adresse</div><!-- slut .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">Telefon</div><!-- slut .label -->
<div class="input">
<input type="text" id="telefon" class="detail" name="telefon" value="<?php echo isset($_POST['telefon'])? $_POST['telefon'] : ''; ?>" /><?php if(in_array('telefon', $validation)): ?><span class="error"><?php echo $error_messages['telefon']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<div class="row">
<div class="label">Besked</div><!-- slut .label -->
<div class="input">
<textarea id="comment" name="besked" class="mess"><?php echo isset($_POST['besked'])? $_POST['besked'] : ''; ?>
</textarea><?php if(in_array('besked', $validation)): ?><span class="error"> <?php echo $error_messages['besked']; ?></span><?php endif; ?>
</div><!-- slut .input -->
</div><!-- slut .row -->
<br />
<div class="g-recaptcha" data-sitekey="6LfEZw0TAAAAAEsi1Gba_D98TgEIN3tw0YUfeB63"></div>
<div class="submit">
<input type="submit" id="submit" name="submit" value="Send besked" /><br /> <br />
</div><!-- .submit -->
</form>
<?php else: ?>
<p style="font-size:25px; font-family:Arial, sans-serif; margin-left:25px;">Tak for din besked</p>
<!--<script type="text/javascript">
setTimeout('ourRedirect()',5000)
function ourRedirect(){
location.href='http://www.apple.dk'
}
</script>-->
<?php endif; ?>
</div><!-- slut #form -->
</div><!-- slut formWrap -->
</body>
</html>
Related
I am trying to send form data from my contact.php page using PHPMailer. But it is not working properly. It is showing internal server error.
This is my contact.php form code. Can you see what is wrong with this code.
<?PHP
session_start();
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
require_once("/home/leasingexpertzz/public_html/helpers/security.php");
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Contact</title>
<?PHP include "header.php"; ?>
</head>
<body class="size-1140">
<!-- TOP NAV WITH LOGO -->
<header>
<?PHP include "nav.php"; ?>
</header>
<section>
<div id="head">
<div class="line">
<h1>Leasing Expertz</h1>
</div>
</div>
<div id="content" class="left-align contact-page">
<h1 class="sub-title">Reach us</h1>
<div class="line">
<div class="margin">
<div class="s-12 l-6">
<h2>Leasing Expertz</h2>
<address>
<p><i class="icon-home icon"></i> Plot no. P-25 1st floor, Uppal South End, Near Eldico Mentions.</p>
<p><i class="icon-globe_black icon"></i> Sohna Road, Gurugram, Haryana, India</p>
<p><i class="icon-mail icon"></i> leasingexpertzz#gmail.com</p>
</address>
<br />
<h2>Social</h2>
<p class="fb"><i class="icon-facebook icon"></i>Leasing Expertz</p>
<p class="linkedin"><i class="icon-linked_in icon"></i>Linked In</p>
<p class="twitter"><i class="icon-twitter icon"></i>Tweeter</p>
</div>
<div class="s-12 l-6">
<h2>Write to us</h2>
<form class="customform" method="post" action="email.php">
<div class="s-12 l-7"><input name="senderEmail" placeholder="Your e-mail" title="Your e-mail" type="text" <?PHP echo isset($fields['email']) ? 'value="' . e($fields['email']) . '"' : '' ?> />
<?PHP if(!empty($errors)) : ?>
<p> <?PHP echo implode('', $errors); ?></p>
<?PHP endif;?>
</div>
<div class="s-12 l-7"><input name="sender" placeholder="Your name" title="Your name" type="text" <?PHP echo isset($fields['name']) ? 'value="' . e($fields['name']) . '"' : '' ?>/>
<?PHP if(!empty($errors)) : ?>
<p> <?PHP echo implode('', $errors); ?></p>
<?PHP endif;?>
</div>
<div class="s-12 l-7"><input name="senderPhone" placeholder="Your phone number" title="Your Phone" type="text" <?PHP echo isset($fields['phone']) ? 'value="' . e($fields['phone']) . '"' : '' ?>/>
<?PHP if(!empty($errors)) : ?>
<p> <?PHP echo implode('', $errors); ?></p>
<?PHP endif;?>
</div>
<div class="s-12"><textarea placeholder="Your massage" name="message" rows="5" <?PHP echo isset($fields['message']) ? e($fields['message']) : '' ?>></textarea>
<?PHP if(!empty($errors)) : ?>
<p> <?PHP echo implode('', $errors); ?></p>
<?PHP endif;?>
</div>
<div class="s-12 m-6 l-4"><button type="submit">Submit Button</button></div>
</form>
</div>
</div>
</div>
</div>
<!-- MAP -->
<div id="map-block">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3508.9917339135745!2d77.03635061456353!3d28.419506282502333!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x390d229e71ef44dd%3A0x9931b80f30d32dd3!2sJMD+Megapolis!5e0!3m2!1sen!2sin!4v1492751226145" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</section>
<!-- FOOTER -->
<footer>
<?PHP include "footer.php"; ?>
</footer>
<script type="text/javascript" src="owl-carousel/owl.carousel.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#owl-demo").owlCarousel({
slideSpeed : 300,
autoPlay : true,
navigation : false,
pagination : false,
singleItem:true
});
$("#owl-demo2").owlCarousel({
slideSpeed : 300,
autoPlay : true,
navigation : false,
pagination : true,
singleItem:true
});
});
</script>
</body>
</html>
<?PHP
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>
Below is my email.php for PHPMailer.
<?php
session_start();
require_once("/home/leasingexpertzz/public_html/PHPMailer_5.2.0/PHPMailerAutoload.php");
$errors =[];
if(isset($_POST["senderEmail"], $_POST["sender"], $_POST["senderPhone"], $_POST["message"])){
$fields = [
'email'=> $_POST["senderEmail"],
'name' => $_POST["sender"],
'phone' => $_POST["senderPhone"],
'message' => $_POST["message"]
];
foreach ($fields as $field => $data) {
if(empty($data)){
$errors[] = 'The' . $field . 'is required.';
}
}
if(empty($errors)){
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "localhost"; // specify main and backup server
$mail->Port = 25;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "admin#leasingexpert.co.in"; // SMTP username
$mail->Password = "xxxxxxxxxxx"; // SMTP password
$mail->From = "admin#leasingexpert.co.in";
$mail->FromName = "Leasing Expert";
$mail->AddAddress("admin#leasingexpert.co.in"); // name is optional
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(); // set email format to HTML
$mail->Subject = "Here is the subject";
$mail->Body = 'From: ' . $fields['name'] . '(' . $fields['email'] . ')' . $fields['phone'] . '<p>' . $fields['message'] .. '</p>';
if($mail->Send())
{
header("Location: http://leasingexpert.co.in/confirmation.php");
die();
}
else{
$errors[] = 'Message could not be sent.';
}
header("Location: http://leasingexpert.co.in/confirmation.php");
}
}else{
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
?>
You should try reading the logs, which can be in different places depending on your OS and the server you're using (apache, nginx...).
You could also use xdebug
Internal Server Error messages indicate that something, in general, is wrong in programming.
While developing you have to enable to error log in PHP.ini file.
Then you can easily find out the errorenter link description here
I am having issues firing off an on-change in the department drop-down field not sure if i wrote it correctly. The error is Uncaught TypeError: Cannot read property 'style' of null. I am trying to select a department like claims then it will fire off an onchange to show another drop-down called workrequested. I have not filled all the departments yet but that should not mater if i want to test it on couple departments first. I think it has to do with dvPassport1.style.display
<script>
function ShowHideDiv1() {
var Department = document.getElementById("Department");
var divPassport1 = document.getElementById("divPassport1");
divPassport1.style.display = Department.value == "Claims" || Department.value == "Flat 1"|| Department.value == "Flat 2"|| Department.value == "Hanging Bulk" || Department.value == "Hanging Store North" || Department.value == "Hanging Store South" || Department.value == "Inventory Integrity" || Department.value == "Rack Shoes" || Department.value == "Fine Jewelry"? "block" : "none";
}
function ShowHideDiv2() {
var Department = document.getElementById("Department");
var divPassport2 = document.getElementById("divPassport2");
divPassport2.style.display = Department.value == "JackPotLane" ? "block" : "none";
}
</script>
<?=form_open('insert/create/', array(
'class' => 'form-horizontal',
'role' => 'form',
)); ?>
<div class="row">
<div class="container">
<h3>Validation Form</h3>
<br>
<div class="col-sm-6">
<div class="form-group">
<?php echo form_label('ZID', 'ZID', $attributes=array());?>
<?php echo form_input('ZID', set_value('ZID'), $attributes=array("class" => "form-control", "id"=>"ZID"));?>
<!--show error message -->
<div class="error"><?php echo form_error('ZID'); ?></div>
</div>
<div class="form-group">
<?php echo form_label('Employee Name', 'EmpName', $attributes=array());?>
<?php echo form_input('EmpName', set_value('EmpName'), $attributes=array("class" => "form-control", "id"=>"EmpName"));?>
<!--show error message -->
<div class="error"><?php echo form_error('EmpName'); ?></div>
</div>
<div class="form-group">
<?php echo form_label('Department', 'Department', $attributes=array());?>
<?php
$options = array(
""=>"Choose Department",
"Claims" => "Claims",
"Flat 1"=>"Flat 1");
?>
<?php echo form_dropdown('Department', $options,set_value('Department'),array("class" => "form-control", "id"=>"Department", "onchange" => "ShowHideDiv1();ShowHideDiv2();"));?>
<!--show error message -->
<div class="error"><?php echo form_error('Department'); ?></div>
</div>
<div class="form-group" id="divpassport1" style="display: none" >
<?php echo form_label('WorkRequested', 'WorkRequested', $attributes=array());?>
<?php
$options = array(
""=>"Choose WorkRequested",
"Cases Not Received" => "Cases Not Received",
"Master Pack"=>"Master Pack");
?>
<?php echo form_dropdown('WorkRequested', $options,set_value('WorkRequested'),array("class" => "form-control", "id"=>"WorkRequested"));?>
<!--show error message -->
<div class="error"><?php echo form_error('WorkRequested'); ?></div>
</div>
<div class="form-group" id="divpassport2" style="display: none" ">
<?php echo form_label('WorkRequested', 'WorkRequested', $attributes=array());?>
<?php
$options = array(
""=>"Choose jackpot WorkRequested",
"FYI" => "FYI",
"Request"=>"Request");
?>
<?php echo form_dropdown('WorkRequested', $options,set_value('WorkRequested'),array("class" => "form-control", "id"=>"WorkRequested"));?>
<!--show error message -->
<div class="error"><?php echo form_error('WorkRequested'); ?></div>
</div>
<div class="form-group">
<?php echo form_label('Description','ReqDescription', $attributes=array());?>
<?php echo form_textarea('ReqDescription',set_value('ReqDescription'),array("class"=>"form-control textarea","id"=>"ReqDescription"));?>
<!--show error ReqDescription -->
<div class="error"><?php echo form_error('ReqDescription'); ?></div>
</div>
<input type="hidden" name="DATEREQUESTED" value="<?php echo date("Y/m/d h:i:sa");?>" value="<?=set_value('DATEREQUESTED')?> " value="<?=set_value('DATEREQUESTED')?>">
<input type="hidden" class="form-control" id="Status" name="Status" value="Received" placeholder="Status" value="<?=set_value('Status')?>">
<div class="form-group">
<?php echo form_submit('submit', 'Submit', array("class"=>"btn-primary btn", "id"=>"submit"));?>
</div>
<?php echo form_close()?>
As far as I can see you want to get divPassport1 (divPassport1) and divPassport2 and not dvPassport1 and dvPassport2.
Change var dvPassport1 = document.getElementById("dvPassport1"); to var dvPassport1 = document.getElementById("divPassport1"); and second one respectively or correct the ids.
EDIT
I guess you are accessing elements too early and you DOM is not loaded yet. Move your js code to the end of page before closing body and wrap it following way to wait for window onload event:
<script>
(function() {
// your javascript code here
// the DOM will be available here
})();
</script>
The following code is to import a csv file into database.
<?php
include("includes/config.php");
if ($_POST['frmSubmit']) {
$file = $_FILES['frmUpload']['tmp_name']; // Get Temporary filename
if ($file) {
$handle = fopen($file,"r"); // Open the file and read
while ($strBookData = fgetcsv($handle, 10000, ",")) { // To get Array from CSV
$strDatas[] = $strBookData;
$strTableColumn = count($strBookData); // To Get Column count
}
if ($strDatas) {
$strInsertRecords = 0;
$strDuplicationRecords = 0;
$duplicateEmails = array();
$strDup = "";
if ($strTableColumn == 5) {
for($k=1; $k<count($strDatas); $k++) {
$strStatus = doCheckDuplication($strDatas[$k]['2']);
if ($strStatus==0) {
// Insert Code
doInsertEmployeeDetails($strDatas[$k]['0'], $strDatas[$k]['1'], $strDatas[$k]['2'], $strDatas[$k]['3'], $strDatas[$k]['4']);
$strInsertRecords++; // To Get Inserted Records Count.
} else {
$strDuplicationRecords++; // To Get Duplication Records Count.
$duplicateEmails[$strDuplicationRecords] = $strDatas[$k]['2'];
$strDup.= $duplicateEmails[$strDuplicationRecords]. "\n";
}
}
//printArray($duplicateEmails);
if (count($strDatas)-1 == $strInsertRecords) {
$strMsg = 'Employee details inserted successfully';
$strClass = 'Succes';
}
if (count($strDatas)-1 != $strInsertRecords) {
$strMsg = 'Employee details inserted successfully, some of names already exists';
$strClass = 'Error';
}
if (count($strDatas)-1 == $strDuplicationRecords) {
$strMsg = 'Employee details are already exists';
$strClass = 'Error';
}
} else {
$strMsg = 'Column mis-match, Please verify the file.';
$strClass = 'Error';
}
}
} else {
$strMsg = 'Please upload the valid file.';
$strClass = 'Error';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Employee Details</title>
<link href="css/employee.css" rel="stylesheet" type="text/css"/>
<script src="js/employee.js" type="text/javascript"></script>
</head>
<body>
<form id="frmEmployee" name="frmEmployee" enctype="multipart/form-data" method="post" action="" onsubmit="return validation();">
<div class="all">
<div class="alls">
<div class="main">
<div class="inner">
<div class="top">
<p> </p>
<div class="text" align="center">
<p class="det">EMPLOYEE DETAILS</p>
</div>
<p> </p>
</div>
<p> </p>
<div align="center"><p class="<?php echo $strClass; ?>"><?php echo $strMsg; ?></p></div>
<p> </p>
<div class="ntop">
<div class="nnn">
<div class="name">CSV Upload:</div>
<div class="field">
<label>
<input type="file" name="frmUpload" id="frmUpload" onblur="checkEmpty('frmUpload', 'error_file', 'Please upload your file');"/>
</label>
</div>
<p> </p>
</div>
<div class="span">
<div class="span2"><span id="error_file" class="spans"></span></div>
<p> </p>
</div>
</div>
<p> </p>
<p> </p>
<div class="submit">
<div class="sub">
<div class="but">
<label>
<input type="submit" name="frmSubmit" id="frmSubmit" value="Submit" class="subb" />
</label>
</div>
<div class="but">
<label>
<input type="reset" name="frmReset" id="frmReset" value="Reset" class="subb" />
</label>
</div>
</div>
<p> </p>
</div>
</div>
<p> </p>
<?php if ($_POST['frmSubmit']) { ?>
<div class="info" id="one">
<table width="59%" border="1" bordercolor="#DEDEDE" class="tabb">
<tr>
<td width="72%"><p class="rec">Total Records:</p> </td>
<td width="28%"><p class="rec"><?php echo count($strDatas)-1; ?></p></td>
</tr>
<tr>
<td><p class="rec">Inserted Records:</p></td>
<td><p class="rec"><?php echo $strInsertRecords; ?></p></td>
</tr>
<tr>
<td><p class="rec">Duplicate Records:</p></td>
<td><p class="rec"><?php echo $strDuplicationRecords; ?></p></td>
</tr>
</table>
</div>
<div class="dup">
<div class="duplicate">
<div class="hea">
<p class="rec">Duplicate Records</p>
</div>
<p style="height: 10px;"></p>
<div style="padding-left: 10px;"><?php echo $strDup. "<br>"; ?></div>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</form>
</body>
</html>
Now i want to export it from the database. Please help me.
you can download adminer.php from this "http://www.adminer.org/" and that will do that job for you. It has all the option to download database in different formats like XML, CSV and text.
I have been developing a custom wordpress theme from scratch and have run into a small problem with my comments.php file.
https://gist.github.com/phillipdews/dcebfec2016a93bd0169
I think the problem stems from line 44 of that file as when I try and leave a comment on my blog post whether logged in or not the comment processes by going to:
www.mydomain.com/postlink/wp-comments-post.php
When naturally it needs to go to:
www.mydomain.com/wp-comments-post.php
UPDATE
This is what i have decided to do! I started again from scratch and have coded out my comments.php file like this:
<div id="comments">
<?php if ( post_password_required() ) : ?>
<p>This post is password protected. Enter the password to view and comments</p>
</div>
<?php
return;
endif;
?>
<?php if ( have_comments() ) : ?>
<ol>
<?php wp_list_comments ( array( 'callback' => 'BRUM_Theme_comment') ); ?>
</ol>
<?php
elseif ( ! comments_open() && ! is_page() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p>Comments are closed</p>
<?php endif; ?>
<?php comment_form(); ?>
</div>
I then added this snippet of code to my functions.php file! This has so far made my comments appear and people are also able to leave comments on my blog post! but as yet the 'Reply to' button is not rendering.
<?php
function BRUM_Theme_comment( $comment, $args, $depth ){
$GLOBALS['comment'] = $comment;
?>
<?php if ( $comment->comment_approved == '1'): ?>
<li>
<article id="comment-<?php comment_ID() ?>">
<?php echo get_avatar( $comment ); ?>
<h4>
<?php comment_author_link() ?>
</h4>
<time><a href="#comment-<?php comment_ID() ?>" pubdate><?php comment_date() ?> at <?php comment_time() ?></a></time>
<?php comment_text() ?>
</article>
<?php endif;
}
That's it so far! once I got the Reply button working I will ammend the code!
Try this:
<div id="respond">
<?php
if (!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME']))
die ('Please do not load this page directly. Thanks!');
if ( post_password_required() ) { ?>
This post is password protected. Enter the password to view comments.
<?php
return;
}
?>
<?php if ( have_comments() ) : ?>
<h2 id="comments"><?php comments_number('No comments', 'One comment', '% Comments' );?></h2>
<div class="navigation">
<div class="next-posts"><?php previous_comments_link() ?></div>
<div class="prev-posts"><?php next_comments_link() ?></div>
</div>
<ol class="commentlist">
<?php wp_list_comments(); ?>
</ol>
<div class="navigation">
<div class="next-posts"><?php previous_comments_link() ?></div>
<div class="prev-posts"><?php next_comments_link() ?></div>
</div>
<?php else : // this is displayed if there are no comments so far ?>
<?php if ( comments_open() ) : ?>
<!-- If comments are open, but there are no comments. -->
<?php else : // comments are closed ?>
<p>Comments are closed.</p>
<?php endif; ?>
<?php endif; ?>
<?php if ( comments_open() ) : ?>
<h2><?php comment_form_title( 'Leave an reply', 'Leave a reply in %s' ); ?></h2>
<div class="cancel-comment-reply">
<?php cancel_comment_reply_link(); ?>
</div>
<?php if ( get_option('comment_registration') && !is_user_logged_in() ) : ?>
<p>You must be logged in to post a comment.</p>
<?php else : ?>
<br class="c" />
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
<?php if ( is_user_logged_in() ) : ?>
<p>Logged as <?php echo $user_identity; ?>. Log out »</p>
<?php else : ?>
<div>
<input type="text" value="Name" onblur="if (this.value == '') {this.value = 'Name';}" onfocus="if (this.value == 'Name') {this.value = '';}" name="author" id="author" size="22" tabindex="1" <?php if ($req) echo "aria-required='true'"; ?> />
</div>
<div>
<input type="text" value="Email" onblur="if (this.value == '') {this.value = 'Email';}" onfocus="if (this.value == 'Email') {this.value = '';}" name="email" id="email" size="22" tabindex="2" <?php if ($req) echo "aria-required='true'"; ?> />
</div>
<div>
<input type="text" value="Website" onblur="if (this.value == '') {this.value = 'Website';}" onfocus="if (this.value == 'Website') {this.value = '';}" name="url" id="url" size="22" tabindex="3" />
</div>
<?php endif; ?>
<br />
<div>
<textarea name="comment" id="comment" cols="58" rows="10" tabindex="4"></textarea>
</div>
<br class="c" />
<div>
<input name="submit" type="submit" id="submit" tabindex="5" value="Send" />
<?php comment_id_fields(); ?>
</div>
<?php do_action('comment_form', $post->ID); ?>
</form>
<?php endif; // If registration required and not logged in ?>
</div>
<?php endif; ?>
This may solve your issue in any Wordpress version since 3.1.
Do not forget to put this code in your template folder (comments.php)
That done the Job Lucas buddy! I had to tweak the code a little and remove the class from the OL and tweak my css as it was making the avatars 100% big and blury! So this is all I done to my css code in order to make the comments styled better:
#respond {float: left;}
#respond img {width: auto; height: auto; float: left; margin-right: 4px; border: 1px solid #aab59a; padding: 1px; border-radius: 10px;}
#respond ol li { background: #f1f1f1; margin:10px 0;padding:8px;border:2px solid #ccc;font-style:normal;list-style: none; border-radius: 10px;}
Also this is a nice feature that people can to their functions.php file as it makes the reply to link into reply to commentors name:
/*
* Change the comment reply link to use 'Reply to <Author First Name>'
*/
function add_comment_author_to_reply_link($link, $args, $comment){
$comment = get_comment( $comment );
// If no comment author is blank, use 'Anonymous'
if ( empty($comment->comment_author) ) {
if (!empty($comment->user_id)){
$user=get_userdata($comment->user_id);
$author=$user->user_login;
} else {
$author = __('Anonymous');
}
} else {
$author = $comment->comment_author;
}
// If the user provided more than a first name, use only first name
if(strpos($author, ' ')){
$author = substr($author, 0, strpos($author, ' '));
}
// Replace Reply Link with "Reply to <Author First Name>"
$reply_link_text = $args['reply_text'];
$link = str_replace($reply_link_text, 'Reply to ' . $author, $link);
return $link;
}
add_filter('comment_reply_link', 'add_comment_author_to_reply_link', 10, 3);
Hope others find it useful and thanks again it's working brilliantly!
Apparently my php email form is full of security vulnerabilities, what can I do to fix them?
And what i mean by security flaws, that is hackers/bots being able to inject additional headers(eg bcc) into my form and send spam in my name
Any suggestions?
<?php
/*
* Template Name: Contact Form Page
*/
if(isset($_POST['submitted'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactName']) === '') {
$nameError = __("You forgot to enter your name.", "site5framework");
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '') {
$emailError = __("You forgot to enter your email address.", "site5framework");
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$emailError = __("You entered an invalid email address.", "site5framework");
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['comments']) === '') {
$commentError = __("You forgot to enter your comments.", "site5framework");
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$msg .= "------------User Info------------ \r\n"; //Title
$msg .= "User IP: ".$_SERVER["REMOTE_ADDR"]."\r\n"; //Sender's IP
$msg .= "Browser Info: ".$_SERVER["HTTP_USER_AGENT"]."\r\n"; //User agent
$msg .= "Referrer: ".$_SERVER["HTTP_REFERER"]; //Referrer
$emailTo = ''.of_get_option('sc_contact_email').'';
$subject = 'Contact Form Submission From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nMessage: $comments \n\n $msg";
$headers = 'From: '.$name.' <'.$email.'>' . "\r\n" . 'Reply-To: ' . $email;
if(mail($emailTo, $subject, $body, $headers)) $emailSent = true;
}
}
get_header();
?>
<div id="content" class="container clearfix">
<!-- page header -->
<div class="container clearfix ">
<?php if(of_get_option('sc_contact_map') != '') { ?>
<!-- contact map -->
<div id="contact-map">
<?php echo of_get_option('sc_contact_map') ?>
</div>
<!-- end contact map -->
<?php } else if(of_get_option('sc_showpageheader') == '1' && get_post_meta($post->ID, 'snbpd_ph_disabled', true) != 'on' ) : ?>
<?php if(get_post_meta($post->ID, 'snbpd_phitemlink', true)!= '') : ?>
<?php
$thumbId = get_image_id_by_link ( get_post_meta($post->ID, 'snbpd_phitemlink', true) );
$thumb = wp_get_attachment_image_src($thumbId, 'page-header', false);
?>
<img class="intro-img" alt=" " src="<?php echo $thumb[0] ?>" alt="<?php the_title(); ?>" />
<?php elseif (of_get_option('sc_pageheaderurl') !='' ): ?>
<?php
$thumbId = get_image_id_by_link ( of_get_option('sc_pageheaderurl') );
$thumb = wp_get_attachment_image_src($thumbId, 'page-header', false);
?>
<img class="intro-img" alt=" " src="<?php echo $thumb[0] ?>" alt="<?php the_title(); ?>" />
<?php else: ?>
<img class="intro-img" alt=" " src="<?php echo get_template_directory_uri(); ?>/library/images/inner-page-bg.jpg" />
<?php endif ?>
<?php endif ?>
</div>
<!-- content -->
<div class="container">
<h1><?php the_title(); ?> <?php if ( !get_post_meta($post->ID, 'snbpd_pagedesc', true)== '') { ?>/<?php }?> <span><?php echo get_post_meta($post->ID, 'snbpd_pagedesc', true); ?></span></h1>
<article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="page-body clearfix">
<?php the_content(); ?>
</div>
<div class="one-third">
<div class="caddress"><strong><?php _e('Address:', 'site5framework') ?></strong> <?php echo of_get_option('sc_contact_address') ?></div>
<div class="cphone"><strong><?php _e('Phone:', 'site5framework') ?></strong> <?php echo of_get_option('sc_contact_phone') ?></div>
<div class="cphone"><strong><?php _e('Fax:', 'site5framework') ?></strong> <?php echo of_get_option('sc_contact_fax') ?></div>
<div class="cemail"><strong><?php _e('E-mail:', 'site5framework') ?></strong> <?php echo of_get_option('sc_contact_email') ?></div>
</div>
<div class="two-third last">
<div id="messages">
<p class="simple-error error" <?php if($hasError != '') echo 'style="display:block;"'; ?>><?php _e('There was an error submitting the form.', 'site5framework'); ?></p>
<p class="simple-success thanks"><?php _e('<strong>Thanks!</strong> Your email was successfully sent. We should be in touch soon.', 'site5framework'); ?></p>
</div>
<form id="contactForm" method="POST">
<div class="one-third">
<label for="nameinput"><?php _e("Your name", "site5framework"); ?></label>
<input type="text" id="nameinput" name="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField"/>
<span class="error" <?php if($nameError != '') echo 'style="display:block;"'; ?>><?php _e("You forgot to enter your name.", "site5framework");?></span>
</div>
<div class="one-third last">
<label for="emailinput"><?php _e("Your email", "site5framework"); ?></label>
<input type="text" id="emailinput" name="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="requiredField email"/>
<span class="error" <?php if($emailError != '') echo 'style="display:block;"'; ?>><?php _e("You forgot to enter your email address.", "site5framework");?></span>
</div>
<div class="two-third">
<label for="nameinput"><?php _e("Area/Rep", "site5framework"); ?></label>
<select>
<option>Area 1 - Engela</option>
<option>Area 2 - Francois</option>
<option>Area 3 - Johan</option>
</select>
</div>
<div class="two-third">
<label for="Mymessage"><?php _e("Your message", "site5framework"); ?></label>
<textarea cols="20" rows="20" id="Mymessage" name="comments" class="requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<span class="error" <?php if($commentError != '') echo 'style="display:block;"'; ?>><?php _e("You forgot to enter your comments.", "site5framework");?></span>
</div>
<br class="clear" />
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit" id="submitbutton" class="button small round orange"><?php _e(' SEND MESSAGE ', 'site5framework'); ?></button>
</form>
</div>
<?php endwhile; ?>
</article>
<?php else : ?>
<article id="post-not-found">
<header>
<h1><?php _e("Not Found", "site5framework"); ?></h1>
</header>
<section class="post_content">
<p><?php _e("Sorry, but the requested resource was not found on this site.", "site5framework"); ?></p>
</section>
<footer>
</footer>
</article>
<?php endif; ?>
</div>
</div> <!-- end content -->
<?php get_footer(); ?>
use another contact template!
contact templates are a very vulnerable point in web sites, this one is really insecure (I guess / hope it's quite old).
A few points for the curious (only a first glance, there may be more issues)
the $name parameter is not escaped, malicious user can enter for example bcc addresses, which would be added to the header section, here
the regex for the $email parameter allows %, thus it is possible to enter url_encoded signs like < >
$comments is not secured, too..
Why exactly do you have the need to let users send email with aribtrary name and email address? Are you trying to be an open proxy?
P.S. Lines like this won't do what you probably intended, because they don't handle the case of no parameter or an array being passed.
trim($_POST['contactName']) === ''