PHP login/register problems

Hello!

I’m coding my first php website right now and I have some problems… one of them is my login/register system
I can register a user but the user can’t activate his account (send email using php mail() work, but the link in the email won’t work) and he can’t log in, change password or anything…
The mail() function work on my server so I know that it works even if I’m running localhost right now (for testing)

Here is the register.php:

[php]

<?php include 'func/init.php'; logged_in_redirect(); include 'template/overall/header.php'; ?>

Register New Account

<?php if (empty($_POST) === false) { $required_fields = array('username', 'password', 'password_again', 'email'); foreach($_POST as $key=>$value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'Fields marked with an asterisk are required'; break 1; } } if (empty($errors) === true) { if (user_exists($_POST['username']) === true) { $errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken.'; } if (preg_match("/\\s/", $_POST['username']) == true) { $errors[] = 'Your username can\'t contain any spaces'; } if (strlen($_POST['username']) > 200) { $errors[] = 'Your username must be less then 200 characters'; } if (strlen($_POST['password']) < 6) { $errors[] = 'Your password must be at least 10 characters'; } if (strlen($_POST['password']) > 200) { $errors[] = 'Your password must be less then 200 characters'; } if ($_POST['password'] !== $_POST['password_again']) { $errors[] = 'Your passwords do not match'; } if (strlen($_POST['first_name']) > 200) { $errors[] = 'Your first name must be less then 200 characters'; } if (strlen($_POST['last_name']) > 200) { $errors[] = 'Your last name must be less then 200 characters'; } if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = 'A valid email address is required'; } if (email_exists($_POST['email']) === true) { $errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use.'; } } } ?>

<?php if (isset($_GET['success']) === true && empty($_GET['success']) === true) { echo 'Thank you for signing up on my website! You\'ve got a link on the email you entered, click on it to complete your registration.'; } else { if (empty($_POST) === false && empty($errors) === true) { $register_data = array( 'username' => $_POST['username'], 'password' => $_POST['password'], 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'email' => $_POST['email'], 'email_code' => md5($_POST['username'] + microtime()) );

	register_user($register_data);
	header('Location: register.php?success');
	exit();

} else if (empty($errors) === false){
	echo output_errors($errors);
}

?>

Username*
e.g. John-Smith or JaneDoe
	<div class="row">
    <div class="label">Password*</div> <!-- end .label -->
    <div class="input">
    <input type="password" id="password" class="detail" name="password">
    </div> <!-- end .input -->
    <div class="context">This should be something safe that only you know about, feel free to use numbers, uppercase and lowercase letters </div> <!-- end .context -->
    </div> <!-- end .row -->
		
	<div class="row">
    <div class="label">Confirm password*</div> <!-- end .label -->
    <div class="input">
    <input type="password" id="password" class="detail" name="password_again">
    </div> <!-- end .input -->
    <div class="context">This should be something safe that only you know about, feel free to use numbers, uppercase and lowercase letters </div> <!-- end .context -->
    </div> <!-- end .row -->
		
	<div class="row">
    <div class="label">First name</div> <!-- end .label -->
    <div class="input">
    <input type="text" id="first_name" class="detail" name="first_name" value="<?php echo isset($_POST['first_name'])? $_POST['first_name'] : ''; ?>" />
    </div> <!-- end .input -->
    <div class="context">e.g. John or Jane</div> <!-- end .context -->
    </div> <!-- end .row -->
		
	<div class="row">
    <div class="label">Last name</div> <!-- end .label -->
    <div class="input">
    <input type="text" id="last_name" class="detail" name="last_name" value="<?php echo isset($_POST['last_name'])? $_POST['last_name'] : ''; ?>" />
    </div> <!-- end .input -->
    <div class="context">e.g. Smith or Doe</div> <!-- end .context -->
    </div> <!-- end .row -->
		
	<div class="row">
    <div class="label">Your email address*</div> <!-- end .label -->
    <div class="input">
    <input type="email" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
    </div> <!-- end .input -->
    <div class="context">We will not share your email with anyone or spam you with messages either</div> <!-- end .context -->
    </div> <!-- end .row -->

	<div class="submit">
	<input type="submit" id="submit" name="submit" value="Register" />
	</div> <!-- end .submit-->
</form>
<?php } include 'template/overall/footer.php'; ?>

[/php]

and users.func.php:

[php]

<?php function change_profile_image($user_id, $file_temp, $file_extn) { $file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn; move_uploaded_file($file_temp, $file_path); mysql_query("UPDATE `users` SET `profile` = '" . mysql_real_escape_string($file_path) . "' WHERE `user_id` = " . (int)$user_id); } function mail_users($subject, $body) { $query = mysql_query("SELECT `email`, `username` FROM `users` WHERE `allow_email` = 1"); while (($row = mysql_fetch_assoc($query)) !== false) { email($row['email'], $subject, "Hello " . $row['username'] . ",\n\n" . $body); } } function has_access($user_id, $type) { $user_id = (int)$user_id; $type = (int)$type; return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_id` = $user_id AND `type` = $type"), 0) == 1) ? true : false; } function recover($mode, $email) { $mode = sanitize($mode); $email = sanitize($email); $user_data = user_data(user_id_from_email($email), 'user_id', 'username'); if ($mode == 'username') { email($email, 'Your username', "Hello!\n\nYour username is: " . $user_data['username'] . "\n\n- Busarna4"); } else if ($mode == 'password') { $salt = hash('sha512', uniqid(mt_rand(), true), microtime() . 'newpasswd'); $hash = $salt . $password; for ( $i = 0; $i < 100000; $i ++ ) { $hash = hash('sha512', $hash); } $hash = $salt . $hash; } $generated_password = $hash; change_password($user_data['user_id'], $generated_password); update_user($user_data['user_id'], array('password_recover' => '1')); email($email, 'Your password recovery', "Hello " . $user_data['username'] . "\n\nYour new password is: " . $password . "\n\n- Busarna4"); } function update_user($user_id, $update_data) { $update = array(); array_walk($update_data, 'array_sanitize'); foreach($update_data as $field=>$data) { $update[] = '`' . $field . '` = \'' . $data . '\''; } mysql_query("UPDATE `users` SET " . implode(', ', $update) . " WHERE `user_id`= $user_id"); } function activate($email, $email_code) { $email = mysql_real_escape_string($email); $email_code = mysql_real_escape_string($email_code); if (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0"), 0) == 1) { mysql_query("UPDATE `users` SET `active` = 1 WHERE `email` = '$email'"); return true; } else { return false; } } function change_password($user_id, $password) { $user_id = (int)$user_id; $password = md5($password); mysql_query("UPDATE `users` SET `password` = '$password', `password_recover` =0 WHERE `user_id` = $user_id"); } function register_user($register_data) { if(isset($_POST['password'])) { $password = $_POST['password']; $salt = hash('sha512', uniqid(mt_rand(), true), microtime() . 'newpasswd'); $hash = $salt . $password; for ( $i = 0; $i < 100000; $i ++ ) { $hash = hash('sha512', $hash); } $hash = $salt . $hash; } $register_data['password'] = $hash; $fields = '`' . implode('`,`', array_keys($register_data)) . '`'; $data = '\'' . implode('\', \'', $register_data) . '\''; mysql_query("INSERT INTO `users` ($fields) VALUES ($data)"); email($register_data['email'], 'Activate your account', "Hello " . $register_data['username'] . ",\n\n You need to activate your account, use the link below to do that:\n\n http://localhost/busarna4-register/activate.php?email=" . $register_data['email'] . "&email_code=" . $register_data['email_code'] . " \n\n- Busarna4"); } function user_count() { return mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0); } function user_data($user_id) { $data = array(); $user_id = (int)$user_id; $func_num_args = func_num_args(); $func_get_args = func_get_args(); if ($func_num_args > 1) { unset($func_get_args[0]); $fields ='`' . implode('`, `', $func_get_args) . '`'; $data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id")); return $data; } } function logged_in() { return (isset($_SESSION['user_id'])) ? true : false; } function user_exists($username) { $username = sanitize($username); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"), 0) == 1) ? true : false; } function email_exists($email) { $email = sanitize($email); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false; } function user_active($username) { $username = sanitize($username); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `active` = 1"), 0) == 1) ? true : false; } function user_id_from_username($username) { $username = sanitize($username); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id'); } function user_id_from_email($email) { $email = sanitize($email); return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `email` = '$email'"), 0, 'user_id'); } function login($username, $password) { $user_id = user_id_from_username($username); $username = sanitize($username); $password = md5($password); return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false; } ?>

[/php]

and here’s my login.php:

[php]

<?php include 'func/init.php'; logged_in_redirect(); if (empty($_POST) === false) { $username = $_POST['username']; $password = $_POST['password']; if (empty($username) === true || empty($password) === true) { $errors[] = 'You need to enter a username and password'; } else if (user_exists($username) === false) { $errors[] = 'We can\'t find that username. Have you registered?'; } else if (user_active($username) === false) { $errors[] = 'You haven\'t activated your account!'; } else { if (strlen($password) > 200) { $errors[] = 'Password too long'; } $login = login($username, $password); if($login === false) { $errors[] = 'That username/password combination is incorrect'; } else { $_SESSION['user_id'] = $login; header('Location: index.php'); exit(); } } } else { $errors[] = 'No data received'; } include 'template/overall/header.php'; if (empty($errors) === false) { ?>
<link rel="stylesheet" href="css/style.css">
<h2>We tried to log you in, but...</h2>
<?php echo output_errors($errors); } include 'template/overall/footer.php'; ?>

[/php]

and changepassword.php:

[php]

<?php include 'func/init.php'; protect_page(); if (empty($_POST) === false) { $required_fields = array('current_password', 'password', 'password_again'); foreach($_POST as $key=>$value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'Fields marked with an asterisk are required'; break 1; } } if (md5($_POST['current_password']) === $user_data['password']) { if (trim($_POST['password']) !== trim($_POST['password_again'])) { $errors[] = 'Your new passwords do not match'; } else if(strlen($_POST['password']) < 6) { $errors[] = 'Your password must be at least 6 characters'; } } else { $errors[] = 'Your current password is incorrect'; } } include 'template/overall/header.php'; ?>

Change Password

<?php if (isset($_GET['success']) === true && empty($_GET['success']) === true) { echo 'Your password has been changed.'; } else { if (isset($_GET['force']) === true && empty($_GET['force']) === true) { ?>
	<p>You must change your password</p>
<?php
}

if (empty($_POST) === false && empty($errors) === true) {
	change_password($session_user_id, $_POST['password']);
	header('Location: changepassword.php?success');
} else if (empty($errors) === false) {
	echo output_errors($errors);
}

?>

<form action="" method="post">
	<ul id="changepassword">
		<li>
			Current password*:<br>
			<input type="password" name="current_password">
		</li>
		<li>
			New password*:<br>
			<input type="password" name="password">
		</li>
		<li>
			New password again*:<br>
			<input type="password" name="password_again">
		</li>
		<li>
			<div class="submit">
            <input type="submit" id="submit" name="submit" value="Change Password" />
            </div> <!-- end .submit -->
		</li>
	</ul>
</form>
<?php } include 'template/overall/footer.php'; ?>

[/php]

and activate.php

[php]

<?php include 'func/init.php'; logged_in_redirect(); include 'template/overall/header.php'; if (isset($_GET['success']) === true && empty($_GET['success']) === true) { ?>
<link rel="stylesheet" href="css/style.css">
<h2>Thanks, we've activated your account...</h2>
<p>You're free to log in!</p>
<?php } else if (isset($_GET['email'], $_GET['email_code']) === true) { $email = trim($_GET['email']); $email_code = trim($_GET['email_code']); if (email_exists($email) === false) { $errors[] = 'Oops, something went wrong, and we couldn\'t find that email address!'; } else if (activate($email, $email_code) === false) { $errors[] = 'We had problems activating your account'; } if (empty($errors) === false) { ?>
	<h2>Oops...</h2>
<?php
	echo output_errors($errors);
} else {
	header('Location: activate.php?success');
	exit();
}

} else {
header(‘Location: index.php’);
exit();
}

include ‘template/overall/footer.php’;
?>
[/php]

If you guys need anything else just tell me.

Does anyone know there the problem/problems are?
Thanks in advance//Busarna4

I would be nice to include .sql file too, I mean the database structure, how tables are defined etc.

This one?

-- phpMyAdmin SQL Dump
-- version 3.5.2.2
-- http://www.phpmyadmin.net
--
-- Värd: 127.0.0.1
-- Skapad: 20 aug 2013 kl 15:20
-- Serverversion: 5.5.27
-- PHP-version: 5.4.7

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Databas: `pswtest`
--

-- --------------------------------------------------------

--
-- Tabellstruktur `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `first_name` varchar(200) NOT NULL,
  `last_name` varchar(200) NOT NULL,
  `email` varchar(1024) NOT NULL,
  `email_code` varchar(32) NOT NULL,
  `active` int(11) NOT NULL DEFAULT '0',
  `password_recover` int(11) NOT NULL DEFAULT '0',
  `type` int(1) NOT NULL DEFAULT '0',
  `allow_email` int(11) NOT NULL DEFAULT '1',
  `profile` varchar(55) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumpning av Data i tabell `users`
--

INSERT INTO `users` (`user_id`, `username`, `password`, `first_name`, `last_name`, `email`, `email_code`, `active`, `password_recover`, `type`, `allow_email`, `profile`) VALUES
(4, 'Busarna4', 'ÀÞE™Ö\ZòÃȝ3ÝŽcnkutÇ~žB#$i õÐôΝ”–U5)Ýiz³!‹9èS-ú¦Þ]{9]Bü41460ec09efd6e57f3f7bce8d6968618e7d8ce41517322c78f1a5106ce68ba3614e62fb298aba0c0c1d951d10b73954723cf63f1a6465a91c3164b57ea49cd1d', '', '', '[email protected]', '130ca79168dbfe205aa00c3a57181837', 1, 0, 0, 1, '');

/*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
/*!40101 SET [email protected]_COLLATION_CONNECTION */;

And btw thanks for the fast answer

And another thing is that everything worked just fine until I upgraded from md5 to the new hashing system (the new one is in the included file)

Yeah this will do the work, is there any other table besides this one??

I will examine the code and will tell you about the problems (if I find any :wink: )

No there are no other tables yet. I will add more but I decided to wait until this is solved.

And thanks for trying to help me out :slight_smile:

If you have time, can you see if there is something different to get a more secure website to? :slight_smile:
(This is not needed but since I’m kind of new to php I would love all the help I can get, and I’m self-learned)

Thanks in advance //Busarna4

I can do different*

Ok. I will try my best to see what I can do for you because I’m also new to PHP.

One more thing is there anything special in the

include ‘func/init.php’;
include ‘template/overall/header.php’;

files that would break the code??? or is there any file needed to make the code work???

I’ve just started reading the code :stuck_out_tongue:

Here’s the func/init.php:

<?php
// Start headers and sessions
ob_start();
session_start();

// MySQL Connection
mysql_connect('localhost', 'root', '');
mysql_select_db('pswtest');
//error_reporting(0);

// Include func files
require 'func/general.func.php';
require 'func/users.func.php';

$current_file = explode('/', $_SERVER['SCRIPT_NAME']);
$current_file = end($current_file);

if (logged_in() === true) {
	$session_user_id = $_SESSION['user_id'];
	$user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'password_recover', 'type', 'allow_email', 'profile');
	if (user_active($user_data['username']) === false) {
		session_destroy();
		header('Location: index.php');
		exit();
	}
	if ($current_file !== 'changepassword.php' && $current_file !== 'logout.php' && $user_data['password_recover'] == 1) {
		header('Location: changepassword.php?force');
		exit();
	}
}
	
$errors = array();

?>

and here’s template/overall/header.php:

<header>
<head>
<link rel="stylesheet" href="css/screen.css">
</head>
<body>
<div class="wrapper">

      <div id="slider">
        <img id="1" src="images/header1.png">
        <img id="2" src="images/header2.png">
	    <img id="3" src="images/header3.png">
	    <img id="4" src="images/header4.png">
      </div>
  
      <a href="#" class="left" onclick="prev(); return false;">Previous</a>
      <a href="#" class="right" onclick="next(); return false;">Next</a>

    </div>
</div>
</body>
<head>
<link rel="stylesheet" href="css/screen.css">
</head>
<body>
  <script src="js/jquery.js"></script>
  <script src="js/javascript.js"></script>
</body>
<div class="clear"></div>
</header>

You need this .htaccess file to get the dynamic profile page to work:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /busarna4-register/profile.php?username=$1

Thanks in advace

I forgot some files… here they come:

  1. loggedin.php:

[php]

1



Hello, <?php echo $user_data['username']?>!




<?php
if (isset($_FILES[‘profile’]) === true) {
if (empty($_FILES[‘profile’][‘name’]) === true) {
echo ‘Please choose a file!’;
} else {
$allowed = array(‘jpg’, ‘jpeg’, ‘gif’, ‘png’);
				$file_name = $_FILES['profile']['name'];
				$file_extn = strtolower(end(explode('.', $file_name)));
				$file_temp = $_FILES['profile']['tmp_name'];
				
				if (in_array($file_extn, $allowed) === true) {
					change_profile_image($session_user_id, $file_temp, $file_extn);
					header('Location: ' . $current_file);
					exit();
				} else {
					echo 'Incorrect file type. Allowed: ';
					echo implode(', ', $allowed);
				}
			}
		}
		
		if (empty($user_data['profile']) === false) {
			echo '<img src="', $user_data['profile'], '" alt"', $user_data['username'], '\'s Profile Image">';
		}
		?>
		<form action="" method="post" enctype="multipart/form-data">
			<input type="file" name="profile"> <input type="submit">
		</form>
	</div>
	<ul>
		<li>
			<a href="logout.php">Log out</a>
		</li>
		<li>
			<a href="<?php echo $user_data['username']; ?>">Profile</a>
		</li>
		<li>
			<a href="changepassword.php">Change password</a>
		</li>
		<li>
			<a href="settings.php">Settings</a>
		</li>
	</ul>
</div>
[/php]
  1. login.php:
<div class="widget">
    <link rel="stylesheet" href="css/style.css">
    <h2>Log in/Register</h2>
    <div class="inner">
        <form action="login.php" method="post">
			<ul id="login">
				<li>
				    <p>Username:<br></p>
				    <input type="text" name="username">
				</li>
				<li>
					<p>Password:<br></p>
					<input type="password" name="password"
				</li>
				<li>
					<div class="submit">
                    <input type="submit" id="submit" name="submit" value="Log In" />
                    </div> <!-- end .submit -->
				</li>
				<li>
				    <a href="register.php">Register</a>
				</li>
				<li>
					<p>Forgotten your <a href="recover.php?mode=username">username</a> or <br /> <br /> <a href="recover.php?mode=password">password</a>?</p>
				</li>
			</ul>
		</form>
    </div>
</div>
  1. user_count.php:

[php]

Users

<?php $user_count = user_count(); $suffix =($user_count != 1) ? 's' : ''; ?>

We current have <?php echo $user_count; ?> registered user<?php echo $suffix; ?>.

[/php]
  1. general.func.php:

[php]

<?php function email($to, $subject, $body) { mail($to, $subject, $body, 'From: [email protected]'); } function logged_in_redirect() { if (logged_in() === true) { header('Location: index.php'); exit(); } } function protect_page() { if (logged_in() === false) { header('Location: protected.php'); exit(); } } function admin_protect() { global $user_data; if (has_access($user_data['user_id'], 1) === false) { header('Location: index.php'); exit(); } } function array_sanitize(&$item) { $item = htmlentities(strip_tags(mysql_real_escape_string($item))); } function sanitize($data) { return htmlentities(strip_tags(mysql_real_escape_string($data))); } function output_errors($errors) { return '
  • ' . implode('
  • ', $errors) . '
'; } ?>

[/php]

  1. logout.php:

[php]

<?php session_start(); session_destroy(); header('Location: index.php'); ?>

[/php]

  1. recover.php:

[php]

<?php include 'func/init.php'; logged_in_redirect(); include 'template/overall/header.php'; ?>

Recover

<?php if (isset($_GET['success']) === true && empty($_GET['success']) === true) { ?>

Thanks, we've emailed you.

<?php } else { $mode_allowed = array('username', 'password'); if (isset($_GET['mode']) === true && in_array($_GET['mode'], $mode_allowed) === true) { if (isset($_POST['email']) === true && empty($_POST['email']) === false) { if (email_exists($_POST['email']) === true) { recover($_GET['mode'], $_POST['email']); header('Location: recover.php?success'); exit(); } else { echo '

Oops, we couldn\'t find that email address!

'; } } ?>
	<form action="" method="post">
		<ul id="recover">
			<li>
				Please enter your email address:<br>
				<input type="email" name="email">
			</li>
			<li>
			<div class="submit">
            <input type="submit" id="submit" name="submit" value="Send Message" />
            </div> <!-- end .submit --></li>
		</ul>
	</form>

<?php
} else {
	header('Location: index.php');
	exit();
}

}
?>

<?php include 'template/overall/footer.php'; ?>

[/php]

And finally settings.php:

[php]

<?php include 'func/init.php'; protect_page(); include 'template/overall/header.php'; if (empty($_POST) === false) { $required_fields = array('email'); foreach($_POST as $key=>$value) { if (empty($value) && in_array($key, $required_fields) === true) { $errors[] = 'Fields marked with an asterisk are required'; break 1; } } if (empty($errors) === true) { if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) { $errors[] = 'A valid email address is required'; } else if (email_exists($_POST['email']) === true && $user_data['email'] !== $_POST['email']) { $errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use.'; } } } ?>

Settings

<?php if (isset($_GET['success']) === true && empty($_GET['success']) === true) { echo 'Your details have been updated!'; } else { if (empty($_POST) === false && empty($errors) === true) { $update_data = array( 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'email' => $_POST['email'], 'allow_email' => ($_POST['allow_email'] == 'on') ? 1 : 0 ); update_user($session_user_id, $update_data); header('Location: settings.php?success'); exit(); } else if (empty($errors) === false) { echo output_errors($errors); } ?>
<form action="" method="post">
	<ul id="settings">
		<li>
			First name:<br>
			<input type="text" name="first_name" value="<?php echo $user_data['first_name']?>">
		</li>
		<li>
			Last name:<br>
			<input type="text" name="last_name" value="<?php echo $user_data['last_name']; ?>">
		</li>
		<li>
			Email*:<br>
			<input type="text" name="email" value="<?php echo $user_data['email']; ?>">
		</li>
		<li>
			<input type="checkbox" name="allow_email" <?php if ($user_data['allow_email'] == 1) { echo 'checked="checked"'; }?>> Would you like to receive email from us?
		</li>
		<li>
			<div class="submit">
            <input type="submit" id="submit" name="submit" value="Update" />
            </div> <!-- end .submit -->
		</li>
	</ul>
</form>
<?php } include 'template/overall/footer.php'; ?>

[/php]

I’m not shure if u need them all but I thought that I could include them so you have everything :slight_smile:

Well I’ve studied some of scripts, You certainly know what you want to do, but it’s kind of repetitive but programmer has his own style 8)

As I told you earlier I am also new to PHP and I haven’t used some of the functions you used in your code. Therefore, I’ve revamped the code to make a bit more sense (at least to me). Now users can register and create an account on the site and they will also have to verify their account to use the site. I haven’t touched on other things. I wanted to share the code with you to get an opinion and let me know if you want me to continue or not. ;D

register.php
[php]<?php
ob_start();
require_once(‘functions.php’);
session_start();

?>

<?php /* This 'IF' confirm all fields are full otherwise the 'ELSE' will run */ if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['password_again']) && !empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['email']) && isset($_POST['submit']) ){
			$conn = db_connect();


			// Storing POST's Keys variables in the $array_key
			$array_key = array_keys($_POST);

			/*Calling the field_length function to check whether user entered required amount of characters in the field or not */
			$username = field_length($conn, 
										ucfirst($array_key[0]), 
										$_POST['username']
									);

			if (preg_match ("/\\s/", $_POST['username']) == FALSE){
					
					if(is_null($username)){
						
						$username = $_POST['username'];
					}

			} else {

					$username .= " You can't use spaces in the username";
			}

			$first_name = field_length(	$conn, 
										ucwords(str_replace("_", " ", $array_key[3])), 
										$_POST['first_name']
									);

			$last_name = field_length(	$conn, 
										ucwords(str_replace("_", " ", $array_key[4])), 
										$_POST['last_name']
									);
		/* If email validation was unsuccessful 'NULL' will be assigned to $email */
			if (!filter_var($_POST['email'], 
				FILTER_VALIDATE_EMAIL)) {
				$email = "Email not valid, Please try again";
			} else { $email = $_POST['email']; }

			/* If password are not same 'NULL' will be assigned to $password */

			if ( strlen($_POST['password']) < 6 ||
					 strlen($_POST['password']) > 200
				){
					$password = " Password should be between 6 to 200 characters ";
			}

			if ( $_POST['password'] !== $_POST['password_again']){
				
				if(isset($password)){
				$password .= " and Passwords are not same! Please try again.";
				} else {$password = "Passwords are not same! Please try again.";}

			} else { $password = $_POST['password'];}
				


	/*Once we have all the values according to our need now it’s time to sanitize it and add it to the database */
	if ( $username == $_POST['username'] &&
		 is_null($first_name) &&
		 is_null($last_name) &&
		 $email == $_POST['email'] &&
		 $password == $_POST['password']
		){

			$username = safe_out($conn, $username);
			/* If NULL is not returned from the following query, an error will be shown to the user "username already exisit" 
			 */
			$username = query_user_check($conn, $username);

			$email = safe_out($conn, $email);
			
			/* If NULL is not returned from the following query, an error will be shown to the user "Email already exisit" 
			 */
			$email = query_email_check($conn, $email);

			if (is_null($username) && is_null($email)){
			
				/* Stripping out unwanted stuff */
				$user = safe_out($conn, $_POST['username']);
				$pass = safe_out($conn, $_POST['password']);
				$pass_hash = secure_password($password);
				$f_name = safe_out($conn, $_POST['first_name']);
				$l_name = safe_out($conn, $_POST['last_name']);
				$email = safe_out($conn, $_POST['email']);
				$vericode = substr(md5($user + microtime()), 1, 10);

				/* Inserting Record in the DB, If successfull a SESSION['username'] will be retruned back. */

				
				
				$result = query_insert_user($conn, $user, 
											$pass_hash, $f_name, 
											$l_name, 
											$email, $vericode);

				

				if(is_array($result)){

					$_SESSION['username'] = $result['username'];
					$_SESSION['email'] = $result['email'];
					$_SESSION['vericode'] = $result['vericode'];

					header("Location: verify.php");

		}
	}
}

}

	/* If any of the field is left blank in the FORM then the following Block will run. */

?>
Register An Account

<?php
if (isset($status))
	{ echo $status . "<br />" ; }
if ( isset($username) && $username != $_POST['username'])
	{echo $username . "<br />";} 
if(isset($password) && $password != $_POST['password'])
	{echo $password . "<br />";}
if(isset($first_name) && !is_null($first_name))
	{echo $first_name . "<br />";}
if(isset($last_name) && !is_null($last_name))
	{echo $last_name . "<br />";}
if(isset($email) && $email != $_POST['email'])
	{echo $email . "<br />";}

?>

Register New Account

<div class="row">
    <div class="label">
    	<label for="username"> Username*</label>
    </div> <!-- end .label -->

    <div class="input">
    	<input type="text" id="username" class="detail" name="username" value="<?php echo isset($_POST['username'])? $_POST['username'] : ''; ?>" />
    </div> <!-- end .input -->

    <div class="context">
    	e.g. John-Smith or JaneDoe
    </div>
    <!-- end .context -->
</div> <!-- end .row -->

<br />
<div class="row">
    <div class="label">
    	<label for="password">Password*</label>
    </div> <!-- end .label -->

    <div class="input">
        <input type="password" id="password" class="detail" name="password">
    </div> <!-- end .input -->

    <div class="context">
    	This should be something safe that only you know about, feel free to use numbers, uppercase and lowercase letters
    </div> <!-- end .context -->
</div> <!-- end .row -->

<br />
<div class="row">
	<div class="label">
		<label for="password_again">Confirm password*</label>
	</div> <!-- end .label -->

    <div class="input">
    	<input type="password" id="password_again" class="detail" name="password_again">
    </div> <!-- end .input -->

    <div class="context">
    	This should be something safe that only you know about, feel free to use numbers, uppercase and lowercase letters 
    </div> <!-- end .context -->
</div> <!-- end .row -->

<br />
<div class="row">
	<div class="label">
		<label for="first_name">First name</label>
	</div> <!-- end .label -->

	<div class="input">
        <input type="text" id="first_name" class="detail" name="first_name" value="<?php echo isset($_POST['first_name'])? $_POST['first_name'] : ''; ?>" />
    </div> <!-- end .input -->

    <div class="context">
    	e.g. John or Jane
    </div> <!-- end .context -->
</div> <!-- end .row -->

<br />
<div class="row">
	<div class="label">
		<label for="last_name">Last name</label>
	</div> <!-- end .label -->

	<div class="input">
        <input type="text" id="last_name" class="detail" name="last_name" value="<?php echo isset($_POST['last_name'])? $_POST['last_name'] : ''; ?>" />
    </div> <!-- end .input -->

    <div class="context">
    	e.g. Smith or Doe
    </div> <!-- end .context -->
</div> <!-- end .row -->

<br />
<div class="row">
    <div class="label">
    	<label for="email">Your email address*</label>
    </div> <!-- end .label -->

    <div class="input">
    	<input type="email" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
    </div> <!-- end .input -->

    <div class="context">
    We will not share your email with anyone or spam you with messages either
    </div> <!-- end .context -->
 </div> <!-- end .row -->

<div class="submit">
	<input type="submit" id="submit" name="submit" value="Register" />
</div> <!-- end .submit-->
<?php if (isset($conn)){
        mysqli_close($conn); 

      }

?>

<?php ob_end_flush(); ?>[/php]

functions.php
[php]<?php

function db_connect(){

$host = 'localhost';
$user = 'tanzeelniazi';
$pass = 'abc';
$db = 'Busarna';

$conn = @mysqli_connect($host, $user, $pass, $db);

if(mysqli_connect_errno()){

	die (mysqli_connect_error());
}

return $conn;

}

function field_length($conn, $key, $string){

if(strlen($string) < 6) {

	$status = "{$key} should be atleast 6 characters long.";
	return $status;
}

if(strlen($string) > 200) {

	$status = "{$key} must be less then 200 characters.";
	return $status;
}

return NULL;

}

function safe_out($conn, $string){

$string = strip_tags($string);
$string = trim($string);
$string = htmlspecialchars($string);
$string = mysqli_real_escape_string($conn, $string);

return $string;

}

function query_user_check($conn, $username){

$query = "SELECT * FROM users
					WHERE username = '{$username}' 
		 ";


$results = mysqli_query($conn, $query);


if ($results && mysqli_affected_rows($conn) == 1){

	$user = "Username Already Exists, Please choose another one";
	return $user;
}

return NULL;

}

function query_email_check($conn, $email){

$query = "SELECT * FROM users
					WHERE email = '{$email}' 
		 ";


$results = mysqli_query($conn, $query);


if ($results && mysqli_affected_rows($conn) == 1){

	$email = "Email Already Exists, Please choose another one";
	return $email;
}

return NULL;

}
/* Applying BlowFish encryption on the password */
function secure_password($password){

	$hash_format = "$2y$10$";
	$salt = md5("[email protected]@SpinZRphp");

	$salt_format = $hash_format . $salt;
	$hash = crypt($password, $salt_format);

	return $hash;

}

function query_insert_user($conn, $username, $pass_hash,
$first_name, $last_name, $email, $vericode){

$query = "INSERT INTO users
					VALUES (NULL, '{$username}',
							'{$pass_hash}', '{$first_name}',
							'{$last_name}', '{$email}', 
							'{$vericode}', 'Unverified', 
							12, 2, 1, 'admin'
							)
		";


$results = mysqli_query($conn, $query);

if($results){

	return  array ( 'username' => $username,
					'email' => $email,
					'vericode' => $vericode
				);
}

	$status = "Can't Register Your Account at the Moment";

	return $status;

}

function query_update_user($conn, $email, $vericode){

	$query = "UPDATE users 
					SET 
						status = 'verified'
					WHERE 
						email = '{$email}' AND
						email_code = '{$vericode}'
			 ";

	
	$results = mysqli_query($conn, $query);

	if ($results && mysqli_affected_rows($conn) == 1){

		return $results;				
	}

	 else { return NULL; }
}

?>[/php]

verify.php
[php]<?php
ob_start();
session_start();
require_once(‘functions.php’);
$conn = db_connect();
?>

Verify Your Account <?php
  if (isset($_SESSION['username']) &&
      isset($_SESSION['email']) &&
      isset($_SESSION['vericode'])
    )

  {
      
      $username = $_SESSION['username'];
      $to = $_SESSION['email'];
      $vericode = $_SESSION['vericode'];
      
      /* Change the following variables according to your site specifications */


          $my_site = "PHP Help";  
              $site_add = "http://localhost/Busarna/"; 
              $subject = "Email Activation requried for {$my_site}";
              $headers = "From: tanzee[email protected] \r\n";
              $headers .= "Reply-To: [email protected] \r\n";
              $headers .= "MIME-Version: 1.0\r\n";
              $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

              $message = '<b>Hello ' . $username . ' </b> <br /><br />
                    Thank you for your interest in ' . $my_site . ' 
                    We need to <span style="color: red;"> CONFIRM </span> your request first. <br /> 
                    <br />

                    IMPORTANT: all you need to do is click the link
                    below: <br /> <br /> <b>' . 

                    '<a href="' . $site_add .'verify.php?email=' . 
                      $to .'&vericode='. 
                      $vericode . '">
                    Confirm Your Email </a>'
                     . 

                   ' <br /> <br /> Click the link above and your account will be activated. If you can\'t use the above mentioned link then click on the link below and enter your email address and  <b><span style="color: blue;">' . $vericode . '</span></b>  in the code field to activate your account.<br /> <br />' .

                       $site_add .'verify.php' .

                   '<br /><br />If you do not want to proceed, simply ignore this message. <br /> <br />

                  
                   Regards, <br />

                   Tanzeel Niazi <br />
                   [email protected] <br />
                   www.spinzr.com <br />
                ';

     if (mail($to, $subject , $message, $headers)) {

     echo 
      ' <h3>Thanks for your registration but we need to verify your account. <br /> An email has been sent to your email address. Please click on the link given in the email to activate your account.</h3> 

        <h3> <a href="index.php">Click Here</a> to go the the Homepage </h3>

        ';

      /* Destroying the session so that users can't access the page variables on multiple page refreshes */

      session_destroy();
      $_SESSION = array();
      
    }

}

else {

    if( $_SERVER['REQUEST_METHOD'] == 'GET' &&
        isset($_GET['email']) &&
        isset($_GET['vericode']) &&
        !empty($_GET['email']) &&
        !empty($_GET['vericode'])
      ) {


        /* Ensuring if user doesn't use query string, then information gets submitted properly via form */

        $result = query_update_user($conn, 
                                      urldecode($_GET['email']),
                                      urldecode($_GET['vericode'])
                                      );

        if (is_null($result)){

            $_GET = array();
            $_SESSION['status'] = "
                        <h3> Sorry Invalid email / verfication code, Please try again or contact the site administrator
                        </h3>
                      ";
            header("Location: verify.php");

        } 

        else { 
                echo '<h3> Thank You! Your email has been verified.
                          <br /> Please <a href="login.php">click here </a> to go to Login Page. 
                      </h3>';
          }

    }
    else 
    {

        /* If a user has entered wrong email / verfication code at least once then the IF statement will run otherwise ELSE will execute */

         if (isset($_SESSION['status'])){

            echo $_SESSION['status'];
            unset($_SESSION['status']);
            
           }
          else {

            echo "<h1> Please enter the following details. </h1>";

          }

      /* If a user got to this page directly without any query string then He/She will see the following HTML form.

      The Closing Curly Braces are located after the HTML form 

      */

?>





          <tr>
              <td>
                <label for="vericode">Verification Code: </label>
              </td>
              <td>
               <input type="text" name="vericode" id="vericode" />
              </td>
          </tr>
      </table>
      <p><input type="submit" value="Verify" name="verify" /></p>
    </form>
<?php } } ?> <?php if (isset($conn)){
        mysqli_close($conn); 

      }

?>

<?php ob_end_flush(); ?>[/php]

queries.sql

CREATE TABLE users( user_id INT(11) AUTO_INCREMENT, username VARCHAR(30) NOT NULL, password VARCHAR(50) NOT NULL, first_name VARCHAR (100) NOT NULL, last_name VARCHAR (100) NOT NULL, email VARCHAR(200) NOT NULL, email_code VARCHAR(10) NOT NULL, status VARCHAR(11) NOT NULL, password_recover INT(11) NOT NULL, type INT(10) NOT NULL, allow_email INT (11), profile VARCHAR(100) NOT NULL, PRIMARY KEY(user_id) );

You can also download all the above code as a single ZIP file.


Busarna.zip (5.63 KB)


Email:


Can you make it all work and modify all files? It would be awsome! And if I should but a file in a special directory, can you write a .txt file that tell me where to put it?

Thanks in advance // Busarna4

Did the code worked or not? Do you understand the logic???

I will try to modify it for you, but there are somethings that I couldn’t understand like:

password_recover INT(11) NOT NULL, type INT(10) NOT NULL, allow_email INT (11), profile VARCHAR(100) NOT NULL,

What is their purpose and why they are in the DB???

It would be easy for me, if you make a bullet list of all the facilities you want in the script. But don’t rely on me heavily I’m just a newbie in the PHP releam.

I couldn’t get this one either ;D

password_recover is used so if a user forget the password they get to a page where they write the email address and then they get an email with a new random generated password, and when they log in with that password they are forced to change password. forced = they can’t access any other page until they changed it. When they click on forgot password and ask for a new password it atomaticlly sets password_recover to 1. So if password_recover = 0 you can do anything but if password_recover = 1 they have to change password and then they do password_recover = 0 again

type = if type is set to 0 (as it is when they register) they are a member and if type is set to 1 (witch I have to do manually) they are admins on the website. (type=0 = member, type=1 = Admin)

allow_email = I have an admin function witch allows me (admin) to email all users where allow_email is set to 1 but if it’s 0 they don’t get that email (there are a checkbox at the settings page that change this)

profile is used to store the profile picture (the uploaded picture get in the images/profile/ folder with a random name using md5 hash and microtime and the profile part in the db remember witch md5 hashed photo that user uploaded)

The files I have so far works great :slight_smile:

I want to be able to register with verification email, log in, send an email with there username if they have forgotten there username (they have to type there email in a site first) and the same thing if they have forgotten there password but instead of sending them the password the website generate a new password, hash it, update the password field with the new hashed password in the db, and then send an email with the actual password (and when they log in using that password but they can’t access anything until they change it), they should be able to change password, upload a profile picture, Admins should be able to email all user with allow_email = 1.

But the only thing I need help with really are to be able to log in, change password and generate new password if a user have forgotten the password.

I maybe need help with something more to, but those are the most needed ones since it’s the login/register system that’s the biggest problem.

Thanks again for all the help and sorry if my english is bad!

Thanks in advance // Busarna4

Can you make it so first and last name are optional?

OK. I will try to include the functions you asked for, but it will take some time. and I will make First Name and Last name Optional.

By the way, English is not my language too. :stuck_out_tongue:

Thanks man :slight_smile: I really appreciate what you’re doing for me :smiley:

okay :stuck_out_tongue:

Here is the code I’ve worked so far. I’ve have ZIPed it so you can quickly download it.


Busarna.zip (12.5 KB)

Sponsor our Newsletter | Privacy Policy | Terms of Service