WP Comments Not Posting Correctly - php

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!

Related

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>

PHP Code will not validate

I am trying to edit a PHP IF statement however, there is a syntax issue according to this online validator:
http://www.piliapp.com/php-syntax-check/
Here is the code:
<?php
if (strpos($row['caption'],'DIGITAL') !== false)
{?><input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart"/>
<?php } ?>
<?php
elseif (strpos($row['price'] != NULL && strpos($row['price']) != '0' && strpos($row['caption'],'DIGITAL') !== true)
{?><input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart"/>
<?php } ?>
This is what I a trying to achieve:
If the "Caption" begins with the text "DIGITAL" then the add to cart button should be active.
If the "Caption does not begin with the text "DIGITAL" AND the "Price" is not NULL or 0 then the shopping cart button should be active. In all other instances, it should be INACTIVE.
Here is the full source code:
<?php include_once('admin/config/config.php'); ?>
<?php include_once('admin/libs/functions.php'); ?>
<?php $obj = new Functions(); ?>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
<link rel="stylesheet" type="text/css" href="reset.css">
<link rel="stylesheet" type="text/css" href="text.css">
<link rel="stylesheet" type="text/css" href="960.css">
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<link rel="stylesheet" type="text/css" href="assets/css/nivo-lightbox.css">
<link rel="stylesheet" type="text/css" href="assets/css/default.css">
<script type="text/javascript" src="assets/js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="assets/js/nivo-lightbox.js"></script>
<script type="text/javascript">
$(function(){
$(".view-img").nivoLightbox();
});
</script>
<script type="text/javascript" src="assets/js/shoppingcart.js"></script>
<script type="text/javascript" src="assets/js/general.js"></script>
<meta charset="utf-8">
<meta name="description" content="CENSORED Photography provides the best quality photography in the SENSORED Region. Whether you are looking for a photographer for a wedding, portrait, event or literally anything else, Let your story begin with SENSORED Photography. ">
<meta name="keywords" content="Photography, , Videography, , Photo, Portrait, Best">
<title>SENSORED Photography</title>
<script type="text/javascript">
$(function(){
$(".item_size").change(function(){
item_val = $(this).val();
n = $(this).attr("custval");
if(item_val != "" && item_val != null) {
$("#s"+n).removeAttr("disabled");
}
else {
$("#s"+n).attr("disabled","disabled");
}
});
});
</script>
</head>
<!-- oncontextmenu="return false;"-->
<body>
<div id="wrapper" class="container_12">
<div id="sidebar" class="grid_3">
<img src="images/sidebar_02.png" alt="sidebar"/>
<ul>
<li class="home">HOME</li>
<li class="about">ABOUT</li>
<li class="contact">CONTACT</li>
<li class="gallery" style="color:#AD6FC4;">GALLERY</li>
</ul>
<p>© Copyright SENSORED 2013</p>
</div><!--end sidebar-->
<div id="content" class="grid_9">
<div id="contact" class="grid_3 alpha push_6">
</div><!--end contact-->
<div id="shop_cart">
<span class="shop_cart_quantity"></span> items
<span class="totalfront"></span><span class="shop_cart_total"></span>
View Details
Checkout
Empty Cart
</div>
<div id="cart_overview" style="background: #ffffff; position: absolute; top: 10px; left: 10px; display: none">
<div id="cart_overviewitems" class="shop_cart_items"></div>
<div style="clear:left"></div>
</div>
<div id="action_overview" style="position: absolute; top: 10px; left: 10px; display: none">
<!-- Product Added -->
<div style="clear:left"></div>
</div>
<div id="content2" class="omega grid_9 content2 newpages">
<?php if(isset($_GET['cat']) && $_GET['cat']!= NULL): ?>
<?php
$query = "SELECT * FROM categories WHERE id={$_GET['cat']}";
$data = $obj->select($query);
?>
<h1 class="normalh1 newpagesnew"><?php echo strtoupper($data['name']); ?></h1>
<?php
if($data['protected'] == '1'):
?>
<?php
$cid = $_GET['cat'];
$cookName = "cat".$cid;
if(!isset($_COOKIE[$cookName]) || $_COOKIE[$cookName] != "checked"):
?>
<div id="formWrap">
<form action="category-login.php" method="post" id="category_login">
<?php if(isset($_GET['mess']) && $_GET['mess'] == "err"): ?>
<p>Incorrect Password. Please try again.</p>
<?php else: ?>
<p>This gallery is protected. Please enter the password.</p>
<?php endif; ?>
<input type="hidden" name="cid" value="<?echo $cid; ?>" />
<div class="row">
<div class="input">
<input type="password" id="password" class="detail" name="password" placeholder="Password" required />
</div><!-- end .input -->
</div><!-- end .row -->
<div class="submit">
<input type="submit" id="submit" name="submit" value="login"/>
</div><!-- end .submit -->
</form>
</div>
<?php else: ?>
<?php
$sql = "SELECT * FROM categories WHERE parent_id = {$_GET['cat']} ORDER BY id DESC";
$res = $obj->selectAll($sql);
if($res):
?>
<?php $flag = 1; ?>
<?php foreach($res as $dat): ?>
<div class="grid_2 gal product">
<a href="viewgallery.php?cat=<?php echo $dat['id']; ?>">
<?php
$sql1 = "SELECT * FROM images WHERE category_id={$dat['id']} AND cover=1";
$dat1 = $obj->select($sql1);
if($dat1):
?>
<img src="gal/thumbs/<?php echo $dat1['filename']; ?>" />
<?php else:?>
<img src="images/nopic.png" />
<?php endif; ?>
</a>
<span>
<a href="viewgallery.php?cat=<?php echo $dat['id']; ?>"><?php echo $dat['name']; ?>
</a>
</span>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php if($flag == 1): ?>
<hr />
<?php endif; ?>
<?php
$n=1;
$query1 = "SELECT * FROM images WHERE category_id={$data['id']} ORDER BY id DESC";
$result = $obj->selectAll($query1);
if($result):
?>
<?php foreach($result as $row): ?>
<div class="grid_2 gal product">
<div class="product_item">
<a class="view-img" href="gal/<?php echo $row['filename']; ?>" data-lightbox-gallery="gallery1" <?php echo $row['caption'] != NULL ? 'title="'.$row['caption'].'"' : ''; ?>>
<img src="gal/thumbs/<?php echo $row['filename']; ?>">
</a>
<span class="item_name" style="display:none">Photo <?php echo $data['id']."-".$row['id']; ?></span>
<?php if($row['price'] != NULL && $row['price'] != '0'): ?><span style="margin-bottom: 0">Price: <i class="item_price"><?php echo $row['priceunit'].$row['price']; ?></i></span> <?php endif; ?>
<input type="hidden" class="item_quantity" value="1" style="width:20px;">
<?php if($row['price'] != NULL && $row['price'] != '0'): ?>
<?php
$sql = "SELECT * FROM sizes";
$res = $obj->selectAll($sql);
?>
<select name="item_size" class="item_size" custval="<?php echo $n; ?>" required>
<option value="">Select Size</option>
<?php foreach($res as $line): ?>
<option value="<?php echo $line['width'].' x '.$line['height']; ?>"><?php echo $line['width'].' x '.$line['height']; ?></option>
<?php endforeach; ?>
</select>
<input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart" disabled />
<?php else: ?>
<div style="height:100px; float: left; clear:both"></div>
<?php endif; ?>
</div>
</div>
<?php $n++; ?>
<?php endforeach; ?>
<?php else: ?>
<?php if($flag != 1): ?>
No Image avilable.
<?php endif; ?>
<?php endif; ?>
<?php endif; ?>
<?php else: ?>
<?php
$sql = "SELECT * FROM categories WHERE parent_id = {$_GET['cat']} ORDER BY id DESC";
$res = $obj->selectAll($sql);
if($res):
?>
<?php $flag = 1; ?>
<?php foreach($res as $dat): ?>
<div class="grid_2 gal product">
<a href="viewgallery.php?cat=<?php echo $dat['id']; ?>">
<?php
$sql1 = "SELECT * FROM images WHERE category_id={$dat['id']} AND cover=1";
$dat1 = $obj->select($sql1);
if($dat1):
?>
<img src="gal/thumbs/<?php echo $dat1['filename']; ?>" />
<?php else:?>
<img src="images/nopic.png" />
<?php endif; ?>
</a>
<span>
<a href="viewgallery.php?cat=<?php echo $dat['id']; ?>"><?php echo $dat['name']; ?>
</a>
</span>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php if($flag == 1): ?>
<hr />
<?php endif; ?>
<?php
$n=1;
$query1 = "SELECT * FROM images WHERE category_id={$data['id']} ORDER BY id DESC";
$result = $obj->selectAll($query1);
if($result):
?>
<?php foreach($result as $row): ?>
<div class="grid_2 gal product">
<div class="product_item">
<a class="view-img" href="gal/<?php echo $row['filename']; ?>" data-lightbox-gallery="gallery1" <?php echo $row['caption'] != NULL ? 'title="'.$row['caption'].'"' : ''; ?>>
<img src="gal/thumbs/<?php echo $row['filename']; ?>">
</a>
<span class="item_name" style="display:none">Photo <?php echo $data['id']."-".$row['id']; ?></span>
<?php if($row['price'] != NULL && $row['price'] != '0'): ?><span style="margin-bottom: 0">Price: <i class="item_price"><?php echo $row['priceunit'].$row['price']; ?></i></span> <?php endif; ?>
<input type="hidden" class="item_quantity" value="1" style="width:20px;">
<?php if($row['price'] != NULL && $row['price'] != '0'): ?>
<?php
$sql = "SELECT * FROM sizes";
$res = $obj->selectAll($sql);
?>
<select name="item_size" class="item_size" custval="<?php echo $n; ?>" required <?php if (strpos($row['caption'],'DIGITAL') !== false) {?>disabled="disabled"<?php }?>>
<option value="">Select Size</option>
<?php foreach($res as $line): ?>
<option value="<?php echo $line['width'].' x '.$line['height']; ?>"><?php echo $line['width'].' x '.$line['height']; ?></option>
<?php endforeach; ?>
</select>
<?php
if (strpos($row['caption'],'DIGITAL') !== false)
{?><input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart"/>
<?php } ?>
<?php
elseif (strpos($row['price'] != NULL && strpos($row['price']) != '0' && strpos($row['caption'],'DIGITAL') !== true)
{?><input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart"/>
<?php } ?>
<?php else: ?>
<div style="height:100px; float: left; clear:both"></div>
<?php endif; ?>
</div>
</div>
<?php $n++; ?>
<?php endforeach; ?>
<?php else: ?>
<?php if($flag != 1): ?>
No Image avilable.
<?php endif; ?>
<?php endif; ?>
<?php endif;?>
<?php else: ?><!-- post -->
<h1 class="normalh1">Invalid action.</h1>
<?php endif;?>
</div><!--end content2-->
</div><!--end content-->
</div><!--end wrapper-->
<script type="text/javascript" src="assets/js/docevents.js"></script>
</body>
</html>
<!-- Localized -->
Can someone advise why I cannot get my code to validate? it looks fine to me.
The validator states " Parse error: syntax error, unexpected "{" in CODE on line 271.
Error Parsing CODE"
The code returns 500 Internal server error if I run it.
The error is in your elseif condition
(strpos($row['price'] != NULL && strpos($row['price']) != '0' && strpos($row['caption'],'DIGITAL') !== true)
^^ ^
|missing ")" missing 2nd argument
missing 2nd argument
I can't even tell what you're trying to do here. Also, strpos will never return boolean true so your check at the end of this line will never be successful.
I would also suggest using PHP's alternative syntax for control structure when mixing PHP and HTML. Something like this...
<?php if (strpos($row['caption'],'DIGITAL') !== false) : ?>
<input type="button" class="item_add" id="s<?= $n ?>" value="Add to cart"/>
<?php elseif (/* some other logic */) : ?>
<input type="button" class="item_add" id="s<?= $n ?>" value="Add to cart"/>
<!-- this line is exactly the same as the previous one?!? -->
<?php endif ?>
You can check below code in http://www.piliapp.com/php-syntax-check/ url for validation and get "No syntax errors detected in CODE" message.
You can use this code instead of your code definitely work.
<?php if (strpos($row['caption'],'DIGITAL') !== false){ ?>
<input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart"/>
<?php } elseif ($row['price'] != NULL && $row['price'] != '0' && strpos($row['caption'],'DIGITAL') !== true) {?>
<input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart"/>
<?php } ?>
This got the code to work:
<?php if (strpos($row['caption'],'DIGITAL') !== false){ ?>
<input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart"/>
<?php }
elseif ($row['price'] != NULL && $row['price'] != '0' && strpos($row['caption'],'DIGITAL') !== true) {?>
<input type="button" class="item_add" id="s<?php echo $n; ?>" value="Add to cart"/>
<?php } ?>
<?php else: ?>
<div style="height:100px; float: left; clear:both"></div>
<?php endif; ?>

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.

Security Flaw in php form

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

Categories