Why does my simple mail php form take a long time to load? - javascript

Good afternoon Stack! I'm currently working on a simple PHP mailing form and my previous version before I started editing it took less than a second to actually load the form, however with these new additions it's now taking over at least 5-10 seconds to load the form.
This is my current code now that takes pretty long to load and here is a LIVE LINK;
<?php
// We use the name2 field as bait for spambots. It's display is off,
// so humans wouldn't know to enter anything into it. Robots would,
// so we ignore submissions with info in name2.
$mail_sent = false;
if(sizeof($_POST) && $_POST["name2"] == "") // receiving a submission
{
// receiving a submission
$to = $_POST['department'];
// prep our data from the form info
$senderName = $_POST['name'];
$senderEmail = $_POST['email'];
$department = $_POST['department'];
$subject = "Visitor message in $department department";
$messageBody = $senderName . ' ('.$senderEmail.') wrote for '.$department.' department: ' . $_POST['message'];
if($department == 'customer') { //if customer was selected
$to = 'email#email.com';
}
else if($department == 'distribution') { //if distribution was selected
$to = 'email#email.com, email#email.com';
}
else if($department == 'press') { //if press was selected
$to = 'email#email.com';
}
else if($department == 'career') { //if career was selected
$to = 'email#email.com';
}
else if($department == 'other') { //if other was selected
$to = 'email#email.com';
}
// From
$header = "From: $senderName <$senderEmail>";
}
// Send it!
$send_contact = mail($to, $subject, $messageBody, $header);
if($send_contact){
$mail_sent = true;
}
else {
echo " ";
}
?>
One thing I did find weird though, making my changes to send to multiple reciepents started telling me ERROR even though it worked perfectly fine, so I changed..
if($send_contact){
$mail_sent = true;
}
else {
echo "ERROR";
}
to print nothing but a space, so users don't see it.. Maybe, this is what could cause it that something is actually going on which prolongs the delay of loading? But.. It works fantastic and perfectly fine.
Anyone have any clue why this form can take so long to be loading? It's definitely the code as I removed it or reverted back to my old version, it loads in less than a second with ySlow.
Here is the PREVIOUS version of my code that loads instantly and a LIVE LINK;
<?php
// We use the name2 field as bait for spambots. It's display is off,
// so humans wouldn't know to enter anything into it. Robots would,
// so we ignore submissions with info in name2.
$mail_sent = false;
if(sizeof($_POST) && $_POST["name2"] == "") // receiving a submission
{
define("SUBJECT", "Visitor Message from Domain.com");
// production recipient:
define("RECIPIENT", "email#email.com");
// prep our data from the form info
$senderName = $_POST['name'];
$senderEmail = $_POST['email'];
$subject = SUBJECT;
$messageBody = $senderName . ' ('.$senderEmail.') wrote:
' . $_POST['message'];
// From
$header = "from: $senderName <$senderEmail>";
// To
$to = RECIPIENT;
// Send it!
$send_contact = mail($to, $subject, $messageBody, $header);
// Check success of send attempt
if($send_contact){
// show thankyou screen
$mail_sent = true;
}
else {
// send failed.
echo "ERROR";
}
}
?>
Any help is kindly appreciated as I've been stuck on this for awhile, thank you for your time and efforts and have a wonderful weekend everyone.

$send_contact = mail($to, $subject, $messageBody, $header);
if($send_contact){
$mail_sent = true;
}
else {
echo " ";
}
This part of the code was left out of the if block that handles your form submission in your new version. So it gets executed every time the page gets loaded. That will slow down the loading because the mail() function tries to send an email and gives an error every time you load the page. Your intention was to send an email only when the form gets correctly submitted. Turning on php notices would be a good idea since. It would make catching errors like this easier.

Related

Joomla 3.x Contact Form - Automatic Email Edits

