Contact Form - JQuery & PHP - sending email not working [duplicate] - javascript

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
Is my code ok to send and email using PHP? Please take a look:
HTML:
<form class="contact_form" method="POST" action="mail.php">
<div class="input">
<label class="pl">Imię</label>
<input id="name" type="text" name="name">
</div>
<div class="input">
<label>E-mail</label>
<input id="email" type="text" name="email">
</div>
<div class="input">
<label class="pl">Temat</label>
<input id="subject" type="text" name="subject">
</div>
<div class="message">
<label class="pl">Twoja wiadomość</label>
<textarea id="message" name="message"></textarea>
</div>
<div class="input">
<input id="submit_pl" class="button pl" type="submit" value="Wyślij">
<input id="reset_pl" class="button pl" type="reset" value="Resetuj">
</div>
</form>
JS/JQuery:
// Form Validation ------------------------------------ //
// Form is not valid on page load //
var isFormValid = false;
// input variables //
var name = $('#name');
var email = $('#email');
var subject = $('#subject');
var message = $('#message');
var subtmitBtnPl = $('#submit_pl');
var subtmitBtnEn = $('#submit_eng');
var resetBtnPl = $('#reset_pl');
var resetBtnEn = $('#reset_eng');
var form = $('.contact_form');
var isNameValid = function () {
var nameVal = name.val();
return nameVal.length > 0 && nameVal.length <= 100;
};
var isEmailValid = function () {
var emailVal = email.val();
return emailVal.indexOf('#') > -1 && emailVal.length <= 100;
};
var isSubjectValid = function () {
var subjectVal = subject.val();
return subjectVal.length > 0 && subjectVal.length <= 100;
};
var isMessageValid = function () {
var messageVal = message.val();
return messageVal.length > 0 && messageVal.length <= 500;
};
function formValidation() {
var isFormValid = isNameValid() && isEmailValid() && isSubjectValid() && isMessageValid();
if (isFormValid === false) {
alert('error');
} else {
alert('succes');
form[0].reset();
}
};
form.submit(function(event) {
event.preventDefault();
formValidation();
});
PHP:
<?php
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['subject'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['message'];
$to = 'xyz#gmail.com';
//headers
$headers = "From: ".$name." <".$email.">\r\n";
$headers .= "Reply-To: ".$email."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset-utf-8";
//send
$send = mail($to, $subject, $body, $headers);
if ($send) {
echo '<br>';
echo 'Thanks for contacting me. I will be with You shorty.';
} else {
echo 'error';
}
}
?>
I'm very unexperienced with PHP. Could You please tell me why my contact form is not working/sending emails?
JQuery Validation works fine.
This project is just on my drive not localhost (is it ok for PHP mail() to work?).
Of course PHP file has name "mail.php".

install a web server like XAMPP,WAMPP, etc

Related

Uploading an image, then displaying it as a Canvas on the next page

