I have a class setup to write some data to a mysql database that doesn't seem to be actually writing the data. I believe the issue lies in the PDO statements somewhere. I double checked the query and the database connection on other scripts on the site and they work fine. Any ideas?
Here is my form:
<?php
$navsection = 'addClass';
$dir = $_SERVER['DOCUMENT_ROOT'] . "/grades/";
// load php-login components
require_once $dir . 'php-login.php';
$classes = new Classes();
// load head file
require_once $dir . 'includes/head.php';
?>
<h1>Add a Class</h1>
<?php
// show negative messages
if ($classes->errors) {
foreach ($classes->errors as $error) {
echo $error;
}
}
// show positive messages
if ($classes->messages) {
foreach ($classes->messages as $message) {
echo $message;
}
}
?>
<br />
<form method='post' action='<?php $siteurl; ?>/grades/pages/addClass.php' name='addClass_form'>
<label for='className'>Class Name:</label>
<input id='className' type='text' name='className' required /><br />
<label for='classProfessor'>Professor's Name:</label>
<input id='classProfessor' type='text' name='classProfessor' /><br />
<label for='classPeriod'>Class Period:</label>
<select id='classPeriod' name='classPeriod'>
<option value='Spring 2014'>Spring 2014</option>
<option value='Fall 2013'>Fall 2013</option>
</select><br />
<label for='classStartDate'>Class Start Date:</label>
<input id='classStartDate' type='date' name='classStartDate' /><br />
<label for='classEndDate'>Class End Date:</label>
<input id='classEndDate' type='date' name='classEndDate' /><br />
<input type='submit' name='addClass' value='Submit' />
</form>
<?php
//load footer file
require_once $dir . 'includes/footer.php';
?>
Here is my class:
<?php
class Classes
{
private $db_connection = null;
public $classAdd_successful = false;
public $classDelete_successful = false;
public $classEdit_successful = false;
public $errors = array();
public $messages = array();
public function __construct()
{
session_start();
if (isset($_POST["addClass"])) {
$this->addNewClass($_POST['className'], $_POST['classProfessor'], $_POST['classPeriod'], $_POST['classStartDate'], $_POST['classEndDate']);
}
}
private function databaseConnection()
{
if ($this->db_connection != null) {
return true;
} else {
try {
$this->db_connection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
return true;
} catch (PDOException $e) {
$this->errors[] = "Database error";
return false;
}
}
}
private function addNewClass ($className, $classProfessor, $classPeriod, $classStart, $classEnd)
{
if(empty($className)) {
$this->errors[] = "Please enter a class name.";
} elseif(empty($classProfessor)) {
$this->errors[] = "Please enter a class professor.";
} elseif(empty($classPeriod)) {
$this->errors[] = "Please select a class period";
} elseif(empty($classStart)) {
$this->errors[] = "Please enter a class start date.";
} elseif(empty($classEnd)) {
$this->errors[] = "Please enter a class end date.";
}
if ($this->databaseConnection() == true) {
//Write data to database
$query_new_class_insert = $this->db_connection->prepare('INSERT INTO classes (class_name, user_id, professor_name, class_start, class_end, school_period) VALUES(:className, :userID, :professorName, :classStart, :classEnd, :schoolPeriod)');
$query_new_class_insert->bindvalue(':className', $className, PDO::PARAM_STR);
$query_new_class_insert->bindvalue(':userID', $_SESSION['user_id'], PDO::PARAM_INT);
$query_new_class_insert->bindvalue(':professorName', $classProfessor, PDO::PARAM_STR);
$query_new_class_insert->bindvalue(':classStart', $classStart, PDO::PARAM_STR);
$query_new_class_insert->bindvalue(':classEnd', $classEnd, PDO::PARAM_STR);
$query_new_class_insert->bindvalue(':schoolPeriod', $schoolPeriod, PDO::PARAM_STR);
$query_new_class_insert->execute();
$this->classAdd_successful = true;
} else {
$this->errors[] = "Database write error";
}
}
}
?>
Related
For my application, there are three levels of users:
top level (00)
mid "district" level
lower level
The interface built allows users to create messages that will be distributed to a mobile app.
I had it working fine, but was then later tasked to add the mid-level. Now, even though the messages appear to update properly, I am encountering an issue that, instead of displaying "Message Updated" and the form after a message is submitted, I am receiving the "You do not have permission to access this page" message.
This does NOT occur with the mid/district level, only the lower and upper levels. Some reason, for these two, it is not properly reading $_SESSION['store'] after the form is submitted (though it works as expected when the page is loaded normally, not via POST).
I would greatly appreciate any guidance:
<?php
session_start();
function format($input) {
$input = trim($input);
$input = stripcslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$con = new PDO("sqlite:managers.db");
$store = $_SESSION['store'];
$stores;
$file;
$district;
$file = "messages/" . $store . ".txt";
if(!file_exists($file)) {
$temp = fopen($file, "w"); // create file
fclose($temp);
}
if(strpos("d", $store) == 0) {
$district = true;
$sql = "SELECT district FROM managers WHERE store = '$store'";
$statement = $con->query($sql);
$row = $statement->fetch();
$storesArray = explode(",", $row[0]);
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$newMessage = format($_POST['message']);
$writer = fopen($file, "w");
fwrite($writer, $newMessage);
fclose($writer);
if($district) {
foreach($storesArray as $store) {
$fileName = "messages/d" . $store . ".txt";
if(!file_exists($fileName)) {
$temp = fopen($fileName, "w"); // create file
fclose($temp);
}
$writer = fopen($fileName, "w");
fwrite($writer, $newMessage);
fclose($writer);
}
}
}
$handler = fopen($file, "r");
$currentMessage = fread($handler, filesize($file));
fclose($handler);
?>
// some code omitted //
<?php
if($store == "" || $store == null) {
echo "<p>You do not have permission to view this page</p>";
} else {
echo "<h2>Manage Messages"; if($store == "00") {
echo "<a href='admin.php'><input type='button' id='adminBack' value='Back' /></a></h2>";
} else {
echo "<a href='adminUI.php'><input type='button' id='adminBack' value='Back' /></a></h2>";
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h2>Message Updated!</h2>";
}
echo "<form class='admin' class='col-md-6' method='post' action='manageMessages.php'>
<div class='form-group'>
<label for='message'> Message: </label>
<textarea class='form-control' id='message' name='message' >$currentMessage</textarea>
<input type='submit' value='Post Message' />
</div>
</form>";
}
?>
</div>
<!-- end page specific content -->
The login page that sets the session:
<?php
session_start();
function format($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
};
$store; $pass; $valid;
echo "<script>function redirect() {
location.assign('manageMessages.php');
}
function adminRedirect() {
location.assign('admin.php');
}</script>";
if($_GET['logout']) {
session_unset();
session_destroy();
}
if($_SERVER['REQUEST_METHOD'] == "POST") {
if(!empty($_POST['store']) && !empty($_POST['pass'])) {
$store = format($_POST['store']);
$pass = format($_POST['pass']);
$con = new PDO("sqlite:managers.db");
$sql = "SELECT *FROM managers WHERE store = '$store' AND password = '$pass'";
$statement = $con->query($sql);
$rows = $statement->fetchAll();
$count = count($rows);
if($count != 1) {
$valid = false;
} else {
$valid = true;
}
}
else {
$valid = false;
}
}
?>
// excess code //
<?php
$location;
if($valid) {
$_SESSION['store'] = $store;
if($store == "00") {
echo "<script>setTimeout(adminRedirect(), 1);</script>";
} else {
echo "<script>setTimeout(redirect(), 1);</script>";
} } elseif ($valid === false) {
echo "<h3>Please enter a valid store/password combination!</h3>";
}
?>
<h2>Admin Login</h2>
<form class="admin" method="post" action="adminUI.php">
<div class="form-group">
<label for="store">Store Number: </label>
<input type="text" class="form-control" name="store" id="store" />
<label for="pass">Password:</label>
<input type="text" class="form-control" name="pass" id="pass" />
<input type="submit" value="Login" />
</div>
</form>
Your $store variable is being overwritten by your foreach:
foreach($storesArray as $store)
You must use a different name for that foreach, something like:
foreach($storesArray as $store2)
We both thought it was working but I tested it and it doesnt output anything. It checks if theres sessions e.t.c and if not then its meant to output a form but it doesnt can anyone enlighten me on my error?
Code:
<?php
session_start();
//Include Database Config.
include('../cdn/global/db.php');
//PDO Settings.
$opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
$dsn = "mysql:host=$host;dbname=$dbname";
//Create a PDO Session.
$DBH = new PDO($dsn, $username, $password, $opt);
//Session Attributes.
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$loginForm = "
<form method='POST' action='' class='pure-form' style='color: #000;'>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>'
</fieldset>
</form>";
if(isset($_POST['username']) && isset($_POST['password'])){
echo $_POST['username'].'is trying to login with password'.$_POST['password'];
$st = $DBH->prepare("SELECT :username FROM users WHERE username = :username AND password = :password");
$st->bindParam(':password', $_POST['password']);
$st->bindParam(':username', $_POST['username']);
$st->execute();
if($st->rowCount()){
$row = $st->fetch(PDO::FETCH_OBJ);
$_SESSION['username'] = $row->username;
echo $_SESSION['username'];
return true;
}
} else if(!isset($_SESSION['username'])) {
echo $loginForm;
}
?>
I think your problem will be resolved if you remove the isset from the first two lines so your first lines should look as follow:
if(!$_SESSION['username'] && ! $_POST['username'] && ! $_POST['password']) {
echo $loginForm;
} elseif(isset($_SESSION['username']) && isset($_POST['username']) && isset($_POST['password'])) {
$grantAccess = login(); //after some serious validation or validate inside
if(!$grantAccess) {
echo 'Test 2';
}
}
Personally, I try to separate tasks so I can keep things straight. Here is basically what I do. Note, all the functions would be on their own files included as needed into any pages that require them. I have notated areas of interest:
<?php
session_start();
// This would be better as a static class so as not to create new connections all the time
// You can populate all the false values here with actual database info
// If you do it here, then the function will not need arguments when you go
// To use it. The only time you would populate the args after this point is if
// you need to connect to multiple databases on the same page.
function Connect($host = false,$username = false,$password = false,$dbname = false)
{
try {
//Create a PDO Session.
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
//Session Attributes.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
echo "<code><pre>".print_r($e)."</pre></code>";
$con = false;
}
return $con;
}
// Since you are just assigning a variable some html, may as well make it a bit flexible in a function (just incase)
function LoginForm($settings = false)
{
$method = (!empty($settings['method']))? $settings['method']:"post";
$action = (!empty($settings['action']))? $settings['action']:"";
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':"";
$class = (!empty($settings['class']))? $settings['class']:"pure-form";
ob_start();
?>
<form method='<?php echo $method; ?>' action='<?php echo $action; ?>' class='<?php echo $class; ?>' style='color: #000;'<?php echo $id; ?>>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>
</fieldset>
</form>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function fetch($sql = false,$bind = false,$obj = false)
{
if(empty($sql))
return 0;
$query = Connect()->prepare($sql);
if(!$query)
return 0;
$query->execute($bind);
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(!empty($row))
$row = ($obj)? (object) $row : $row;
else
$row = 0;
return $row;
}
function user_login($username = false, $password = false)
{
$st = fetch("SELECT username,password FROM users WHERE username = :username",array(":username"=>$username));
$valid = false;
if($st != 0) {
if($st[0]['password'] == $password) {
$_SESSION['username'] = $row[0]['username'];
$valid = true;
}
}
return $valid;
}
function user_logout($location = 'loggedout.php')
{
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
session_destroy();
header("Location: ".$location);
exit;
}
}
// Include Database Config.
// If you just have $username,$password,$host,$dbname here,
// you can skip this if you just add those values into the Connect()
// function as default arguements
include('../cdn/global/db.php');
//Add static function that listens for logout
user_logout();
// If username set (password is also going to be set)
if(!empty($_POST['username']))
// Get true/false for user hit
echo (user_login($_POST['username'],$_POST['password']))? "Welcome ".htmlspecialchars($_SESSION['username']) : "Invalid username and/or password!";
// If there is no session username, show login form
echo (empty($_SESSION['username']))? LoginForm() : 'Log Out';
?>
EDIT: How I would do it in this scenario (in a general sense)
/functions/functions.php
<?php
function Connect($host = false,$username = false,$password = false,$dbname = false)
{
try {
//Create a PDO Session.
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
//Session Attributes.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
echo "<code><pre>".print_r($e)."</pre></code>";
$con = false;
}
return $con;
}
// Since you are just assigning a variable some html, may as well make it a bit flexible in a function (just incase)
function LoginForm($settings = false)
{
$method = (!empty($settings['method']))? $settings['method']:"post";
$action = (!empty($settings['action']))? $settings['action']:"";
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':"";
$class = (!empty($settings['class']))? $settings['class']:"pure-form";
ob_start();
?>
<form method='<?php echo $method; ?>' action='<?php echo $action; ?>' class='<?php echo $class; ?>' style='color: #000;'<?php echo $id; ?>>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>
</fieldset>
</form>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function fetch($sql = false,$bind = false,$obj = false)
{
if(empty($sql))
return 0;
$query = Connect()->prepare($sql);
if(!$query)
return 0;
$query->execute($bind);
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(!empty($row))
$row = ($obj)? (object) $row : $row;
else
$row = 0;
return $row;
}
function user_login($username = false, $password = false)
{
$st = fetch("SELECT username,password FROM users WHERE username = :username",array(":username"=>$username));
$valid = false;
if($st != 0) {
if($st[0]['password'] == $password) {
$_SESSION['username'] = $row[0]['username'];
$valid = true;
}
}
return $valid;
}
function user_logout($location = 'loggedout.php')
{
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
session_destroy();
header("Location: ".$location);
exit;
}
}
?>
login.php
session_start();
include_once(__DIR__.'/functions/functions.php');
user_logout();
?><html>
<head>
</head>
<body>
<?php
if(!empty($_POST['username']))
echo (user_login($_POST['username'],$_POST['password']))? "Welcome ".htmlspecialchars($_SESSION['username']) : "Invalid username and/or password!";
echo (empty($_SESSION['username']))? LoginForm() : 'Log Out';
?>
</body>
</html>
You can also create a class to manager your users. Let's create db.php class.
<?php
class Db {
private static $_dbase = 'data';
private static $_username = 'root';
private static $_passwd = '';
private static $_host = 'localhost';
private static $_options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
private static $_dsn;
private static $_db;
function __construct() {
}
public static function getDB() {
if (!isset(self::$_db)) {
try {
self::$_dsn = 'mysql:host=' . self::$_host . ';dbname=' . self::$_dbase;
self::$_db = new PDO(self::$_dsn, self::$_username, self::$_passwd, self::$_options);
} catch (PDOException $exc) {
echo $exc->getMessage();
}
}
return self::$_db;
}
}
And now let's create User.php class
<?php
session_start();
require_once 'db.php';
class USER {
private $db;
function __construct() {
$this->db = Db::getDb();
}
public function register($uname, $umail, $upass) {
try {
$new_password = password_hash($upass, PASSWORD_DEFAULT);
//create the activasion code
$activation = md5(uniqid(rand(), true));
$stmt = $this->db->prepare("INSERT INTO users(user_name,user_email,user_pass,active)
VALUES(:uname, :umail, :upass,:active)");
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->bindparam(":active", $activation);
$stmt->execute();
$id = $this->db->lastInsertId('memberID');
$this->sendMail($id, $activation);
$this->redirect('sign-up.php?joined');
return $stmt;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function login($uname, $umail, $upass) {
try {
$stmt = $this->db->prepare("SELECT * FROM `users` WHERE `user_name` = :uname AND `user_email` = :umail LIMIT 1");
$stmt->execute(array(':uname' => $uname, ':umail' => $umail));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
//verifying user.
if (password_verify($upass, $userRow['user_pass']) && $userRow['active'] === 'Yes') {
$_SESSION['user_session'] = $userRow['user_id'];
return true;
} else {
return false;
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
private function sendMail($email,$id, $activation) {
//send email to the user for account activation.
$to = $email;
$subject = "Registration Confirmation";
$body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n " . DIR . "activate.php?x=$id&y=$activation\n\n Regards Site Admin \n\n";
$additionalheaders = "From: <" . SITEEMAIL . ">\r\n";
$additionalheaders .= "Reply-To: " . SITEEMAIL . "";
mail($to, $subject, $body, $additionalheaders);
}
//check if the user is logged in
public function is_loggedin() {
if (isset($_SESSION['user_session'])) {
return true;
}
}
// redirect the user.
public function redirect($url) {
header("Location: $url");
}
//user log out
public function logout() {
session_destroy();
unset($_SESSION['user_session']);
return true;
}
//display login form
public function display_login_form() {
return "
<form method='POST' action='' class='pure-form' style='color: #000;'>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>'
</fieldset>
</form>";
}
}
We are going to check if the user is logged in and if not display the login form.
<?php
require_once 'User.php';
$User = new User();
$form = '';
if($User->is_loggedin()){
$User->redirect('private.php');
}else{
$form = $User->display_login_form();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><?php echo $form; ?></div>
</body>
i'm trying to create a simple user class but i can't get the data in the database i tried a lot of different code now here is the user class
namespace MonetizeMedia;
class User {
private $uid;
private $fields;
public function __construct() {
$this->uid = null;
$this->fields = array('username' => '',
'password' => '');
}
public function __get($field) {
if($field == 'uid')
{
return $this->uid;
}
else
{
return $this->fields[$field];
}
}
public function __set($field, $value) {
if(array_key_exists($field, $this->fields))
{
$this->fields[$field] = $value;
}
}
public function createUser() {
try {
$db = new \MonetizeMedia\Database;
$bcrypt = new \MonetizeMedia\Bcrypt(15);
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":username", $username);
$stmt->bindParam(":password", $bcrypt->hash($password));
$stmt->execute();
return "Registration Successful";
} catch ( PDOException $e ) {
return $e->getMessage();
}
}
and here is the register page
<?php
ob_start();
session_start();
include 'classes/user.class.php';
if(isset($_POST['submitted'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$User->username = $username;
$User->password = $password;
if($User->createUser()) {
echo "DONE!";
}
else
{
echo "An error occured while creating your account. Please try later.";
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Register</title>
</head>
<body>
<form method="post" action="">
<ul>
<li>
<label for="usn">Username : </label>
<input type="text" name="username" />
</li>
<li>
<label for="passwd">Password : </label>
<input type="password" name="password" />
</li>
<li class="buttons">
<input type="submit" name="register" value="Register" />
</li>
</ul>
</form>
</body>
</html>
i'm trying to learn php and pdo so i'm not so good at the moment
Its a log in form, and a class_login.php file. I got a token, to verify the form submissions. Its a random string and i send it hidden. I got 3 error messages on my class. Invalid form submission. Invalid form data. and Invalid Username/Password. The problem is doesnt matter what i do i get stuck on the first error invalid form submission. Its like the token i send never matches the session token. But when i remove that part i always get the invalid form data, even if i write a correct existing user/password. Need some help here please:
<?php
class class_login
{
private $id;
private $username;
private $password;
private $passmd5;
private $errors;
private $access;
private $login;
private $ltoken;
public function __construct()
{
$this->errors = array();
$this->login = isset($_POST['login'])? 1:0;
$this->access = 0;
$this->ltoken = $_POST['ltoken'];
$this->id = 0;
$this->username = ($this->login)? $this->filter($_POST['username']) : $_SESSION['username'];
$this->password = ($this->login)? $this->filter($_POST['password']) : '';
$this->passmd5 = ($this->login)? md5($this->password) : $_SESSION['password'];
}
public function isLoggedIn()
{
($this->login)? $this->verifyPost() : $this->verifySession();
return $this->access;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function verifyPost()
{
try
{
if(!$this->tokenValid())
throw new Exception('Invalid Form Submission!');
if(!$this->isDataValid())
throw new Exception('Invalid Form Data!');
if(!$this->verifyDatabase())
throw new Exception('Invalid Username/Password!');
$this->access = 1;
$this->registerSession();
}
catch(Exception $e)
{
$this->errors[] = $e->getMessage();
}
}
public function verifySession()
{
if($this->sessionExist() && $this->verifyDatabase())
$this->access = 1;
}
public function verifyDatabase()
{
include('db_connect.php');
$data = mysql_query("SELECT ID FROM users WHERE username = '($this->username)' AND password = '($this->passmd5)'");
if (mysql_num_rows($data))
{
list($this->id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
return false;
}
public function isDataValid()
{
return (preg_match('/[^a-zA-Z0-9]$/', $this->username) && preg_match('/[^a-zA-Z0-9]$/', $this->password))? 1:0;
}
public function tokenValid()
{
return (!isset($_SESSION['ltoken']) || $this->ltoken != $_SESSION['ltoken'])? 0 : 1;
}
public function registerSession()
{
$_SESSION['ID'] = $this->id;
$_SESSION['username'] = $this->username;
$_SESSION['password'] = $this->passmd5;
}
public function sessionExist()
{
return (isset($_SESSION['username']) && isset($_SESSION['password']))? 1 : 0;
}
public function show_errors()
{
foreach($this->errors as $value)
echo $value."</br>";
}
}
?>
Here is the login_form.php
<?php
$check = 0;
$ltoken = $_SESSION['ltoken'] = md5(uniqid(mt_rand(), true));
if(isset($_POST['login']))
{
$check = 1;
include('class_login.php');
$login = new class_login();
if ($login->isLoggedIn())
echo "Success!";
else
$login->show_errors();
}
?>
<link rel="stylesheet" href="CSS/regstyle.css" type="text/css" />
<script src="JS/jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var checker = <?php echo $check; ?>;
if(checker == 1)
{
$("#logform").slideDown("fast")
}
});
</script>
<div id="content">
<?php echo $ltoken; ?>
<!-- Begin Form -->
<div class="form-content">
<form class="reg-form" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<fieldset>
<div class="divusername">
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Your Username Here" />
</div>
<div class="password">
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Your Password Here" />
</div>
<div class="submit-button">
<input type="hidden" name="ltoken" value="<?php echo $ltoken; ?>" />
<input type="submit" name="login" value="Login" />
</div>
</fieldset>
</form>
</div>
</div>
I suspect that you forgot to start the session using session_start(). Please show us how you use this class. (The file where you use it.)
Edit
Disregard the above. The problem here is that you are setting the $_SESSION['ltoken'] to a new random value on each page load. That's why the posted value (this is one generation 'behind') never matches.
Separate out this code:
return (!isset($_SESSION['ltoken']) || $this->ltoken != $_SESSION['ltoken'])? 0 : 1;
It may or may not be accurate, but it's not readable and makes your debugging harder. I think it may be throwing you off because you're using the if or else as the second condition.
if( ! isset( $_SESSION['ltoken'] ) return false;
return ( $this->ltoken != $_SESSION['ltoken']) ? 0 : 1;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Headers already sent by PHP
I have been all over the internet trying to figure this out. There are about a million threads discussing this error, but none of them make it clear how to solve it.
Here is what I am trying to accomplish, and I don't think it's that complicated.
I want to put html-form-guide.com's contact form script contactform.phplink on an existing html page. I have already renamed it to .php and that's fine. The .php for the actual form submission is a seperate file, which I have included in the body section of my html with
<?
include ('contactform.php')
?>
The contact form shows up fine, and you can enter everything fine. But when you click submit, you get the aforementioned error:
Warning: Cannot modify header information - headers already sent by... etc
When you click the submit button, another php script runs that validates everything and sends the email. This runs fine too, as emails are actually being sent. Then it is SUPPOSED to load a page that says thank you for your submission with this code:
function RedirectToURL($url)
{
header("Location: $url");
exit;
But it doesn't, instead I get the error. It sounds like it is loading something from my main html page that actually displays the form, which is preventing this part from working. I have been to plenty of threads already that say you can't have any html or anything else displayed before the header command, but this doesn't really help me. I don't understand what else is being loaded, and far more importantly, I don't understand how to make it work. I vaguely understand the problem, what I don't at all understand is how to fix it.
index.php
<body>
<div id="container">
<div id="header">
<p style="font-size:36px;">VoiceOverGenie.com</p>
</div>
<div id="social">
<ul id="soclist">
<li>facebook</li>
<li>twitter</li>
<li>linkedin</li>
<li>blog</li>
</ul>
</div>
<?
include ('contactform.php')
?>
<div id="content">
</div>
</div>
</body>
</html>
contactform.php
<?PHP
/*
Contact Form from HTML Form Guide
This program is free software published under the
terms of the GNU Lesser General Public License.
See this page for more info:
http://www.html-form-guide.com/contact-form/simple-php-contact-form.html
*/
require_once("./include/fgcontactform.php");
$formproc = new FGContactForm();
//1. Add your email address here.
//You can add more than one receipients.
$formproc->AddRecipient('test#test'); //<<---Put your email address here
//2. For better security. Get a random tring from this link: http://tinyurl.com/randstr
// and put it here
$formproc->SetFormRandomKey('CnRrspl1FyEylUj');
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("thank-you.php");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>Contact us</title>
<link rel="STYLESHEET" type="text/css" href="contact.css" />
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
</head>
<body>
<!-- Form Code Start -->
<form id='contactus' action='<?php echo $formproc->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Contact us</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<input type='hidden' name='<?php echo $formproc->GetFormIDInputName(); ?>' value='<?php echo $formproc->GetFormIDInputValue(); ?>'/>
<input type='text' class='spmhidip' name='<?php echo $formproc->GetSpamTrapInputName(); ?>' />
<div class='short_explanation'>* required fields</div>
<div><span class='error'><?php echo $formproc->GetErrorMessage(); ?></span></div>
<div class='container'>
<label for='name' >Your Full Name*: </label><br/>
<input type='text' name='name' id='name' value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" /><br/>
<span id='contactus_name_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' value='<?php echo $formproc->SafeDisplay('email') ?>' maxlength="50" /><br/>
<span id='contactus_email_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='phone' >Phone Number*:</label><br/>
<input type='text' name='phone' id='phone' value='<?php echo $formproc->SafeDisplay('phone') ?>' maxlength="15" /><br/>
<span id='contactus_phone_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='message' >Message:</label><br/>
<span id='contactus_message_errorloc' class='error'></span>
<textarea rows="10" cols="50" name='message' id='message'><?php echo $formproc->SafeDisplay('message') ?></textarea>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Submit' />
</div>
</fieldset>
</form>
<!-- client-side Form Validations:
Uses the excellent form validation script from JavaScript-coder.com-->
<script type='text/javascript'>
// <![CDATA[
var frmvalidator = new Validator("contactus");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("message","maxlen=2048","The message is too long!(more than 2KB!)");
frmvalidator.addValidation("phone","req","Please provide your phone number");
// ]]>
</script>
</body>
</html>
fgcontactform.php
<?PHP
/*
Contact Form from HTML Form Guide
This program is free software published under the
terms of the GNU Lesser General Public License.
This program is distributed in the hope that it will
be useful - WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
#copyright html-form-guide.com 2010
*/
require_once("class.phpmailer.php");
/*
Interface to Captcha handler
*/
class FG_CaptchaHandler
{
function Validate() { return false;}
function GetError(){ return '';}
}
/*
FGContactForm is a general purpose contact form class
It supports Captcha, HTML Emails, sending emails
conditionally, File atachments and more.
*/
class FGContactForm
{
var $receipients;
var $errors;
var $error_message;
var $name;
var $email;
var $message;
var $from_address;
var $form_random_key;
var $conditional_field;
var $arr_conditional_receipients;
var $fileupload_fields;
var $captcha_handler;
var $mailer;
function FGContactForm()
{
$this->receipients = array();
$this->errors = array();
$this->form_random_key = 'HTgsjhartag';
$this->conditional_field='';
$this->arr_conditional_receipients=array();
$this->fileupload_fields=array();
$this->mailer = new PHPMailer();
$this->mailer->CharSet = 'utf-8';
}
function EnableCaptcha($captcha_handler)
{
$this->captcha_handler = $captcha_handler;
session_start();
}
function AddRecipient($email,$name="")
{
$this->mailer->AddAddress($email,$name);
}
function SetFromAddress($from)
{
$this->from_address = $from;
}
function SetFormRandomKey($key)
{
$this->form_random_key = $key;
}
function GetSpamTrapInputName()
{
return 'sp'.md5('KHGdnbvsgst'.$this->GetKey());
}
function SafeDisplay($value_name)
{
if(empty($_POST[$value_name]))
{
return'';
}
return htmlentities($_POST[$value_name]);
}
function GetFormIDInputName()
{
$rand = md5('TygshRt'.$this->GetKey());
$rand = substr($rand,0,20);
return 'id'.$rand;
}
function GetFormIDInputValue()
{
return md5('jhgahTsajhg'.$this->GetKey());
}
function SetConditionalField($field)
{
$this->conditional_field = $field;
}
function AddConditionalReceipent($value,$email)
{
$this->arr_conditional_receipients[$value] = $email;
}
function AddFileUploadField($file_field_name,$accepted_types,$max_size)
{
$this->fileupload_fields[] =
array("name"=>$file_field_name,
"file_types"=>$accepted_types,
"maxsize"=>$max_size);
}
function ProcessForm()
{
if(!isset($_POST['submitted']))
{
return false;
}
if(!$this->Validate())
{
$this->error_message = implode('<br/>',$this->errors);
return false;
}
$this->CollectData();
$ret = $this->SendFormSubmission();
return $ret;
}
function RedirectToURL($url)
{
header("Location: $url");
exit;
}
function GetErrorMessage()
{
return $this->error_message;
}
function GetSelfScript()
{
return htmlentities($_SERVER['PHP_SELF']);
}
function GetName()
{
return $this->name;
}
function GetEmail()
{
return $this->email;
}
function GetMessage()
{
return htmlentities($this->message,ENT_QUOTES,"UTF-8");
}
/*-------- Private (Internal) Functions -------- */
function SendFormSubmission()
{
$this->CollectConditionalReceipients();
$this->mailer->CharSet = 'utf-8';
$this->mailer->Subject = "Contact form submission from $this->name";
$this->mailer->From = $this->GetFromAddress();
$this->mailer->FromName = $this->name;
$this->mailer->AddReplyTo($this->email);
$message = $this->ComposeFormtoEmail();
$textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
$this->mailer->AltBody = #html_entity_decode($textMsg,ENT_QUOTES,"UTF-8");
$this->mailer->MsgHTML($message);
$this->AttachFiles();
if(!$this->mailer->Send())
{
$this->add_error("Failed sending email!");
return false;
}
return true;
}
function CollectConditionalReceipients()
{
if(count($this->arr_conditional_receipients)>0 &&
!empty($this->conditional_field) &&
!empty($_POST[$this->conditional_field]))
{
foreach($this->arr_conditional_receipients as $condn => $rec)
{
if(strcasecmp($condn,$_POST[$this->conditional_field])==0 &&
!empty($rec))
{
$this->AddRecipient($rec);
}
}
}
}
/*
Internal variables, that you donot want to appear in the email
Add those variables in this array.
*/
function IsInternalVariable($varname)
{
$arr_interanl_vars = array('scaptcha',
'submitted',
$this->GetSpamTrapInputName(),
$this->GetFormIDInputName()
);
if(in_array($varname,$arr_interanl_vars))
{
return true;
}
return false;
}
function FormSubmissionToMail()
{
$ret_str='';
foreach($_POST as $key=>$value)
{
if(!$this->IsInternalVariable($key))
{
$value = htmlentities($value,ENT_QUOTES,"UTF-8");
$value = nl2br($value);
$key = ucfirst($key);
$ret_str .= "<div class='label'>$key :</div><div class='value'>$value </div>\n";
}
}
foreach($this->fileupload_fields as $upload_field)
{
$field_name = $upload_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename = basename($_FILES[$field_name]['name']);
$ret_str .= "<div class='label'>File upload '$field_name' :</div><div class='value'>$filename </div>\n";
}
return $ret_str;
}
function ExtraInfoToMail()
{
$ret_str='';
$ip = $_SERVER['REMOTE_ADDR'];
$ret_str = "<div class='label'>IP address of the submitter:</div><div class='value'>$ip</div>\n";
return $ret_str;
}
function GetMailStyle()
{
$retstr = "\n<style>".
"body,.label,.value { font-family:Arial,Verdana; } ".
".label {font-weight:bold; margin-top:5px; font-size:1em; color:#333;} ".
".value {margin-bottom:15px;font-size:0.8em;padding-left:5px;} ".
"</style>\n";
return $retstr;
}
function GetHTMLHeaderPart()
{
$retstr = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'."\n".
'<html><head><title></title>'.
'<meta http-equiv=Content-Type content="text/html; charset=utf-8">';
$retstr .= $this->GetMailStyle();
$retstr .= '</head><body>';
return $retstr;
}
function GetHTMLFooterPart()
{
$retstr ='</body></html>';
return $retstr ;
}
function ComposeFormtoEmail()
{
$header = $this->GetHTMLHeaderPart();
$formsubmission = $this->FormSubmissionToMail();
$extra_info = $this->ExtraInfoToMail();
$footer = $this->GetHTMLFooterPart();
$message = $header."Submission from 'contact us' form:<p>$formsubmission</p><hr/>$extra_info".$footer;
return $message;
}
function AttachFiles()
{
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
$filename =basename($_FILES[$field_name]['name']);
$this->mailer->AddAttachment($_FILES[$field_name]["tmp_name"],$filename);
}
}
function GetFromAddress()
{
if(!empty($this->from_address))
{
return $this->from_address;
}
$host = $_SERVER['SERVER_NAME'];
$from ="nobody#$host";
return $from;
}
function Validate()
{
$ret = true;
//security validations
if(empty($_POST[$this->GetFormIDInputName()]) ||
$_POST[$this->GetFormIDInputName()] != $this->GetFormIDInputValue() )
{
//The proper error is not given intentionally
$this->add_error("Automated submission prevention: case 1 failed");
$ret = false;
}
//This is a hidden input field. Humans won't fill this field.
if(!empty($_POST[$this->GetSpamTrapInputName()]) )
{
//The proper error is not given intentionally
$this->add_error("Automated submission prevention: case 2 failed");
$ret = false;
}
//name validations
if(empty($_POST['name']))
{
$this->add_error("Please provide your name");
$ret = false;
}
else
if(strlen($_POST['name'])>50)
{
$this->add_error("Name is too big!");
$ret = false;
}
//email validations
if(empty($_POST['email']))
{
$this->add_error("Please provide your email address");
$ret = false;
}
else
if(strlen($_POST['email'])>50)
{
$this->add_error("Email address is too big!");
$ret = false;
}
else
if(!$this->validate_email($_POST['email']))
{
$this->add_error("Please provide a valid email address");
$ret = false;
}
//message validaions
if(strlen($_POST['message'])>2048)
{
$this->add_error("Message is too big!");
$ret = false;
}
//captcha validaions
if(isset($this->captcha_handler))
{
if(!$this->captcha_handler->Validate())
{
$this->add_error($this->captcha_handler->GetError());
$ret = false;
}
}
//file upload validations
if(!empty($this->fileupload_fields))
{
if(!$this->ValidateFileUploads())
{
$ret = false;
}
}
return $ret;
}
function ValidateFileType($field_name,$valid_filetypes)
{
$ret=true;
$info = pathinfo($_FILES[$field_name]['name']);
$extn = $info['extension'];
$extn = strtolower($extn);
$arr_valid_filetypes= explode(',',$valid_filetypes);
if(!in_array($extn,$arr_valid_filetypes))
{
$this->add_error("Valid file types are: $valid_filetypes");
$ret=false;
}
return $ret;
}
function ValidateFileSize($field_name,$max_size)
{
$size_of_uploaded_file =
$_FILES[$field_name]["size"]/1024;//size in KBs
if($size_of_uploaded_file > $max_size)
{
$this->add_error("The file is too big. File size should be less than $max_size KB");
return false;
}
return true;
}
function IsFileUploaded($field_name)
{
if(empty($_FILES[$field_name]['name']))
{
return false;
}
if(!is_uploaded_file($_FILES[$field_name]['tmp_name']))
{
return false;
}
return true;
}
function ValidateFileUploads()
{
$ret=true;
foreach($this->fileupload_fields as $upld_field)
{
$field_name = $upld_field["name"];
$valid_filetypes = $upld_field["file_types"];
if(!$this->IsFileUploaded($field_name))
{
continue;
}
if($_FILES[$field_name]["error"] != 0)
{
$this->add_error("Error in file upload; Error code:".$_FILES[$field_name]["error"]);
$ret=false;
}
if(!empty($valid_filetypes) &&
!$this->ValidateFileType($field_name,$valid_filetypes))
{
$ret=false;
}
if(!empty($upld_field["maxsize"]) &&
$upld_field["maxsize"]>0)
{
if(!$this->ValidateFileSize($field_name,$upld_field["maxsize"]))
{
$ret=false;
}
}
}
return $ret;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
/*
Sanitize() function removes any potential threat from the
data submitted. Prevents email injections or any other hacker attempts.
if $remove_nl is true, newline chracters are removed from the input.
*/
function Sanitize($str,$remove_nl=true)
{
$str = $this->StripSlashes($str);
if($remove_nl)
{
$injections = array('/(\n+)/i',
'/(\r+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}
return $str;
}
/*Collects clean data from the $_POST array and keeps in internal variables.*/
function CollectData()
{
$this->name = $this->Sanitize($_POST['name']);
$this->email = $this->Sanitize($_POST['email']);
/*newline is OK in the message.*/
$this->message = $this->StripSlashes($_POST['message']);
}
function add_error($error)
{
array_push($this->errors,$error);
}
function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email);
}
function GetKey()
{
return $this->form_random_key.$_SERVER['SERVER_NAME'].$_SERVER['REMOTE_ADDR'];
}
}
?>
The contactform.php has obviously not been created for your usage in index.php:
<body>
<div id="container">
<div id="header">
...
</div>
<?php
include ('contactform.php')
?>
<div id="content">
...
</div>
</div>
</body>
</html>
Instead it has it's output and processing logic on it's own. Read the usage terms, the software has not been written to fit for a particular purpose:
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
You need to adopt the contact.php file itself to make it working with your website. Or use an <iframe> element`MDC to "include" it.
There are many situations which shows this kind of error messages.
One reason is white spaces.Especially in the first line of your page.
Check whether your pages contains white spaces before or after the opening and closing PHP tags.Delete those spaces.