Please be aware I am not very familiar with JavaScript and I am doing this to help out a coworker.
I am trying to make an edit to the contact form automatic email replies. The change I am looking to make is when a person sends an email to someone on the website a reply is sent back to the person stating "This is a copy of the following message you sent to WEBSITE PERSON via WEBSITE NAME." The person receiving the email only gets the name of the person that sent it and the message.
I need to add the "This is a copy of the following message you sent to WEBSITE PERSON via WEBSITE NAME" message to the other email because one person is receiving all emails and sending them to the appropriate person. I know, this sounds unreasonable but it is what has been requested.
I found the code in contact.php but I am not entirely sure how to make the change.
This is where the code is getting the portion that I need:
// Check whether email copy function activated
if ($copy_email_activated == true && !empty($data['contact_email_copy']))
{
$copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename);
$copytext .= "\r\n\r\n" . $body;
$copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);
$mail = JFactory::getMailer();
$mail->addRecipient($email);
$mail->addReplyTo($email, $name);
$mail->setSender(array($mailfrom, $fromname));
$mail->setSubject($copysubject);
$mail->setBody($copytext);
$sent = $mail->Send();
}
return $sent;
}
}
And I need the above to work with
// Prepare email body
$prefix = JText::sprintf('COM_CONTACT_ENQUIRY_TEXT', JUri::base());
$body = $prefix . "\n" . $name . ' <' . $email . '>' . "\r\n\r\n" . stripslashes($body);
// Load the custom fields
if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact->email_to, true, $data['com_fields']))
{
$output = FieldsHelper::render(
'com_contact.mail',
'fields.render',
array(
'context' => 'com_contact.mail',
'item' => $contact,
'fields' => $fields,
)
);
if ($output)
{
$body .= "\r\n\r\n" . $output;
}
}
$mail = JFactory::getMailer();
$mail->addRecipient($contact->email_to);
$mail->addReplyTo($email, $name);
$mail->setSender(array($mailfrom, $fromname));
$mail->setSubject($sitename . ': ' . $subject);
$mail->setBody($body);
$sent = $mail->Send();
I thought it would be as simple as copying some code around but I am was very wrong. I knwo there are overrides in Joomla to prevent core code from being touched. As soon as I can get this figured out I can do the override to properly add my changes.
Thank you in advance!
Sorry, i used mobile so it hard to check
// Check whether email copy function activated if ($copy_email_activated == true && !empty($data['contact_email_copy'])) { $copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename); $copytext .= "\r\n\r\n" . $body; $copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);
// Load the custom fields if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact->email_to, true, $data['com_fields'])) { $output = FieldsHelper::render( 'com_contact.mail', 'fields.render', array( 'context' => 'com_contact.mail', 'item' => $contact, 'fields' => $fields, ) ); if ($output) { $copytext .= "\r\n\r\n" . $output; } }
$mail = JFactory::getMailer(); $mail->addRecipient($email); $mail->addReplyTo($email, $name); $mail->setSender(array($mailfrom, $fromname)); $mail->setSubject($copysubject); $mail->setBody($copytext); $sent = $mail->Send(); } return $sent; } }

Equal sign in javascript mailto url getting parsed on Android

I have a web app that sends a URL link in the body of the email from a button onclick="email();". The url is a php page with .php?id= and everything after equal sign is getting truncated when sent from an Android device.
I have tried encoding the URL but nothing is working...
I know the mailto tag uses the = sign as a parsing character...but still cannot figure this out.
Here is code.
function email() {
window.location.href = "mailto:?subject=LIVE link!&body=Here is a link for a LIVE demo!%0D%0Awww.domain.ca/scores/" + sport + "php%3Fid%3d" + id +"%0D%0A%0D%0AThanks";
}
Any suggestions or experience in this?
Works fine on all other platforms (iOS, Windows etc)
Turns out is was specific to Outlook app on Android device.
This is from one of my sites..
<?php
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['mail'];
$message = $_POST['appointment'];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
$email_from = 'Client';//<== update the email address
$email_subject = "Booking an appointment";
$email_body = "You have received a new message from the user $name.\n"."Here
is the message:\n $message";
$to = "somebody#hotmail.com ";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: aboutUs.html');
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>

