Security Flaw in php form - php

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']) === ''

Related

Contact.PHP Form Internal Server error

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

reCaptcha breaks other validation?

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>

Contact form issues wordpress

I've got a problem with a contact form on my webpage.
When someone fills it in, i always got the error message that something isn't filled in right.
It seems to be the telephone number.
The link to the webpage is http://www.tiggelovend-kok.nl/index.php/contact/
<?php
/*
Template Name: Contact
*/
?>
<?php get_header(); ?>
<div class="wider_blog">
<div class="_blog">
<div class="topbar"><div class="row">
<?php
echo beopen_main_title();
if (beopen_get_option('show_breadcrumbs') == '2') {
echo beopen_breadcrumb();
}
?>
</div></div>
<?php
if (beopen_get_option('show_map') != 1) {
?>
<div id="map_canvas_shadow"></div>
<div id="map_canvas"></div>
<?php
}
?>
<div class="row">
<!-- Row for main content area -->
<div id="content" class="eight columns rightfade" role="main">
<div class="post-box">
<article class="contact">
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php if (beopen_get_option('show_contact_form') == 2) { ?>
<?php echo beopen_get_option('contact_form_text'); ?>
<form class="beopen-contact-form" action="<?php echo get_permalink(); ?>" method="post">
<?php
require_once(THEME_LIBRARY . '/recaptchalib.php');
$error_contact_name = '';
$error_contact_email = '';
$error_contact_phone = '';
$error_contact_company = '';
$error_contact_message = '';
$contact_name = '';
$contact_email = '';
$contact_company = '';
$contact_phone = '';
$contact_message = '';
$publickey = beopen_get_option('recaptcha_public_key');
$privatekey = beopen_get_option('recaptcha_private_key');
if (isset($_POST['beopen_form'])) {
foreach ($_POST as $key => $val) {
$GLOBALS[$key] = wp_filter_kses($val);
}
$send = 0;
if (beopen_get_option('show_recaptcha') == 2) {
$recaptcha_challenge_field = '';
if (isset($_POST["recaptcha_challenge_field"])) {
$recaptcha_challenge_field = $_POST["recaptcha_challenge_field"];
}
$recaptcha_response_field = '';
if (isset($_POST["recaptcha_response_field"])) {
$recaptcha_response_field = $_POST["recaptcha_response_field"];
}
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $recaptcha_challenge_field, $recaptcha_response_field);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
echo '<div class="alert-box alert">';
echo (__("The reCAPTCHA wasn't entered correctly. Go back and try it again.", 'beopen') .
"(" . __('reCAPTCHA said:', 'beopen') . " " . $resp->error . ")");
echo '</div>';
} else {
// Your code here to handle a successful verification
$send = 1;
}
} else {
$send = 1;
}
if (!(isset($_POST['contact_name']) && ($_POST['contact_name']) != '')) {
$error_contact_name = 'error';
$send = 2;
}
if (!(isset($_POST['contact_message']) && ($_POST['contact_message']) != '')) {
$error_contact_message = 'error';
$send = 2;
}
if ($send == 2) {
echo '<div class="alert-box alert">';
_e('U bent een veld vergeten in te vullen!', 'beopen');
echo '</div>';
} else
if ($send == 1) {
$mail_content = __('Name:', 'beopen') . PHP_EOL . $_POST['contact_name'] . PHP_EOL . PHP_EOL .
__('E-mail:', 'beopen') . PHP_EOL . $_POST['contact_email'] . PHP_EOL . PHP_EOL .
__('Company:', 'beopen') . PHP_EOL . $_POST['contact_company'] . PHP_EOL . PHP_EOL .
__('Phone:', 'beopen') . PHP_EOL . $_POST['contact_phone'] . PHP_EOL . PHP_EOL .
__('Message:', 'beopen') . PHP_EOL . $_POST['contact_message'] . PHP_EOL;
if ($_POST['contact_email'] == '') {
$mail_headers = 'From: ' . beopen_get_option('contact_email_from') . PHP_EOL .
'Reply-To: ' . beopen_get_option('contact_email_from');
} else {
$mail_headers = 'From: ' . $_POST['contact_email'] . PHP_EOL .
'Reply-To: ' . $_POST['contact_email'];
}
if (mail(beopen_get_option('contact_email_to'), beopen_get_option('contact_email_subject'), $mail_content, $mail_headers)) {
echo '<div class="alert-box success">';
_e('Bericht verzonden!', 'beopen');
echo '</div>';
} else {
echo '<div class="alert-box alert">';
_e('Voer de juiste gegevens in!', 'beopen');
echo '</div>';
}
}
}
?>
<div class="row">
<div class="six columns">
<div class="beopen-wrap author-icon <?php echo $error_contact_name; ?>">
<input type="text" name="contact_name" value="<?php echo $contact_name; ?>" placeholder="<?php _e('Uw naam', 'beopen'); ?>" />
</div>
</div>
<div class="six columns">
<div class="beopen-wrap email-icon <?php echo $error_contact_email; ?>">
<input type="text" name="contact_email" value="<?php echo $contact_email; ?>" placeholder="<?php _e('Uw e-mail', 'beopen'); ?>" />
</div>
</div>
</div>
<div class="row">
<div class="six columns">
<div class="beopen-wrap company-icon <?php echo $error_contact_company; ?>">
<input type="text" name="contact_company" value="<?php echo $contact_company; ?>" placeholder="<?php _e('Uw organisatie', 'beopen'); ?>" />
</div>
</div>
<div class="six columns">
<div class="beopen-wrap phone-icon <?php echo $error_contact_phone; ?>">
<input type="text" name="contact_phone" value="<?php echo $contact_phone; ?>" placeholder="<?php _e('Uw telefoonnummer', 'beopen'); ?>" />
</div>
</div>
</div>
<textarea name="contact_message" placeholder="<?php _e('Voer hier uw bericht in', 'beopen'); ?>" <?php if ($error_contact_message) { echo 'class="' . $error_contact_message . '"'; } ?>><?php echo $contact_message; ?></textarea>
<div id="recaptcha_div"></div>
<input type="hidden" name="beopen_form" value="1" />
<button class="button send-message" type="submit"><span class="send-message"></span><?php _e('Verzenden', 'beopen'); ?></button>
</form>
<?php } ?>
</article>
</div>
</div><!-- End Content row -->
<div class="four columns">
<div class="contact-sidebar">
<?php echo wpautop(beopen_get_option('map_address')); ?>
</div>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>

