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>
';
?>
Related
I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.
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.
I'm trying to have the mail.php script identify the page that called the script, and return the user to that page and if the form didn't validate, was empty, etc. When I click on submit, it just 404's.
<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "email#email.com";
/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$email_address = $_REQUEST['email'];
$comments = $_REQUEST['comment'];
$fname = $_REQUEST['first-name'];
$lname = $_REQUEST['last-name'];
$filename = debug_backtrace();
$page = $filename[0]['file'];
/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
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;
}
}
// If the user tries to access this script directly, redirect them to the feedback form,
if (!isset($_REQUEST['email_address'])) {
header( "Location: $page" );
}
// If the form fields are empty, redirect to the error page.
elseif (empty($email_address) || empty($comments) || empty($fname)) {
echo "<script type=\"text/javascript\">window.alert('Please fill in the required fields.');
window.location.href = $page;</script>";
exit;
}
// If email injection is detected, redirect to the error page.
elseif (isInjected($email_address)){
echo "<script type=\"text/javascript\">window.alert('Please, Try Again.');
window.location.href = $page;</script>";
exit;
}
// If we passed all previous tests, send the email then redirect to the thank you page.
else {
mail("$webmaster_email", "Feedback Form Results", $comments, "From: $email_address");
echo "<script type=\"text/javascript\">window.alert('Thank You for contacting us!');
window.location.href = $page;</script>";
exit;
}
?>
No need for debug_backtrace(). To get the referring page, you could replace this:
$filename = debug_backtrace();
$page = $filename[0]['file'];
With this:
$page = $_SERVER['HTTP_REFERER'];
However, $_SERVER['HTTP_REFERER'] is unreliable according to the PHP docs:
This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
So another solution is to add an additional field in the referring form and retrieve it in the PHP script e.g.
<input name="referrer" type="hidden" value="<?php echo $_SERVER['PHP_SELF'];?>"/>
Then:
$page = $_REQUEST['referrer'];
I am new to development with HTML, PHP, CSS etc.
I need to do this small Registration and Login Form. I haven't gone into detail in Object-Oriented PHP and I'm working in the simplest manner as this task needs to be done in a short time and I've only been coding and experimenting with these languages these past two days.
What I already have is a working Registration and Login forms that when they are submitted the information is posted to another php file. Than it verifies that the data has been entered and that the e-mail isn't already used. What i need is that when either the e-mail is already used and when a field is left empty that it automatically goes back to Registration/Login forms and displays a message with their respective errors.
I know this might have been done in a different way but the deadline is really close and so i need a solution that works with what I already have.
I'm sorry if a similar question is already available, but i might be using incorrect keywords to search for the solution.
Keywords currently that I'm using are Redirection, "Going back to previous page".
If JavaScript is more suitable for this kind of operation it is also excepted and would like this to be pointed out, although a php solution would be appreciated a bit more as i currently obtain more knowledge on PHP than on JavaScript.
Thanks, any help or directions to suitable solutions would be mostly appreciated.
You can use
A) PHP header() function
B) echo a META HTTP - EQUIV=" refresh "
CONTENT=" seconds; URL = \the-other-url">
C) Use JS like this but you
will need to set a timeout
Example:
if (empty ($_POST ['username']) || empty ($_POST ['password']))
{
echo "Please enter a username, or password";
header ("refresh:5; url=back.php");
exit;
}
There are many different ways to do this. If when the form is submitted your executing the code on a different php file then you could have an IF statement there which redirects the headers back to the form page if there are errors with the users input such as:
if($username == "")
{
header("Location: YOUR_FORM_PAGE.php");
}
Hope this helps.
To add the execution to the same page you can do this.
add these buttons;
<input type="hidden" id="submitted" name="submitted" value="1">
<span class="label"></span><input type="submit" class="submit" value="Submit"><input type="reset" class="submit" value="Clear">
set the form action to the form page. Add this to the top of the page and add any PHP you want to it;
if(isset($_POST["submitted"]) && $_POST["submitted"] == 1)
{
for example;
if($from_fullname == "")
{
$submission_status = '<div class="vpb_info" align="left">Please enter your fullname in the required field to proceed. Thanks.</div>';
}
and add this to the page where you want the error displayed;
<p> <?php echo $submission_status; ?></p>
Sounds like http-redirect (http://php.net/manual/en/function.http-redirect.php) should help you out. You can redirect on your error conditions with that.
Update
With redirect you can attatch QueryString Parameters so you could redirect back to the login.php page with an errror code and/or message as a query string perameter.
These will get you started, a registration or signup php file and a login php file I made once
(personal info is faked).
SignUp.php
<?php
session_start();
$name = $_REQUEST['name'] ;
$userpassword = hash('sha512',$_REQUEST['password'] );
$signature = $_REQUEST['signature'] ;
$image = $_REQUEST['image'];
$email = $_REQUEST['email'] ;
$emailreplies = $_REQUEST['emailreplies'] ;
if (!isset($_REQUEST['name'])) {
header( "Location: MotesBlog.php" );
}else{
$username="root";
$password="root";
$database="MotesBlog";
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query=sprintf("SELECT Name FROM users WHERE Name LIKE '%s';",
mysql_real_escape_string($name));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$query = sprintf("SELECT Email FROM users WHERE Name='%s';",
mysql_real_escape_string($name));
$query=mysql_query($query);
$_SESSION['NameTaken'] = true;
$_SESSION['UsedName'] = $name;
$_SESSION['UsedEmail'] = mysql_result($query,0);
header("Location: SignUp.html");
}else{
$query=sprintf("SELECT Email FROM users WHERE Email LIKE '%s';",
mysql_real_escape_string($email));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$_SESSION['EmailTaken'] = true;
$_SESSION['UsedEmail'] = $email;
header("Location: SignUp.html");
}else{
$query = sprintf(" INSERT INTO users VALUES (
NULL , '%s', '%s' , '%s', '%s', '%s', CURRENT_TIMESTAMP , 0, $emailreplies);",
mysql_real_escape_string($name),
$userpassword,
mysql_real_escape_string($signature),
mysql_real_escape_string($image),
mysql_real_escape_string($email));
mysql_query($query);
$query = sprintf("SELECT JoinDate FROM users WHERE Name='%s';",
mysql_real_escape_string($name));
$vcode=md5(mysql_result(mysql_query($query),0));
mysql_close();
require_once "Mail.php";
$from = "PocketWoods Hunting Hall<pwoods#email.com>";
$to = $email;
$subject = "Welcome to Motes Blog";
$body = "<html>
<body>Thank you for your time. <br/>
To ensure a human made this account and not an
automated process please click the link below:<br>
<a href=\"http://site.com/MotesBlog/verifyaccount.php?vcode=".$vcode."&name=".$name."\">
Activate Account
</a>
</body>
</html>";
$host = "mail.root.com";
$username = "root#root.com";
$password = "root";
$headers = array ( 'From' => $from,
'To' => $to,
'Subject' => $subject,
'MIME-Version' => "1.0",
'Content-type' => "text/html; charset=iso-8859-1");
$smtp = Mail::factory('smtp',
array ( 'host' => $host,
'auth' => false,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
header("Location: success.html");
}
}
}
?>
Login.php
<?php
session_start();
$username="root";
$password="root";
$database="MotesBlog";
mysql_connect("localhost",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$user_name = $_REQUEST['name'];
$user_password = $_REQUEST['password'];
if (!isset($_REQUEST['name'])) {
header( "Location: MotesBlog.php" );
}else{
if(isset($_SESSION['User'])){
if( ($_SESSION['CreatedTime'] + 3600) < time() ){
$_SESSION['Expired'] = true;
}
unset($_SESSION['User']);
}
$query = sprintf("SELECT Password FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
if(mysql_num_rows($query)){
$real_password=mysql_result($query,0);
$query = sprintf("SELECT Email FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
$email = mysql_result($query,0);
if($real_password == hash('sha512',$user_password)){
$query = sprintf("SELECT Validated FROM users WHERE Name='%s';",
mysql_real_escape_string($user_name));
$query=mysql_query($query);
mysql_close();
if(mysql_result($query,0)){
$_SESSION['User'] = $user_name;
$_SESSION['CreatedTime'] = time();
setcookie("User", $_REQUEST['name'], time() + 60*60*24*365);
header( "Location: MotesBlog.php" );
}else{
$_SESSION['resend_name'] = $user_name;
$_SESSION['resend_email'] = $email;
$_SESSION['NotValidated'] = true;
header( "Location: MotesBlog.php" );
}
}else{
$_SESSION['WrongPW'] = true;
$_SESSION['UsedEmail'] = $email;
header( "Location: MotesBlog.php" );
}
}else{
$_SESSION['WrongName'] = true;
header( "Location: MotesBlog.php" );
}
}
?>
I'm creating an online chat box for me and my friends at college to use online. In the current configuration, the chat messages are stored in a plain text file on the host machine (mine) and are fetched via AJAX every second, however, sometimes it is slow and glitchy and doesn't always work.
To send a message, it passes the message to a JavaScript function which passes the value to a PHP script, writing it to the file along with the user's unique color (stored in a local cookie). Here's the functions.js file (pastebin): http://pastebin.com/CpGxj5cP
Here's the php file to send the message:
<?php
session_start();
require_once('mysql_connect.php');
date_default_timezone_set("EST");
//Format the message
$date = date('n/j g:i A');
$username = $_SESSION['username'];
$color = $_COOKIE[$username];
$message = "<font color='" . $color . "'>" . $username . "</font> (" . $date . "): ";
$message .= $_GET['m'] . "\n";
$file = '../messages.txt';
$handle = fopen($file, 'a');
fputs($handle, $message);
fclose($handle);
//Reset timeout
//$_SESSION['timeout'] = 300;
?>
As I said above, the issue is that it's very very slow. If there's a way to do it better than a textfile/AJAX, please let me know!
Yes there is a better way if you are using a browser that supports HTML 5
Web Sockets
http://www.tutorialspoint.com/html5/html5_websocket.htm
Check this out for a full code of a chat box using PHP. Download the source code or see the live demo in this site.
Moderator note: This link is no longer alive, and archive.org does not seem to have a copy, either.
http://purpledesign.in/blog/?p=19
function getLoginBox() {
ob_start();
require_once('login_form.html');
$sLoginForm = ob_get_clean();
$sLogoutForm = 'logout';
if ((int)$_REQUEST['logout'] == 1) {
if (isset($_COOKIE['member_name']) && isset($_COOKIE['member_pass']))
$this->simple_logout();
}
if ($_REQUEST['username'] && $_REQUEST['password']) {
if ($this->check_login($_REQUEST['username'], MD5($_REQUEST['password']))) {
$this->simple_login($_REQUEST['username'], $_REQUEST['password']);
return 'Hello ' . $_REQUEST['username'] . '! ' . $sLogoutForm;
} else {
return 'Username or Password is incorrect' . $sLoginForm;
}
} else {
if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {
if ($this->check_login($_COOKIE['member_name'], $_COOKIE['member_pass'])) {
return 'Hello ' . $_COOKIE['member_name'] . '! ' . $sLogoutForm;
}
}
return $sLoginForm;
}
}
Of course you will need to create a log in box. Kindly check the link I have shared. It has all the details