How do I return my Form errors

My php runs but for some reason my variables are not being communicated. What am I doing incorrectly? I am trying to relay the message through ajax and i can't seem to get any type of error or success message to pop up, no matter where I put it in my php..which leads me to believe that the problem lies inside my ajax/javascript functions. The ajax should place the message straight in the defined . I also realize this has been asked before on here but I have truly looked at a lot of them and still can not figure out what's wrong. Thanks guys, sorry for the wall.
AJAX
<!-- Email -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('#sub_result').html("");
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'phEmail.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for email ---------------
if (data.errors.email) {
$('#sub_result').addClass('class="error"'); // add the error class to show red input
$('#sub_result').append('<div class="error">' + data.errors.email + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('#sub_result').append('<div class="success" >' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
PHP
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false)
{
$errors['email'] = 'Email is not valid';
}
if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
}
// if there are items in our errors array, return those errors============================
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
//variables===============================================================================
$servername = "localhost";
$username = "ghostx19";
$password = "nick1218";
$dbname = "ghostx19_samplepacks";
$user = $_POST['email'];
// Create connection======================================================================
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Connection failed";
}
//add user================================================================================
$sql = "INSERT INTO users (email)
VALUES ('$user')";
if ($conn->query($sql) === TRUE) {
$data['success'] = true;
$data['message'] = 'Subscribed!';
} else {
$errors['email'] = 'Error';
}
$conn->close();
// message to me==========================================================================
$to = 'garvernr#mail.uc.edu';
$subject = 'New subscription';
$message = $_POST['email'];
$headers = 'From: newsubscription#samplepackgenerator.com' . "\r\n" .
'Reply-To: newsubscription#samplepackgenerator.com';
mail($to, $subject, $message, $headers);
//message to user=========================================================================
$to = $_POST['email'];
$subject = 'Subscribed!';
$message = 'Hello new member,
Thank you for becoming a part of samplepackgenerator.com. You are now a community member and will recieve light email updates with the lastest information. If you have recieved this email by mistake or wish to no longer be apart of this community please contact nickgarver5#gmail.com
Cheers!,
-Nick Garver ';
$headers = 'From: newsubscription#samplepackgenerator.com' . "\r\n" .
'Reply-To: newsubscription#samplepackgenerator.com';
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
?>
HTML
<!-- Subscription -->
<div class="container shorter">
<div class="no-result vertical-align-outer">
<div class="vertical-align">
<form action="phEmail.php" method="POST">
<!-- EMAIL -->
<div id="email-group" class="form-group">
<label for="email"></label>
<input type="text" class="email" name="email" placeholder="Enter your email">
<button type="submit" class="emailbtn">Subscribe</button>
<span></span>
<!-- errors -->
</div>
</div>
</div>
</div>
<br>
<br>
<div id="sub_result">
</div>
You just need to use json_encode in your PHP becuase your data type is json and you are expecting the response in json format like that
if (!empty($error)){
// your stuff
$data['success'] = false;
$data['errors'] = $errors;
echo json_encode($data);
}
else {
// your stuff
$data['success'] = "SUCCESS MESSAGE";
$data['errors'] = false;
echo json_encode($data);
}
That's because you forgot to encode your $data array. Do echo json_encode($data); just before your ending PHP tag(?>), like this:
// your code
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo json_encode($data);
?>
Your php don't return any value, add a simple "echo" line at the end:
...
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo $data['message'];
?>
And in js (if all the other code is correct) you receive the message.
Your php file doesn't send anything to the output.
Add a line
exit(json_encode($data));
to your php file on the line where you want to return your reply.