PHP form redirect to thanks page

I have a custom WP theme that I'm trying to redirect to a thanks page after the form has been verified. I know there are a ton of other questions very similar, but I've tried the "headers" trick and all of the other suggestions, but my page just keeps going back to the contact.php page. Hovering over the submit button (before clicking it) shows mypageURL.com/contact, instead of mypageURL.com/thanks. Here is my code.
<?php
//Verify the email address
function isemail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
}
//set variables
$error_name = false;
$error_email = false;
$error_message = false;
//Get form values
if (isset($_POST['contact-submit'])) {
$contact_name = '';
$contact_email = '';
$contact_subject = '';
$contact_message = '';
$contact_reciever = '';
if (trim($_POST['contact_name']) === '') {
$error_name = true;
} else {
$contact_name = trim($_POST['contact_name']);
}
if (trim($_POST['contact_email']) === '' || !isemail(trim($_POST['contact_email']))) {
$error_email = true;
} else {
$contact_email = trim($_POST['contact_email']);
}
$subject = trim($_POST['contact_subject']);
if (trim($_POST['contact_message']) === '') {
$error_message = true;
} else {
$contact_message = stripslashes(trim($_POST['contact_message']));
}
//Check for errors
if (!$error_name && !$error_email && !$error_message) {
//Get reciever email
if( get_theme_mod( 'custom_contact_form_mail' ) != '') $get_contact_reciever = get_theme_mod( 'custom_contact_form_mail' ) ;
$contact_reciever = $get_contact_reciever;
$the_subject = 'New message: ' . $contact_subject;
$the_message = 'Message from: ' . $contact_name . PHP_EOL . 'Email: ' . $contact_email . PHP_EOL . PHP_EOL . $contact_message . PHP_EOL ;
$the_headers = "Form " . $contact_email . PHP_EOL . 'Reply-To: ' . $contact_email . PHP_EOL . 'MIME-Version: 1.0' . PHP_EOL . 'Content-type: text/plain; charset=utf-8' . PHP_EOL . 'Content-Transfer-Encoding: quoted-printable' . PHP_EOL;
if (mail($contact_reciever, $the_subject, $the_message, $the_headers)) {
$contact_form_sent = true;
} else {
$contact_form_sent_error = true;
}
} else {
$contact_form_not_filled = true;
}
}
?>
<?php get_header(); ?>
<section id="content">
<?php if (have_posts()) : while(have_posts()) : the_post(); ?>
<div class="white-section contact">
<div class="container">
<div class="row">
<div class="span12">
<?php if (current_user_can('edit_post', $post->ID))
edit_post_link( $link = __('You are logged in as an Administrator. Click this text to edit this page. This text will not show up if you are not logged in as Admin.', 'cht'), $before = '<i class="icon-edit"></i> ', $after = '' );
?>
<div class="row">
<div class="span6">
<?php the_content(); ?>
<h4><?php _e('Contact info', 'cht') ?></h4>
<ul>
<?php if( get_theme_mod( 'custom_contact_info_name' ) != '') { ?>
<li><i class="icon-briefcase"></i> <?php print get_theme_mod( 'custom_contact_info_name' ) ?></li>
<?php } else { ?>
<li><i class="icon-briefcase"></i> Cloud Hoster Ltd.</li>
<?php } ?>
<?php if( get_theme_mod( 'custom_contact_info_address' ) != '') { ?>
<li><i class="icon-map-marker"></i> <?php print get_theme_mod( 'custom_contact_info_address' ) ?></li>
<?php } else { ?>
<li><i class="icon-map-marker"></i> 01234 Main Street, New York 45678</li>
<?php } ?>
<?php if( get_theme_mod( 'custom_contact_info_phone' ) != '') { ?>
<li><i class="icon-phone"></i> <?php print get_theme_mod( 'custom_contact_info_phone' ) ?></li>
<?php } else { ?>
<li><i class="icon-phone"></i> Phone: 555-555-5555 Fax: 444-444-4444</li>
<?php } ?>
<?php if( get_theme_mod( 'custom_contact_info_mail' ) != '') { ?>
<li><i class="icon-envelope-alt"></i> Email: <?php print get_theme_mod( 'custom_contact_info_mail' ) ?></li>
<?php } else { ?>
<li><i class="icon-envelope-alt"></i> Email: info#domain.com</li>
<?php } ?>
</ul>
</div><!-- span6 end -->
<div class="span6">
<div id="map"></div>
<script>
jQuery(document).ready(function(){
var map;
map = new GMaps({
div: '#map',
<?php if( get_theme_mod( 'custom_google_map_lat' ) != '') { ?>
lat: <?php print get_theme_mod( 'custom_google_map_lat' ) ?>,
<?php } else { ?>
lat: 40.714353,
<?php } ?>
<?php if( get_theme_mod( 'custom_google_map_lng' ) != '') { ?>
lng: <?php print get_theme_mod( 'custom_google_map_lng' ) ?>,
<?php } else { ?>
lng: -74.005973,
<?php } ?>
zoom: 15,
zoomControl: true,
zoomControlOpt: {
style : 'SMALL',
position: 'TOP_LEFT'
},
streetViewControl: false,
});
map.addMarker({
<?php if( get_theme_mod( 'custom_google_map_lat' ) != '') { ?>
lat: <?php print get_theme_mod( 'custom_google_map_lat' ) ?>,
<?php } else { ?>
lat: 40.714353,
<?php } ?>
<?php if( get_theme_mod( 'custom_google_map_lng' ) != '') { ?>
lng: <?php print get_theme_mod( 'custom_google_map_lng' ) ?>,
<?php } else { ?>
lng: -74.005973,
<?php } ?>
});
});
</script>
</div><!-- span6 end -->
</div><!-- row end -->
<div class="row">
<div class="span12">
<form action="<?php the_permalink(); ?>" method='post' name='contactform' id='contactform'>
<p><?php _e('Your name:', 'cht') ?></p>
<input type="text" class="input-box" name="contact_name" value="<?php if (isset($_POST['contact_name'])) echo $_POST['contact_name']; ?>" placeholder="<?php _e('Please enter your name.', 'cht') ?>">
<p><?php _e('Email address:', 'cht') ?></p>
<input type="text" class="input-box" name="contact_email" value="<?php if (isset($_POST['contact_email'])) echo $_POST['contact_email']; ?>" placeholder="<?php _e('Please enter your email address.', 'cht') ?>">
<p><?php _e('What kind of problems are you having?', 'cht') ?></p>
<input type="text" class="input-box" name="contact_subject" value="<?php if (isset($_POST['contact_subject'])) echo $_POST['contact_subject']; ?>" placeholder="<?php _e('Purpose of this message.', 'cht') ?>">
<p class="right-message-box"><?php _e('How Can We Help You?', 'cht') ?></p>
<textarea class="input-box right-message-box message-box" name="contact_message" value="<?php if (isset($_POST['contact_message'])) echo stripslashes($_POST['contact_message']); ?>" placeholder="<?php _e('Your message.', 'cht') ?>"></textarea>
<button type='submit' class='submit-contact-form' name='submit' id="submit">Send your message</button>
<input type="hidden" name="contact-submit" id="contact-submit" value="true">
</form>
</div><!-- span12 end -->
</div><!-- row end -->
<?php if (isset($contact_form_sent) && $contact_form_sent == true) : ?>
<div class="alert alert-success"><p><strong><?php _e('Success! ', 'cht') ?> </strong><?php _e('Your message has been sent.', 'cht') ?></p></div>
<?php elseif (isset($contact_form_sent_error) && $contact_form_sent_error == true) : ?>
<div class="alert alert-error"><p><strong><?php _e('Error! ', 'cht') ?> </strong><?php _e('Something went wrong. Please try again.', 'cht') ?></p></div>
<?php elseif (isset($contact_form_not_filled) && $contact_form_not_filled == true) : ?>
<div class="alert alert-error"><p><strong><?php _e('Error! ', 'cht') ?> </strong><?php _e('Fill out the form correctly and try again.', 'cht') ?></p></div>
<?php endif; ?>
</div><!-- span12 end -->
</div><!-- row end -->
</div><!-- conteiner end -->
</div><!-- white-section end -->
<?php endwhile; endif; ?>
</section><!-- content end -->
<?php get_footer(); ?>
It's not really a trick, its how you can do exactly what you want done.
if (mail($contact_reciever, $the_subject, $the_message, $the_headers)) {
$contact_form_sent = true;
header("Location: " . get_permalink($THANKYOU_PAGE_ID));
}
Does it throw off any errors when you try using header? If so you might have to create a hook and verify the form earlier in the page load.
I'm assuming your comment means "Yes it is throwing off errors, how do I hook my form earlier so that it doesn't do that?". Well my good friend follow me..
add_action( 'send_headers', 'form_verify' );
function form_verify() {
// add form code here with header code
}

