How to validate captcha in registration form? - php

I'm trying to create a registration form with a captcha, using this tutorial, but I don't know how to validate the captcha, can you help me?
<?php
include ('php/mysql_prisijungimas.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['name'])) {//if no name has been supplied
$error[] = 'Please Enter a name ';//add to array "error"
} else {
$name = $_POST['name'];//else assign it a variable
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
//regular expression for email validation
$Email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM members WHERE Email ='$Email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (md5($_POST['norobot']) == $_SESSION['randomnr2']) {
// here you place code to be executed if the captcha test passes
echo "Hey great , it appears you are not a robot";
} else {
// here you place code to be executed if the captcha test fails
echo "you're a very naughty robot!";
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
mail($Email, 'Registration Confirmation', $message, 'From: test#gmail.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for
registering! A confirmation email
has been sent to '.$Email.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email
address has already been registered.
</div>';
}
} else {//If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
?>
<head>
<meta charset="UTF-8">
<!-- Remove this line if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<meta name="description" content="test.">
<meta name="author" content="test">
<title>test</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/stilius.css">
</head>
<body>
<div class="container">
<hr>
<div class="home-page main">
<section class="grid-wrap" >
<header class="grid col-full">
<div class="right">
<form align="center" action="registracija.php" method="post" class="registration_form">
<fieldset>
<legend>Registracijos forma </legend>
<div class="elements">
<label for="name">Slapyvardis :</label>
<input type="text" id="name" name="name" size="25" />
</div>
<div class="elements">
<label for="e-mail">El. paštas :</label>
<input type="text" id="e-mail" name="e-mail" size="25" />
</div>
<div class="elements">
<label for="Password">slaptažodis:</label>
<input type="password" id="Password" name="Password" size="25" />
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>"
id="captchaimg" >
<label for="message">Enter the code above here :</label>
<input id="6_letters_code" name="6_letters_code" type="text">
</div>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Registruotis!" />
</div>
</fieldset>
</form>
</div>
</body>
</html>

Captcha is just any string created using image library.Process as below:
1- create random or dictionary word string
2- store it anywhere [session in your case before displaying your registration form
3- compare session value to user submit value
Your code :
if (md5($_POST['norobot']) == $_SESSION['randomnr2'])
{
echo 'You passed captcha test';
}
$_SESSION['randomnr2'] is random string created and stored in session.before storing it is md5 encrypted.

Related

issues with multiple forms on php page

i am trying to make a simple login system, with password recovery option,, so i made a password reset link.
hwoever, it is not working, meaning that form2's button just leads back to form1 (leads back to username and email form && i have three different forms), so i separated it into three different if statements, for each button clicked, but the same issue keeps on happening.
please tell me what is happening and ho to fix it
thank you.
(code is below)
//not actually js, but is php
session_start();
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
header("Location: changepass.php");
}
if(($_SERVER["REQUEST_METHOD"] == "POST")) {
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "test";
$con = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connection failed: %s\n". $con -> error);
$GLOBALS['email'] = $_POST['email'];
$GLOBALS['username'] = $_POST['username'];
$result = mysqli_query($con,"SELECT * FROM login WHERE email='" . htmlspecialchars($GLOBALS['email']) . "' and username = '". htmlspecialchars($GLOBALS['username'])."'");
$count = mysqli_num_rows($result);
//Part 1
if($_POST['submit1']) {
if($count==0) {
echo "<script>
document.getElementById('error').innerHTML += 'Invalid Username or Email.';
</script>";
} else {
echo "<script>
document.getElementById('main').style.display = 'none';
</script>";
echo "<script>
document.getElementById('next').style.display = 'inline-block';
</script>";
echo "<script>
document.getElementById('verify').innerHTML += 'A verification email has been sent to you. Copy the verification code and paste it above.';
</script>";
$GLOBALS['token'] = bin2hex(random_bytes(3));
echo $GLOBALS['token'];
$to = $GLOBALS['email'];
$subject = "Password Reset";
$msg = "Hello. Your token is <strong>" . $GLOBALS['token'] . "</strong>. <br>Good day.";
$msg = wordwrap($msg,70);
$headers = "From: email#example.com";
mail($to, $subject, $msg, $headers);
}
}
//Part 2
if($_POST['submit2']) {
if($_POST['code'] != $GLOBALS['token']) {
echo "<script>
document.getElementById('error2').innerHTML += 'Invalid verification code.';
</script>";
} else {
echo "<script>
document.getElementById('next').style.display = 'none';
</script>";
echo "<script>
document.getElementById('final').style.display = 'inline-block';
</script>";
}
}
//Part 3
if($_POST['submit3']) {
$np = $_POST['np'];
$cnp = $_POST['cnp'];
if($np != $cnp) {
echo "<script>
document.getElementById('error3').innerHTML += 'Passwords do not match.';
</script>";
} else {
$sql = "UPDATE login SET password='$cnp' WHERE email=" . $GLOBALS['email'];
$rs = mysqli_query($con, $sql);
if($rs) {
echo "Changed password successfully! Click <a href='login.php'>here</a> to sign in.";
} else {
echo "An unknown error occurred. Please try again.";
}
}
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reset Password</title>
</head>
<body>
<fieldset>
<legend>Reset Password</legend>
<form name="frmContact" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="main">
<label for="email">Email</label>
<input type="email" style="display:inline-block" name="email" id="email" required autofocus />
<br>
<br>
<label for="username">Username</label>
<input type="text" style="display:inline-block" name="username" id="username" required />
<br>
<p id="error" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit1" id="submit1" value="Reset Password" /> Create an Account Sign in
</p>
</div>
</form>
<form name="frmContact2" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="next" style="display:none;">
<p id="verify" style="color:green"></p>
<label for="code">Verification Code</label>
<input type="text" style="display:inline-block" maxlength="6" name="code" id="code" required autofocus /> <p style="color:red;display:inline-block" id="validatecode"></p>
<br>
<p id="error2" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit2" id="submit2" value="Reset Password" /> Create an Account Sign in
</p>
</div>
</form>
<form name="frmContact3" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="final" style="display:none;">
<label for="np">New Password</label>
<input type="text" style="display:inline-block" name="np" id="np" required autofocus /> <p style="color:red;display:inline-block" id="validatenp"></p>
<br>
<label for="cnp">Confirm New Password</label>
<input type="text" style="display:inline-block" name="cnp" id="cnp" required autofocus /> <p style="color:red;display:inline-block" id="validatecnp"></p>
<br>
<p id="error3" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit3" id="submit3" value="Reset Password" />
</p>
</div>
</form>
</fieldset>
</body>
</html>
Just for sake of debugging remove all extra stuff from that file and focus on 3 if statements
Also try using
if(isset($_POST['submit1']))
Always try to close in onto the problem at hand and remove extra stuff that is in there. It helps make simpler but better decisions.

PHP PDO Registration not working

I am having issues with the code below for site Sign-Up Page
I am trying to implement a login and registration system for students and staff on my university course. I have two tables in the DB, one for authorised users and then the other for registered users.
Before somebody can register, I have to enter either their student ID or email into the authorised table, otherwise it should tell the user that they are not authorised to register.
My problem is that when I register, I just get told that I am not authorised. The ID and email is in the authorised DB, so there is an issue with my code, and I cannot work it out.
Thanks in advanced.
I have this function for registering
public function register($firstname, $surname, $student_id, $email, $password) {
try {
$new_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO members(firstname, surname, student_id, email, password) VALUES(:fname, :sname, :sid, :smail, :spass)");
$stmt->bindparam(":fname", $firstname);
$stmt->bindparam(":sname", $surname);
$stmt->bindparam(":sid", $student_id);
$stmt->bindparam(":smail", $email);
$stmt->bindparam(":spass", $password);
$stmt->execute();
return $stmt;
} catch(PDOException $exception) {
echo $exception->getMessage();
}
}
And my registration page is as below.
<?php
require_once 'dbconfig.php';
if ($user->is_loggedin()!="") {
$user->redirect('home.php');
}
if (isset($_POST['btn-register'])) {
$fname = trim($_POST['fname']);
$sname = trim($_POST['sname']);
$student_id = trim($_POST['sid']);
$email = trim($_POST['smail']);
$password = trim($_POST['spass']);
$email_requirement = '#chester.ac.uk';
$email_verification = strpos($email, $email_requirement);
if ($fname == ""){
$error[] = "Please enter your firstname.";
} else if ($sname == "") {
$error[] = "Please enter your surname.";
} else if ($student_id == "") {
$error[] = "Please enter your Student ID.";
} else if ($email == "") {
$error[] = "Please enter your student email address.";
} else if ((!$email_verification) && (!filter_var($email, FILTER_VALIDATE_EMAIL))) {
$error[] = "Please enter a valid Chester Univeristy email address.";
} else if ($password == "") {
$error[] = "Please enter a password";
} else if (strlen($email) < 6 ) {
$error[] = "Passwords need to be at least 6 characters.";
} else {
try {
$check_exist = $DB_con->prepare("SELECT student_id, email FROM members WHERE student_id=:sid OR email=:smail");
$check_exist->execute(array(':sid'=>$student_id, ':smail'=>$email));
$row=$check_exist->fetch(PDO::FETCH_ASSOC);
if ($row['student_id'] == $student_id) {
$error[] = "That student ID has already been registered.";
} else if ($row['email'] == $email) {
$error[] = "That email address has already been registered.";
} else {
try {
$check_auth = $DB_con->prepare("SELECT student_id, email FROM authorised WHERE student_id=:sid OR email=:smail");
$check_auth->execute(array(':sid'=>$student_id, ':smail'=>$email));
$row2=$check_auth->fetch(PDO::FETCH_ASSOC);
if (($row2['student_id'] != $student_id) || ($row['email'] != $email)) {
$error[] = "You are not authorised to register. Please contact Richard - admin#cybersecurity.bloxamrose.co.uk.";
} else {
if ($user->register($fname, $sname, $student_id, $email, $password)) {
$user->redirect('sign-up.php?joined');
}
}
} catch (PDOException $exception) {
echo $exception->getMessage();
}
}
} catch (PDOException $exception) {
echo $exception->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>University of Chester (UNOFFICIAL) - Cybersecurity Notes</title>
<meta name="description" content="Student made resource for Cybersecurity students at the University of Chester. UNOFFICIAL." />
<meta name="author" content="Richard J Bloxam-Rose" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div class="form-container">
<form method="post">
<h2>Register</h2>
<hr />
<?php
if (isset($error)) {
foreach ($error as $error) {
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
} else if (isset($_GET['joined'])) {
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"> Registration complete Login here.
</div>
<?php
}
?>
<div class="form-group">
<input type="text" class="form-control" name="fname" placeholder="First Name" value="<?php if (isset($error)) {echo $fname;}?>" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="sname" placeholder="Surname" value="<?php if (isset($error)) {echo $sname;}?>" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="sid" placeholder="Student ID" value="<?php if (isset($error)) {echo $student_id;}?>" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="smail" placeholder="Student Email" value="<?php if (isset($error)) {echo $email;}?>" />
</div>
<div class="form-group">
<input type="password" class="form-control" name="spass" placeholder="Password" />
</div>
<div class="clearfix"></div>
<hr />
<div class="form-control">
<button type="submit" class="btn btn-block btn-primary" name="btn-register">
<i class="glyphicon glyphicon-open-file"></i> Register
</button>
</div>
<br />
<label>Already registered? Login</label>
</form>
</div>
</div>
</body>
</html>

Syntax Error, unexpected $end -- PHP error, what's wrong?

My entire error code is Parse error: syntax error, unexpected $end in /home/a3704125/public_html/home.php on line 356
Here is my entire PHP file.. Tell me what the problem may be? ._. Thanks!
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('GamesFXLogin');
// Starting the session
session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks
session_start();
if($_SESSION['id'] && !isset($_COOKIE['GamesFXRemember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the GamesFXRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: home.php?logout=true");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM gamesfx_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('GamesFXRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php?page=home&error=true");
exit;
}
else if($_POST['submit']=='Register')
{
// If the Register form has been submitted
$err = array();
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['username'] == '')
{
$err[] = 'User Name is required.';
}
if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
$err[]='Your username must be between 3 and 32 characters!';
}
if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
$err[]='Your username contains invalid characters!';
}
//whether the email is blank
if($_POST['email'] == '')
{
$err[]='E-mail is required.';
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$sql1 = "SELECT * FROM gamesfx_members WHERE email = '$email'";
$result1 = mysql_query($link,$sql1) or die(mysql_error());
if (mysql_num_rows($result1) > 0)
{
$err[]='This Email is already used.';
}
}
else
{
//this error will set if the email format is not correct
$err[]='Your email is not valid.';
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$err[]='Password is required.';
}
if(!count($err))
{
// If there are no errors
// Make sure the email address is available:
if(!count($err))
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$activation = md5(uniqid(rand()));
$encrypted=md5($password);
$sql2 = "INSERT INTO gamesfx_members (usr, email, pass, Activate) VALUES ('$username', '$email', '$encrypted', '$activation')";
$result2 = mysql_query($link,$sql2) or die(mysql_error());
if($result2)
{
$to = $email;
$subject = "Confirmation from GamesFX to $username";
$header = "GamesFX: Confirmation from GamesFX";
$message = "Please click the link below to verify and activate your account. rn";
$message .= "http://www.mysite.com/activate.php?key=$activation";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
}
exit();
}
}
$script = '';
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load
$script = '
<script type="text/javascript">
$(function(){
$("div#panel").show();
$("#toggle a").toggle();
});
</script>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A Cool Login System With PHP MySQL &amp jQuery | Tutorialzine demo</title>
<link rel="stylesheet" type="text/css" href="demo.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/slide.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<!-- PNG FIX for IE6 -->
<!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
<!--[if lte IE 6]>
<script type="text/javascript" src="js/pngfix/supersleight-min.js"></script>
<![endif]-->
<script src="js/slide.js" type="text/javascript"></script>
<?php echo $script; ?>
</head>
<body>
<!-- Panel -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<div class="left">
<h1>The Sliding jQuery Panel</h1>
<h2>A register/login solution</h2>
<p class="grey">You are free to use this login and registration system in you sites!</p>
<h2>A Big Thanks</h2>
<p class="grey">This tutorial was built on top of Web-Kreation's amazing sliding panel.</p>
</div>
<?php
if(!$_SESSION['id']):
?>
<div class="left">
<!-- Login Form -->
<form class="clearfix" action="" method="post">
<h1>Member Login</h1>
<?php
if($_SESSION['msg']['login-err'])
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> Remember me</label>
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>
</div>
<div class="left right">
<!-- Register Form -->
<form action="" method="post">
<h1>Not a member yet? Sign Up!</h1>
<?php
if($_SESSION['msg']['reg-err'])
{
echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
unset($_SESSION['msg']['reg-err']);
}
if($_SESSION['msg']['reg-success'])
{
echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
unset($_SESSION['msg']['reg-success']);
}
?>
<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="30" />
<label>A password will be e-mailed to you.</label>
<input type="submit" name="submit" value="Register" class="bt_register" />
</form>
</div>
<?php
else:
?>
<div class="left">
<h1>Members panel</h1>
<p>You can put member-only data here</p>
View your profile information and edit it
<p>- or -</p>
Log off
</div>
<div class="left right">
</div>
<?php
endif;
?>
</div>
</div> <!-- /login -->
<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Hello <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Guest';?>!</li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>
<a id="close" style="display: none;" class="close" href="#">Close Panel</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
</div> <!--panel -->
I am trying to use the slide panel that's a login panel.. Don't know if you ever heard of it. But anyhow, I am wondering how to fix this error. As-for I can't see what the problem may be.. I'm banging my head over it, thanks for the help!
EDIT: I added what's after the below this text..
<div class="pageContent">
<div id="main">
<div class="container">
<h1>A Cool Login System</h1>
<h2>Easy registration management with PHP & jQuery</h2>
</div>
<div class="container">
<p>This is a simple example site demonstrating the Cool Login System tutorial on <strong>Tutorialzine</strong>. You can start by clicking the <strong>Log In | Register</strong> button above. After registration, an email will be sent to you with your new password.</p>
<p>View a test page, only accessible by <strong>registered users</strong>.</p>
<p>The sliding jQuery panel, used in this example, was developed by Web-Kreation.</p>
<p>You are free to build upon this code and use it in your own sites.</p>
<div class="clear"></div>
</div>
<div class="container tutorial-info">
This is a tutorialzine demo. View the original tutorial, or download the source files. </div>
</div>
</div>
</body>
</html>
Closing brackets in here :
else if($_POST['submit']=='Register')
{
Put two closing brackets here:
$script = '';
}} #line 175
if($_SESSION['msg'])
Moral: always put opening and closing brackets together when going for any condition statement.

Registration form (validating email)

I have a project where I need to create registration form and insert it to the database.
I am currently stuck every time I tried to registered, it pop out a message saying "please enter a valid email format". Is it something to do regarding with the regex for the email?
Below is the code
<?php
require_once('sqlconnect.inc.php');
session_start();
if (isset($_POST["Register"]))
{
$email = $_POST['email'];
$memberName = $_POST['membername'];
$passw = $_POST['password'];
$conPassw = $_POST['conpassword'];
if($email=='')
{
echo "<p>Please enter the Email address</p>";
echo "Back to Registration Page!";
exit();
}
if($memberName=='')
{
echo "<p>Please enter the Member Name</p>";
echo "Back to Registration Page!";
exit();
}
if($passw=='')
{
echo "<p>Please enter Password</p>";
echo "Back to Registration Page!";
exit();
}
if($conPassw=='')
{
echo "<p>Please enter Confirm Password</p>";
echo "Back to Registration Page!";
exit();
}
else {
$email = $_POST['email'];
$pattern = '/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*#[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/';
if (preg_match($pattern, $email))
{
echo "<p>Please enter a valid email format<p>";
}
else{
$memberName = strtolower(trim($_POST['membername']));
$_SESSION['name'] = $_POST['membername'];
$pattern1 = '/^[a-z][a-z ]*$/i';
if (preg_match($pattern1, $memberName))
{
echo "<p>Member name must contain only letters, space and hypen</p>";
}
else{
$pattern2 = '^[a-zA-Z0-9]+$';
if (preg_match($pattern2, $passw))
{
echo "<p>Password must only contain numbers and letters!</p>";
}
else{
if($passw<>$conPassw)
{
echo "<p>Passwords does not match!</p>";
$passw="";
$conPassw="";
}
else{
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
if (!$conn)
die ("<p>Couldn't connect to the server!<p>");
$SelectDatabase = #mysqli_select_db($conn,"s7259476_db")
or die("<p>The database is not available.</p>");
$insertDatabase = "INSERT INTO team VALUES('NULL','$email','$password','$memberName',CURDATE(),0)";
$queryResult = #mysqli_query($conn, $insertDatabase)
or die ("<p>Email already exists.Please enter another email id</p>");
echo"<p>Data entered into friends table successfully</p>";
echo "<p>Welcome"." ".$_SESSION['name']."</p>";
}
}
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/chtml-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Web Programming :: Assignment 2" />
<meta name="Keywords" content="Web, programming" />
<title>Register Page</title>
</head>
<body>
<form id='register' action='signup.php' method='POST'>
<fieldset >
<legend><h1>My Team System Registration Page</h1></legend>
<?php $email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_STRING) : ''; ?>
<?php $memberName = isset($_POST['membername']) ? filter_var($_POST['membername'], FILTER_SANITIZE_STRING) : ''; ?>
<div class="elements">
<label for='email' >Email:</label>
<input type='text' name='email' id='email' maxlength="50" value="<?php echo $email; ?>" />
</div>
<br />
<div class="elements">
<label for='membername' >Member Name:</label>
<input type='text' name='membername' id='membername' maxlength="50" value="<?php echo $memberName; ?>" />
</div>
<br />
<div class="elements">
<label for='password' >Password:</label>
<input type='password' name='password' id='password' maxlength="50" />
</div>
<br />
<div class="elements">
<label for='conpassword' >Confirm Password:</label>
<input type='password' name='conpassword' id='conpassword' maxlength="50" />
</div>
<br />
<div class="submit">
<input type='submit' name='Register' value='Register' />
<input type='reset' name='Submit' value='Clear' />
<br />
<div class="elements">
Home
</fieldset>
</form>
</body>
</html>
Don't use a regex to validate an email address. PHP has filter_var for that, which is quick and easy to use. Email addresses are notoriously painful to validate properly with a regex (there is a regex that validates them properly somewhere, and it is HUGE!).
Some typical code for validating an email address with filter_var might look like this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "Invalid email address";
}

Photo uploading PHP undefined index. Insert photo into sql database

I'm working right now with a registration form that allows photo uploading for a profile picture. When attempting to submit everything works successfully except the errors given by the picture index.
I highly believe it has to do with running the php within the form as the picture isn't uploaded to the variable before submitting but I can't get past it.
Notice: Undefined index: photo in /var/www/registeraccount.php on line 54
Notice: Undefined index: photo in /var/www/registeraccount.php on line 57
<?php
error_reporting(E_ALL);
ini_set('display_errors',"On");
include ('database_connection.php');
$target = "/var/www/profile";
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['name'])) {//if no name has been supplied
$error[] = 'Please Enter a name ';//add to array "error"
} else {
$name = $_POST['name'];//else assign it a variable
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
//regular expression for email validation
$Email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM account WHERE email ='$Email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$target = $target . basename($_FILES['photo']['name']);
//This gets all the other information from the form
$pic=($_FILES['photo']['name']);
$query_insert_user = "INSERT INTO `account` ( `username`, `passwords`, `email`, `picture`) VALUES ( '$name', '$Password', '$Email ' , '$pic')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
mail($Email, 'Registration Confirmation', $message, 'From: systemadminstrator#theanimator.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for
registering! A confirmation email
has been sent to '.$Email.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email
address has already been registered.
</div>';
}
} else {//If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration Form</title>
<style type="text/css">
//CSS Once again removed because it has nothing to do with the issue.
</style>
</head>
<body>
<form action="registeraccount.php" method="post" class="registration_form" enctype="multipart/form-data">
<fieldset>
<legend>Registration Form </legend>
<h2 style="text-align:center">Create an account!</h2>
<p style="text-align:center"> <span>Already a member? Log in</span> </p>
<div class="elements">
<label for="name">Name :</label>
<input type="text" id="name" name="name" size="25" />
</div>
<div class="elements">
<label for="e-mail">E-mail :</label>
<input type="text" id="e-mail" name="e-mail" size="25" />
</div>
<div class="elements">
<label for="Password">Password:</label>
<input type="password" id="Password" name="Password" size="25" />
<p>
Photo:
</p>
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
<p>
</div>
<br />
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Register" />
</div>
</fieldset>
</form>
<button onclick="window.location='theanimator.html';">Go Back!</button>
</body>
</html>
it's a simple matter of adding a condition to check if a photo is uploaded
if(!isset($_FILES['photo'])) {
$error[] = "No photo selected !";
}

Categories