Issue with Captcha system on PHP, AJAX Contact form

In 2011, I bought a PHP contact form from codecanyon that uses AJAX to process the form. After reporting my problem to them today, they responded saying that they no longer offer support for their 'old' product (so much for the life time support they generally offer as a rule) ... so they aren't going to help me hence this post on SO.
I would say that this isn't a normal issue but I think it's very important that it gets sorted out - here it is (this is my email to the seller but does explain the problem):
=================
I have an unusual issue with your AJAX Contact Form (you're going to have to read carefully and slowly).
Okay everything works 100% fine BUT ... let me explain (basically this has everything to do with the Captcha and verification of it)
My website has many pages with your online form on each of those pages.
Now I also have a listings page that has links going to all of those pages with forms.
EXAMPLE:
Lets say I am on a listings page (a page with a whole load of links going to other pages) and I right click on Link A to open page A in a new tab ... and then I also right click on Link B to open page B in a new tab. Right, so we have the listings page (that's still opened in front of me) and those 2 other pages that opened up in new tabs (Page A and Page B) ... as explained above, both those pages has your online form.
Now, I fill in both forms and click submit.
The first page that I right clicked to open in a new tab (Page A) - that form's Captcha doesn't work even when I've verified it correctly... however the form's Captcha on Page B does work (like it should). Why is it that the Captcha on Page A (the first page I opened) doesn't work?
I get the feeling that in the whole verification system, because Page B was opened up last, the verification is taking that page's captcha code into account, using that captcha for verification (throughout the session surfing on my website) thus making the Captcha on the first opened page (Page A) to not work.
So what I did as an experiment:
I restarted and did the same thing again, IE: I right clicked Link A to open page A in a new tab ... and then I also right click on Link B to open page B in a new tab.
I filled in Page B's Captcha code in Page A's Captcha verification field and what do you know - there's a match!
So this is my problem because I know when some people surf internet (I do this all the time and maybe you do too), they like to right click links to open them in new tabs so that they can get back to them later after browsing the listings page. So the person may have 6 tabs open in the browser and each of those pages has your online form. If the user wants to submit each of those forms, then he/she will experience the exact problem I am reporting above. They will be able to send through 1 form (the last page that was opened in a new tab) but the other page's Captchas won't work unless they refresh the page ... but most people won't think to do that - instead, they will think somethings wrong with the my website - which I am afraid of.
Is there a solution to this?
I'm not even sure if you've noticed this before?
I hoped I've explained the situation clearly and I'd really appreciate it if you could assist.
=================
Now back to you. What's causing this?
There are 3 files needed for the form to work / process etc (I'm not including the CSS file in this post not the html for the form as I don't think it's necessary).
1) process.php
2) image.php (this is for the captcha)
3) ajax.js
PROCESS.PHP
<?php if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$address = "email#example.com";
$bcc = "email#example.com";
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail
address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits
(numbers and no spaces).</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is
incorrect.</li>';
}
if($error != '') {
echo '<div class="error_title"><h6><span>Attention!
</span> Please correct the errors below and try again</h6>';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '<div class="close"></div>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
$e_subject = 'Booking / Enquiry';
$msg = '<html>
<body style="margin:0; padding:0;">
Name: '.$_POST['name'].'
Email: '.$_POST['email'].'
Contact Number: '.$_POST['phone'].'
Notes: '.$_POST['comments'].'
</body>
</html>';
$msg = wordwrap( $msg, 70 );
$headers = "From: $email\r\nBCC:{$bcc}\r\n" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= 'Content-Transfer-Encoding: 8bit'. "\n\r\n" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
echo "<div class='success'>";
echo "<h6>Your Enquiry has been Successfully submitted. </h6>";
echo '<div class="close"></div>';
echo "</div>";
} else {
echo 'ERROR!';
}
}
?>
*Please note that in the process.php code above, I removed a function that seems to validate the email address field - reason why I didn't include it in the code above is because it was heavy with code (would take up a lot of space) and I don't think it's necessary to include
IMAGE.PHP
<?php if (!isset($_SESSION)) session_start(); header("(anti-spam-
content-
type:) image/png");
$enc_num = rand(0, 9999);
$key_num = rand(0, 24);
$hash_string = substr(md5($enc_num), $key_num, 5); // Length of
String
$hash_md5 = md5($hash_string);
$_SESSION['verify'] = $hash_md5;
setcookie("verify", $hash_md5, time()+3600, "/");
session_write_close();
$bgs = array("../../img/1.png","../../img/2.png","../../img/3.png");
$background = array_rand($bgs, 1);
$img_handle = imagecreatefrompng($bgs[$background]);
$text_colour = imagecolorallocate($img_handle, 108, 127, 6);
$font_size = 5;
$size_array = getimagesize($bgs[$background]);
$img_w = $size_array[0];
$img_h = $size_array[1];
$horiz = round(($img_w/2)-
((strlen($hash_string)*imagefontwidth(5))/2),
1);
$vert = round(($img_h/2)-(imagefontheight($font_size)/2));
imagestring($img_handle, $font_size, $horiz, $vert, $hash_string,
$text_colour);
imagepng($img_handle);
imagedestroy($img_handle);
?>
AJAX.JS
jQuery(document).ready(function() {
$('.advertform').submit(function() {
var action = $(this).attr('action');
var form = this;
$('.submit', this).attr('disabled', 'disabled').after(
'<div class="loader"></div>').addClass("active");
$('.message', this).slideUp(750, function() {
$(this).hide();
$.post(action, {
name: $('.name', form).val(),
email: $('.email', form).val(),
phone: $('.phone', form).val(),
comments: $('.comments', form).val(),
verify: $('.verify', form).val()
},
function(data) {
$('.message', form).html(data);
$('.message', form).slideDown('slow');
$('.loader', form).fadeOut('fast', function() {
$(this).remove();
});
$('.submit',
form).removeAttr('disabled').removeClass("active");
});
});
return false;
});
$('.message').on('click', function(){
$('.message').slideUp();
});
});
Looking at the code above, can anyone spot what could be causing this problem? I'm assuming this can has to do with the javascript?
The comments are correct, the validation is failing on some forms because the session only holds the value of the last captcha generated therefore making captchas open in other tabs invalid because their value in the session was overwritten. Because of this, anyone using the same or similar code has this problem.
You can solve it fairly simply by changing the session to store an array of codes instead of just one.
In image.php, change:
$_SESSION['verify'] = $hash_md5;
to:
if (!isset($_SESSION['verify'])) $_SESSION['verify'] = array();
$_SESSION['verify'][$hash_md5] = $hash_md5; // *explantion for this array key later
You can also get rid of the cookie that gets set for the captcha, session storage should be fine.
Then in your form processor, change:
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.</li>';
}
to:
if(!array_key_exists($posted_verify, $session_verify)) {
$error .= '<li>The verification code you entered is incorrect.</li>';
}
This should allow you to have multiple forms open in multiple tabs and still be able to submit each one without getting the incorrect captcha error.
Also, another issue with this code is that it doesn't unset the session verify value after a successful post. This means a person could solve one captcha and submit your form an unlimited number of times re-using the old code as long as they don't access image.php again between submissions.
To fix this with the array version, you'll need to unset the session key after the captcha and form is processed.
unset($_SESSION['verify'][$posted_verify]); // remove code from session so it can't be reused
Hope that helps.
I have an idea. Store the captcha values in an array, and keep a counter; both stored in SESSION variables.
So in the form you put a hidden input, and set it to the index.
When we check for captcha, we compare $_SESSION['captcha'][$index] to $_POST['captcha'].
Any time you (the client) open a new window; $index is increased.
We pass that index to image.php through the url; example src="img.php?index=2"
Here is a concept; minimal code to accomplish this.
Open a couple of windows with this page. See what happens
img.php
<?php
session_start();
header("(anti-spam-content-type:) image/png");
$captcha_text = rand(0, 99999);
// we read a "index" from the URL, example: <img src="img.php?index=2">
$index = isset($_GET['index']) ? (int) $_GET['index'] : 0;
if( empty($_SESSION['captcha'])) {
$_SESSION['captcha'] = array();
}
$_SESSION['captcha'][$index] = $captcha_text;
// #see http://php.net/manual/en/function.imagestring.php , first example
$im = imagecreate(100, 30);
$bg = imagecolorallocate($im, 55, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, $captcha_text, $textcolor);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
index.php
<?php
session_start();
// we handle the POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_SESSION['captcha'])) {
if ($_SESSION['captcha'][ $_POST['index'] ] == $_POST['captcha']) {
echo '<h2>correct</h2>';
}
else {
echo '<h2>not correct</h2>';
}
echo '<a href="index.php">Back to form</form>';
// header('location: index.php');
exit;
}
// normal page, with form
if(isset($_SESSION['captcha_index'])) {// index
// set a new index
$_SESSION['captcha_index']++;
}
else {
$_SESSION['captcha_index'] = 0;
}
$captcha_index = $_SESSION['captcha_index'];
echo '
<img src="img.php?index=' . $captcha_index . '">
<form action="" method="post">
<input name="captcha">
<input name="index" type="hidden" value="' . $captcha_index . '">
<input type="submit" value="GO">
</form>
';
// we show what's happening. Obviously you don't want to print this after test phase
$captcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : array();
echo '
<br>print_r of $_SESSION[captcha]
<pre>' . print_r($captcha, true) . '<pre>
';
?>