Saving Info on web form error on submit

I have a php script that I am working on and have yet to be able to get the form to save the info and repopulate on a validation error. I've tried several how to's on various websites but perhaps I am missing something as they mostly have a lot of other PHP lines in them but the how to pages don't give specifics on the lines of code that are necessary to save data and repopulate. Below is the code and if anyone has any ideas or could point me to some place that works well I would greatly appreciate it, I've hit a wall thus far. Thanks in advance!!
<?php
/*
Template Name: Post Submit Form
*/
?>
<?php if ( $user_ID > 0) { ?>
<?php if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['title'])) {
$title = $_POST['title'];
} else {
$error .= "Please add a title<br />";
}
if (!empty($_POST['description'])) {
$description = $_POST['description'];
} else {
$error .= "Please add a description<br />";
}
if (!empty($_POST['post_tags'])) {
$post_tags = $_POST['post_tags'];
} else {
$error .= "Please add some keywords<br />";
}
if (!empty($_POST['externalurl'])) {
$externalurl = $_POST['externalurl'];
} else {
$error .= "Please add a URL to post<br />";
}
// IMAGE VALIDATION - CHECK IF THERE IS AN IMAGE AND THAT ITS THE RIGHT FILE TYPE AND RIGHT SIZE
if ($_FILES) {
foreach ($_FILES as $file => $array) {
//Check if the $_FILES is set and if the size is > 0 (if =0 it's empty)
if(isset($_FILES[$file]) && ($_FILES[$file]['size'] > 0)) {
$tmpName = $_FILES[$file]['tmp_name'];
list($width, $height, $type, $attr) = getimagesize($tmpName);
if($width<=899 || $height<=299)
{
$error .= "Image is to small. Minimum 900 pixels wide.<br />";
unlink($_FILES[$file]['tmp_name']);
}
// Get the type of the uploaded file. This is returned as "type/extension"
$arr_file_type = wp_check_filetype(basename($_FILES[$file]['name']));
$uploaded_file_type = $arr_file_type['type'];
// Set an array containing a list of acceptable formats
$allowed_file_types = array('image/jpg','image/jpeg');
// If the uploaded file is the right format
if(in_array($uploaded_file_type, $allowed_file_types)) {
} else { // wrong file type
$error .= "Please upload a .jpg type image<br />";
}
} else {
$error .= "Please add an image<br />";
}
} // end for each
} // end if
$tags = $_POST['post_tags'];
$externalurl = $_POST['externalurl'];
// ADD THE FORM INPUT TO $new_post ARRAY
if (empty($error)) {
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'preview', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post', //'post',page' or use a custom post type if you want to
'externalurl' => $externalurl
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
//KEEPS OUR COMMA SEPARATED TAGS AS INDIVIDUAL
wp_set_post_tags($pid, $_POST['post_tags']);
//REDIRECT TO THE NEW POST ON SAVE
$link = get_permalink( $pid );
wp_redirect( $link );
//ADD OUR CUSTOM FIELDS
add_post_meta($pid, 'externalurl', $externalurl, true);
//INSERT OUR MEDIA ATTACHMENTS
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, $pid );
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($pid,'_thumbnail_id',$attach_id);
}
} // END SAVING POST
} // END VALIDATION
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM
//POST THE POST YO
do_action('wp_insert_post', 'wp_insert_post');
?>
<?php get_header(); ?>
<?php get_template_part('wrapper', 'start'); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('box mb20'); ?>>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( is_front_page() ) { ?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php } else { ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php } ?>
<div class="form-content">
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo '<p class="success">' . $success . '</p>';
}
?>
<div class="entry-content clearfix mt20">
<?php the_content(); ?>
</div>
<div class="dashedline"></div>
<!-- Start FORM -->
<div class="submitpost-form">
<form id="new_post" name="new_post" method="post" action="" class="submitpost-form" enctype="multipart/form-data">
<!-- post name -->
<fieldset name="name">
<label for="title">Post Title:</label>
<input type="text" id="submitpost-entry" value="<?php echo $_SERVER['title']; ?>" tabindex="5" name="title" />
<p class="submitpost-entry-infotext">Choose a descriptive title that highlights the most important thing about your project. This will also be part of the URL. Do not use your name or genre in it.</p>
</fieldset>
<!-- External URL -->
<fieldset class="externalurl">
<label for="externalurl">Direct link (URL) to post page: (must include http://)</label>
<input type="text" value="<?php echo $_SERVER['externalurl']; ?>" id="submitpost-entry" tabindex="10" name="externalurl" onFocus="this.value=''"/>
<p class="submitpost-entry-infotext">This will be the URL linked to by the post. This should be a direct url to the webpage / article about the project. Do not link to your homepage or main portfolio page. The image submited below must appear on this page.</p>
</fieldset>
<!-- post tags -->
<fieldset class="tagsentry">
<label for="post_tags">Tags (comma separated):</label>
<input type="text" value="" tabindex="15" name="post_tags" id="submitpost-entry" />
<p class="submitpost-entry-infotext">Use a few descriptive words (all lowercase) to allow users to discover your work via exploring tags. Avoid using genre terms. Example: environmental, b&w, lifestyle. Keep below about ten.</p>
</fieldset>
<!-- post Category -->
<fieldset class="category">
<label for="cat">Genre:</label>
<?php wp_dropdown_categories( 'tab_index=20&taxonomy=category&hide_empty=0&exclude=1' ); ?>
<p class="submitpost-entry-infotext" style="position:relative; top:-14px;">Select the most suitable genre for your work. If you have a genre suggestion please let us know via the contact page.</p>
</fieldset>
<!-- authors -->
<fieldset class="images">
<label for="bottle_front">Image</label>
<input type="file" name="Image" id="image" tabindex="25" />
<p class="submitpost-entry-infotext">Images must be .jpg format with a minimum of 900 pixels wide and be less than 600kb in size.</p>
</fieldset>
<!-- post Content -->
<fieldset class="submitpostcontent">
<label for="description">Description:</label>
<textarea id="submitpost-message" tabindex="30" name="description" rows="10"></textarea>
<p class="submitpost-entry-infotext" >Enter more detail about the project or piece, the first 40 words will be displayed on the grid page. Any extra text will show on the post page. Do not compose in this field to avoid loosing text. Spell check before submiting! Profanity or offensive text will not be published. </p>
</fieldset>
<fieldset class="submit">
<input type="submit" value="Post Review" tabindex="40" id="submit" name="submit" />
</fieldset>
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
</div> <!-- END WPCF7 -->
<!-- END OF FORM -->
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
<?php edit_post_link( __( 'Edit', 'twentyten' ), '<span class="edit-link">', '</span>' ); ?>
</div><!-- .entry-content -->
</div><!-- #post-## -->
<?php comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
</article>
<?php get_template_part('wrapper', 'end'); ?>
<?php get_footer(); ?>
<?php } else { ?>
<?php get_header(); ?>
<?php get_template_part('wrapper', 'start'); ?>
<?php while (have_posts()) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('box mb20'); ?>>
<header class="entry-header">
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<div class="entry-content clearfix mt20">
Message for non logged in users.
</div>
</article>
<?php comments_template(); ?>
<?php endwhile; ?>
<?php get_template_part('wrapper', 'end'); ?>
<?php get_footer(); ?>
<?php }; ?>
To avoid undefined index errors, you should use something along these lines:
<form>
<input type="text" id="someField" name="title" value="<?php echo !empty( $_POST['title'] ) ? $_POST['title'] : ''?>" />
</form>
Cheers
This is how it should work:
<form id="new_post" name="new_post" method="post" action="this_form.php" class="submitpost-form" enctype="multipart/form-data">
<input type="text" id="submitpost-entry" value="<?php echo $_POST['title']; ?>" tabindex="5" name="title" />
...and so on populating input field value with post data.

Categories