I'm attempting to create a page that allows the manipulation of an uploaded image by using Canvas. So far, I've had no luck forwarding the image from one page (the submit form) to the other, which contains the canvas. I'm using PHP, Javascript and HTML in order to try and send the image from the submit form to the canvas space.
This is the submitting form.
<form action="designer.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label><?php
include('/tbp3/php/autoload.php');
header('Content-Type: application/json');
$fullpath = $_SESSION['activeImg'];
$size = getimagesize($fullpath);
echo json_encode(array('x' => $size[0], 'y' => $size[1], 'path' => $fullpath, 'lastPosJson' => isset($_SESSION['lastPos']) ? $_SESSION['lastPos'] : '[]'));
$db->close();
?>
<p>2-32 characters</p>
<input class="form-control" type="text" name="name" id="name">
</div>
<div class="form-group">
<p>JPEG/PNG under 2MB only</p>
<label class="btn btn-default" for="image">Choose Image</label>
<span></span>
<input class="inputfile" type="file" name="image" id="canvas">
</div>
<div class="form-group">
</div>
<input class="btn btn-primary" type="submit" value="Next">
</form>
This is the JavaScript I use in order to confirm the uploaded file is a PNG or JPEG. Note: I'm a novice at Javascript.
var validTypes = ['png', 'jpg', 'jpeg'];
$(document).ready(function(){
$('form').submit(function(e){//on submission..
var file = $('#upload').val();
var isValid = true;
var error = '';
if(file == ''){
error = 'Select a file before proceeding!';
$('#upload').addClass('validation-error');
isValid = false;
} else{
var type = /[^\.]*$/.exec(file).toString().toLowerCase();
if($.inArray(type, validTypes) == -1){
error = type + ' is an invalid type for the image! Please use ' + validTypes.join(', ').replace(/,([^,]*)$/, " or$1.");
$('#upload').addClass('validation-error');
isValid = false;
}
}
});
And this is on the page 'Designer.php'. I want the image to be displayed on the tag.
<div class="row canvasarea">
<div class="col-xs-6 header">Canvas</div>
<div class="col-xs-6 header">Live View</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6 help">TEXT</div>
<div class="col-xs-6 help">TEXT</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6">
<canvas id='canvas'></canvas></div>
<div class="col-xs-6">
<img id='liveupdate'/><br></div>
The PHP script I'm using to save it to the server.
<?php
require('/var/www/html/tpb3/php/autoload.php');
session_start();
$megabyte = 8000000;
$db = "new Database();";
function getImage(){
$id = $this->getTemplateId();
$type = $this->getFiletype();
return "img/template/$id.$type";
}
function addTemplate($templateId, $filetype){
if(!$this->isLoggedIn()){
echo "You're not logged in";
return '';
}
function isValidFileType($type){
$type = strtolower($type);
$types = array('jpeg', 'jpg', 'png');
for($i = 0; $i < count($types); $i++){
if($type === $types[$i]){
return true;
}
}
return false;
}
function isPng($filepath){
$img = #imagecreatefrompng($filepath);
if($img === false){
return false;
} else{
echo "Not a PNG";
imagedestroy($img);
return true;
}
}
function isJpeg($filepath){
$img = #imagecreatefromjpeg($filepath);
if($img === false){
return false;
} else{
echo "Not a JPEG";
imagedestroy($img);
return true;
}
}
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
if(!empty($_POST['selectedType']) ){
$selectedType = $_POST['type'];
}
if(isset($_POST["type"]))
$selectedType = $_POST["type"];
$dir = $selectedType == 'template' ? 'temp' : 'sourceimages';
if(isset($_POST["submit"])) {
$valid = true;
$id = uniqid();
$type = strtolower(pathinfo(basename($_FILES['upload']['name']), PATHINFO_EXTENSION));
$uploadFileDest = 'img/template/$id.$type';
$size = #getimagesize($_FILES["upload"]["tmp_name"]);
$error = '';
if($size === false) {
$error .= "Main image not a valid image, ";
$valid = false;
} elseif($size[0] > 2000 || $size[1] > 2000){
$error .= "Image larger than 2000px, ";
$valid = false;
} elseif(!isValidFileType($type)){
$error .= "Not a valid filetype, ";
$valid = false;
} elseif(!isJpeg($_FILES["upload"]["tmp_name"]) && !isPng($_FILES["upload"]["tmp_name"])){
$error .= "Image is not a valid jpg/png. ";
$valid = false;
} elseif ($_FILES["upload"]["size"] > 2 * $megabyte) {
$error .= "File larger than 2 MB, ";
$valid = false;
}
}
if($valid = true){
if($selectedType == 'template'){
$_SESSION['activeId'] = $id;
$_SESSION['activeImg'] = $uploadFileDest;
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
header('Location: designer.php');
} else{
$response = $db->addSourceImage($id, $type);
if($response == ';success'){
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
$_SESSION['lastId'] = $id;
header('Location: success.php');
} else{
header('Location: submit.php?e='.urlencode("Database failed with message: $response"));
}
}
} else{
header('Location: submit.php?e='.urlencode(substr($error, 0, strlen($error) - 2)));
}
}
?>
Any push into the right direction would be appreciated.

contact form unable to reset

I am looking to create a contact Us form in my website, where after the form is submitted, the text fields should be cleared, and a Thank You should appear.
Here is the html code :
<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<form action="contactform.php" method="post" role="form" class="contactForm">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name (eg: James)" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email (eg: james#example.com)" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Phone Number (eg: 0406 624 456)" data-rule="minlen:9" data-msg="Please enter a valid contact number" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<br/>
<div class="text-center">
<button type="submit" name="submit" value="Submit"></button>
<!--b>Send Message</b-->
</div>
</form>
The relevant java script code:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function(){
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function(){ // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if( rule !== undefined ){
var ierror=false; // error flag for current input
var pos = rule.indexOf( ':', 0 );
if( pos >= 0 ){
var exp = rule.substr( pos+1, rule.length );
rule = rule.substr(0, pos);
}else{
rule = rule.substr( pos+1, rule.length );
}
switch( rule ){
case 'required':
if( i.val()==='' ){ ferror=ierror=true; }
break;
case 'minlen':
if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
break;
case 'email':
if( !emailExp.test(i.val()) ){ ferror=ierror=true; }
break;
case 'checked':
if( !i.attr('checked') ){ ferror=ierror=true; }
break;
case 'regexp':
exp = new RegExp(exp);
if( !exp.test(i.val()) ){ ferror=ierror=true; }
break;
}
i.next('.validation').html( ( ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
}
});
f.children('textarea').each(function(){ // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if( rule !== undefined ){
var ierror=false; // error flag for current input
var pos = rule.indexOf( ':', 0 );
if( pos >= 0 ){
var exp = rule.substr( pos+1, rule.length );
rule = rule.substr(0, pos);
}else{
rule = rule.substr( pos+1, rule.length );
}
switch( rule ){
case 'required':
if( i.val()==='' ){ ferror=ierror=true; }
break;
case 'minlen':
if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
break;
}
i.next('.validation').html( ( ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
}
});
if( ferror ) return false;
else var str = $(this).serialize();
$.ajax({
// alert("enterd the loop")
type: "POST",
url: "contactform/contactform.php",
data: str,
success: function(msg){
//alert(msg);
if(msg == "New record created successfully") {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
document.getElementsByClassName("contactForm").reset();
}
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
Relevant php script to obtain db credentials and properties:
<?php include "../../inc/dbinfo.inc"; ?>
<?php
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$Phone = test_input($_POST["Phone"]);
$message = test_input($_POST["message"]);
$submit = test_input($_POST["Submit"])
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "INSERT INTO contact_details (name, email, Phone, message)
VALUES ('$name', '$email', '$Phone', '$message')";
// <script>alert("your message is sent successfully");
// window.location="index.html";
// </script>
if ($connection->query($sql) === TRUE) {
echo "New record created successfully";
mysqli_free_result($result);
mysqli_close($connection);
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
mysqli_free_result($result);
mysqli_close($connection);
}
?>
after submitting the form, the form doesn't reset and displays any message but its getting updated in the database.
Redirect to new page or same page like below:
if ($connection->query($sql) === TRUE) {
mysqli_free_result($result);
mysqli_close($connection);
header('Location: filename?msg=success');
}

How to push data from database and see vote count after each data?

What I'm trying to do is to allow students answer questions and see each vote after each question and then the teacher can push the next question. The votes will then be entered into the database which I can use to produce a chart. I currently have the student answering questions but I'm having problem on stopping the next question from coming so the poll vote can show and how to show the vote before the next question comes.
This gets the questions from the database:
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted"+ p.responseText);
var url = 'quiz.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
On a different php file:
require_once 'core/init.php';
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$connection = mysqli_connect('localhost', 'root', '', 'alsp');
$sql = mysqli_query($connection,"SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: start-quiz.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your username and submit</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<button class="btn btn-action" type="submit" value="finish">Submit</button>
</form>';
exit();
}
$singleSQL = mysqli_query($connection,"SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection,"SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()"class="btn btn-action">Submit</button></span>';
echo $output;
}
}
I'm guessing rather than have a submit button that takes you to the next page, after clicking on a radio button, the vote should show and then the teacher can push the next question. That's were the main issue is.

Javascript PhP mailing Doesnt work in new project

I am trying to integrate an old mailing script I have from a past project to my new site. The process involves a javascript and a php script in the following manner.
<script type="text/javascript">
function send_mail() {
var subject = document.getElementById('subject').value;
var message = document.instanceById('message').getContent();
var params = 'subject='+subject+'&message='+message;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else { xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); }
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById('result').innerHTML=xmlhttp.responseText; }
}
document.getElementById('result').innerHTML = 'Message is sending.. please wait..';
xmlhttp.open('POST', 'scripts/newsletter-mail.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
</script>
The form :
<label><strong>Title</strong></label>
<input type="text" name="subject" id="subject" class="form-control" value="">
<br>
</div>
<div class="col-md-12">
<label><strong>Main Text</strong></label>
<textarea class="summernote" id="text" name="message" id="message" data-plugin-summernote data-plugin-options='{ "height": 300, "codemirror": { "theme": "ambiance" } }'></textarea>
<input class="button" type="submit" id="submit" name="submit" value="Send Email" onclick="send_mail();" />
An the php script
#error_reporting(E_ALL & ~E_NOTICE);
session_cache_limiter('nocache, must-revalidate');
session_start();
include_once '../../scripts/mysql.lib.php';
$mysql = new mysql(TRUE);
$serv = $mysql->fetch("SELECT * FROM server ;", FALSE);
$host = $serv['host'];
$limit = 100;
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers[] = 'From: My Address';
$headers[] = 'X-Priority: 5';
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-Type: text/html; charset="utf-8"' . "\r\n";
$hlist = implode("\r\n", $headers);
$result = 1;
$list = $mysql->fetch('SELECT COUNT(*) AS count FROM newsletter;', FALSE);
$count = $list['count'];
$emails = $mysql->fetch("SELECT email_id, email FROM newsletter WHERE status = 'none' LIMIT $limit;", TRUE);
if ($mysql->num_rows > 0) {
$sent = array();
$error = array();
foreach($emails as $email) {
$msg = $message . "\r\n<br /><br />" . '<small>If you wish to unregister from our newsletter list please click Here</small>';
if (#mail($email['email'], $subject, $msg, $hlist)) { $sent[] = $email['email_id']; }
else { $error[] = $email['email_id']; }
unset($msg);
}
$updsent = $mysql->query("UPDATE newsletter SET status = 'sent' WHERE email_id IN('" . implode("','",$sent) . "');");
$upderror = $mysql->query("UPDATE newsletter SET status = 'error' WHERE email_id IN('" . implode("','",$error) . "');");
switch(TRUE) {
case (count($error) == 0): $result = 3; break;
case (count($error) == $mysql->num_rows): $result = 4; break;
case (count($error) > 0): $result = 5; break;
}
}
if (($result == 1) && ($count > 0)) { $result = 2; }
switch($result) {
case 1: echo 'No Email Address in List - Message was not sent.'; break;
case 2: echo 'All User have received the Message'; break;
case 3: echo 'Message Sent!<br />(Cont. Sending ..)'; break;
case 4: echo 'Error - Message was not sent.'; break;
case 5: echo 'Message Sent to some User.<br />(Cont. Sending..)'; break;
}
?>
In the Html above the form there exist a div to grab results.
In short, after migrating the code to my project, nothing works what so ever. Nothing is sent, no result appear in the result div and my URL bar gets back the following:
newsletter-mail.php?subject=This is a title &message=<p>This is a test message<%2Fp>&submit=Send+Email
Any ideas will be appreciated.

Registration form email verification [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have a script which I have been following a tutorial - I wish to remove the email activation and ensure the users are activated once they hit sign up instead of the activation email being sent and verified?
Here is the script.
<?php
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
header("location: message.php?msg=NO to that weenis");
exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("includes/db_connex.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("includes/db_connex.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
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
$p_hash = md5 ($p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir('user/'.$u, 0755, True);
}
// Email the user their activation link
$to = "$e";
$from = "hello#iamdanbarrett.com";
$subject = 'yoursitename Account Activation';
$message = 'message here!'.$e.'</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();
}
?>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[" "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} 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+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
function openTerms(){
_("terms").style.display = "block";
emptyElement("status");
}
/* function addEvents(){
_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<div id="pageMiddle">
<h3>Sign Up Here</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("includes/template_country_list.php"); ?>
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Web Intersect Terms Of Use</h3>
<p>1. Play nice here.</p>
<p>2. Take a bath before you visit.</p>
<p>3. Brush your teeth before bed.</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
To be honest, you should really learn what is going on in the code instead of simply copying it out from a tutorial
The email activation occurs here
// Email the user their activation link
$to = "$e";
$from = "hello#iamdanbarrett.com";
$subject = 'yoursitename Account Activation';
$message = 'message here!'.$e.'</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";
so you can simply remove this, and instead of emailing them a verification, just change their status in the database to registered or however you distinguish between someone who hasn't activated their account and someone who has activated their account.
In order to achieve that you'll need to :
1 - learn PHP
2 - There's no 2, you'll just figure it out once you can read the code.

Categories