PHP and Javascript - Problems with undefinded variable

Hey guys i am very new to this so i am sorry if there is just something completely stupid i am missing here. I have the following Sign Up Form. And in the URL http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de i am trying to submit the value e. However, in all cases e is simply empty or undefined:
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$p = $_POST['p'];
$e = $_GET['e'];
echo "test";
echo "$e";
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM team WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "UPDATE team
SET username='$u',password='$p_hash',ip='$ip',signup=now(),lastlogin=now(),notecheck=now()
WHERE email='$e'";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>yoursitename Message</title></head>
<body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;">
<div style="padding:10px; background:#333; font-size:24px; color:#CCC;">
<img src="http://www.rockaholics-cologne.de/root/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">Account Activation</div>
<div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* Username: <b>'.$u.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
I do get new entries into the database when i fill out the form. But it does neither send me an email or UPDATE the database at the specified email. It simply updates all the entries with a blank email. The echo "$e" within the script also return nothing.
I used this code to check:
<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
$e = $_GET['e'];
echo "$e";
?>
And in this case it does return an array with [e]=cataras#gmx.de and it also prints out $e. But why doesnt it work in the other skript? I'm using the exact same methods to get e from the URL.
When i run my Javascript function:
function signup(){
var u = _("username").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.replace(/^\s+|\s+$/g, "") == "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&p="+p1);
}
}
I get Uncaught ReferenceError: e is not defined. And the site stops at "please wait...". I just took out the +e+ in the js to get to the php above. Sorry for the long post but i am really running out of ideas. THANKS in advance!!!
I think $_GET['e'] is not working in your original script because it's not getting passed to that processing script from your form page. I accessed the URL you provided (http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de). Note that when you submit your form, the value of "e" in your URL is not being passed to whatever is processing your script. In your form, you need to either do this:
<form action="{yourscripturl}?e=<?php echo $_GET['e']?>" {rest of form tag}>
Or, add a hidden to hold the value of "e", and then use $_POST['e'] on your processing script instead of $_GET['e'].
<input type="hidden" name="e" value="<?php echo $_GET['e']?>" />

Categories

Resources