I have a page here: https://github.com/alexwaters/PWTKD-new-CMS/blob/master/taekwondo/schedule-dev.php that is not showing my session messages: <?php echo output_message($message); ?>
I have been trying to track down what the heck is wrong with them, but have no idea. They work on other pages but not this one.
Can someone please help me find the noobie mistakes I made?
Per request here is some of the code that may be relevant:
schedule-dev.php
<?php require_once("../includes/initialize.php"); ?>
<?php $schedules = Schedule::find_all();?>
<?php $messages = Messages::find_by_id(1);?>
<!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>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contactLink").click(function(){
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
}else{
$("#contactForm").slideUp("slow");
}
});
});
function closeForm(){
$("#messageSent").show("slow");
setTimeout('$("#messageSent").hide();$("#contactForm").slideUp("slow")', 2000);
}
</script>
...
<?php
if(isset($_POST['signupSubmit'])){
$signup = new Signup();
$signup->name = $_POST['name'];
$signup->age = $_POST['email'];
if($signup->save()) {
$session->message("We will contact you with details.");
redirect_to('schedule.php');
} else {
$message = join("test", $signup->errors);
}
}
?>
<?php echo output_message($message); ?>
<div id="contactFormContainer">
<div id="contactLink"></div>
<div id="contactForm">
<fieldset>
<label for="name">Name *</label>
<input id="name" type="text" />
<label for="email">Email address *</label>
<input id="email" type="text" />
<input id="sendMail" type="submit" name="signupSubmit" onclick="closeForm()" />
<span id="messageSent"></span>
</fieldset>
</div>
</div>
Signup.php
<?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class Signup extends DatabaseObject {
protected static $table_name="signup";
protected static $db_fields=array('id', 'name','email');
public $id;
public $name;
public $email;
public $errors=array();
public function save() {
// A new record won't have an id yet.
if(isset($this->id)) {
// Really just to update the name
$this->update();
return true;
} else {
// Make sure there are no errors
// Can't save if there are pre-existing errors
if(!empty($this->errors)) { return false; }
// Make sure the name is not too long for the DB
if(strlen($this->name) >= 255) {
$this->errors[] = "Name must be <= 255 characters long.";
return false;
}
if(strlen($this->email) >= 255) {
$this->errors[] = "Email must be <= 255 characters long.";
return false;
}
if(empty($email)) {
$this->errors[] = "Please enter an email address";
return false;
}
//Finally add the item to the DB
if($this->create()) {
return true;
} else {
//
$this->errors[] = "Send failed, please contact us";
return false;
}
}
}
and some other generic class stuff
message method from session.php
public function message($msg="") {
if(!empty($msg)) {
// then this is "set message"
// make sure you understand why $this->message=$msg wouldn't work
$_SESSION['message'] = $msg;
} else {
// then this is "get message"
return $this->message;
}
}
Don't you need to add session_start() to you php file? Try doing that, let me know if that helps.
I had to use $this-email in the save method
I needed to make the form an actual post form
The session message wasn't being outputted(?) because it wasn't grabbing the post vars
Related
I wrote a script to protect my form with session token; however my script does not work if I try to validate form fields before checking for the token. Would someone help me figure out what is wrong with my script please?
<?php
session_start();
class TOKEN {
public static function generate() {
return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(15));
}
public static function check($token) {
if (isset($_SESSION['token']) && $token === $_SESSION['token']) {
unset($_SESSION['token']);
return true;
}
return false;
}
}
?>
<?php
$display_form = FALSE;
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$userpass = $_POST['userpass'];
if (strlen($username) < 4) {
$error_name = 'required';
$display_form = true;
$validation_error = true;
}
if (strlen($userpass) < 8) {
$error_pass = 'required';
$display_form = true;
$validation_error = true;
}
if (!$validation_error) {
if (TOKEN::check($_POST['token'])) {
echo 'process form';
} else {
echo 'invalid security token';
}
}
} else {
$display_form = TRUE;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<?php
if ($display_form == true) {
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">
<input type="hidden" name="token" value="<?php echo TOKEN::generate(); ?>">
<input type="text" name="username" id="" placeholder="username">
<?php echo $error_name; ?>
<br>
<input type="password" name="userpass" id="" placeholder="Password">
<?php echo $error_pass; ?>
<br>
<input type="submit" name="submit" value="Sign in">
</form>
</body>
</html>
<?php
}
?>
I suppose that the problem here is in the following.
You have token in the form and token in the session. They're equal.
When you fill the form with errors - your form loads again. But! In the session you have previous token, from point 1, and in the form you have new token.
You submit again and check different tokens.
So, the solution is to unset token always, no matter you have wrong or right values in the form.
Update:
I suppose it should be something like:
if (!$validation_error) {
// here token will be removed in `TOKEN::check`
if (TOKEN::check($_POST['token'])) {
echo 'process form';
} else {
echo 'invalid security token';
}
} else {
// remove token implicitly
TOKEN::remove();
}
And in TOKEN:
public static function check($token) {
$result = false;
if (isset($_SESSION['token'])) {
if ($token === $_SESSION['token']) {
$result = true;
}
// if token set - remove it
self::remove();
}
return $result;
}
public static function remove() {
unset($_SESSION['token']);
}
This code is very hard to read. I can't tell when if statements start and end. Also stop using classes for everything. Use procedural programming like a big boy.
Your issue is a simple one. $validation_error was not initialized in the outer scope. Meaning that it was not saved between if statments.
To fix this simply add $validation_error = false at the outer scope:
...
$display_form = FALSE;
$validation_error = false; // right here
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$userpass = $_POST['userpass'];
...
I'm writing my first php code... I'm trying to submit a form.
I have two php files. index.php(which contains the form) and process.php(which contains the method that handles the form).
But on form submission, the browser heads to process.php, so nothing is displayed.
I'm trying to echo the result in index.php .
And keep in mind this is my very first php code... :-)
This is index.php
<!DOCTYPE html>
<html>
<?php
include 'process.php';
$newletter1 = new newsletter();
?>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="email" placeholder="Your Email Address..."><br><br>
<input type="submit">
</form>
<h4><?php $newletter1 -> abc(); ?></h4>
</body>
</html>
And this is process.php
class newsletter
{
public function abc()
{
if (isset($_POST["email"])) {
$input = $_POST["email"];
if (empty($input)) {
echo "Please provide an email address!";
}else{
echo "Thanks for subscribing " . $input;
}
}else{
echo "ELSE is running...";
}
}
}
Your script process.php is just a class definition.
A class does nothing unless it is instantiated and a method called.
As you are including it and instantiating it in your index.php I would suggest changing your <form> tag so it runs itself, leaving href="" will do that.
<?php
// run this only if we are being set info by the user
// so not when the form is first loaded.
$to_show_later = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
include 'process.php';
$newletter1 = new newsletter();
$to_show_later = $newsletter1->abc();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="" method="post">
<input type="text" name="email" placeholder="Your Email Address..."><br><br>
<input type="submit">
</form>
<h4><?php echo $to_show_later; ?></h4>
</body>
</html>
It's also bad practice to echo directly out of a class method, so change this so it return the data.
class newsletter
{
public function abc()
{
$reply = '';
if (isset($_POST["email"])) {
$input = $_POST["email"];
if (empty($input)) {
$reply = "Please provide an email address!";
}else{
$reply = "Thanks for subscribing " . $input;
}
}else{
$reply = "ELSE is running...";
}
return $reply;
}
}
In your process.php replace it by:
if (isset($_POST["email"])) {
$input = $_POST["email"];
if (empty($input)) {
echo "Please provide an email address!";
}else{
echo "Thanks for subscribing " . $input;
}
}else{
echo "ELSE is running...";
}
It will work, and you dont have to include process.php to submit form only
I'm creating a function for PHP form validation. The idea is that if a user has not filled out a required field (for example, if a $_POST variable called "name" is empty), then the user will be warned.
This function doesn't seem to work, however:
function addError($x) {
if (!$_POST["$x"]) {
$error.="Please enter your $x";
}
}
echo $error;
I've isolated the problem down to the passing of the argument $x into $_POST, i.e. this line:
if (!$_POST["$x"]) {
Specifically, $_POST["$x"]. Is this the right way/syntax to pass an argument?
Thank you!
Your code should be like -
$error = '';
function addError($x, $error) {
if (!$x) { // Check for the data
$error.="Please enter your $x"; // Concatenate the errors
}
return $error; // return the error
}
echo addError($_POST[$x], $error); // Pass the data to check & the error variable
Try this.....
<form method="post">
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
<?php
$x=$_POST["name"];
function addError($x)
{
if ($x==null)
{
$error="Please enter your name";
}
else
{
$error='';
}
return $error;
}
echo addError($x);
?>
Try this :-
$error = "";
function addError($x)
{
global $error;
if ("" == $_POST['"'.$x.'"'])
{
$error.="Please enter your".$x;
}
}
addError("name");
echo $error;
I referenced above two answers and write some code for this question. It works when I tested. You might get some idea for your coding.
Here is my tested code.
PHP section
<?php
function check_error($x){
$error = "";
if(isset($_POST[$x]) && $_POST[$x] == ""){
$error = "Please Enter Data";
}
return $error;
}
echo check_error('txt_name');
?>
HTML section
<!DOCTYPE html>
<html>
<head>
<title> Testing </title>
</head>
<body>
<h1> Testing </h1>
<hr/>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="text" name="txt_name" value="" placeholder="Your name" />
<input type="Submit" name="btn_submit" value="Submit" />
</form>
</body>
</html>
Make $error a global variable.
I am developing a website with User registration and login ,after completing the page configuration ,i tried to register it worked perfectly and later next day i tried to register but the page is not loading ,after filling in the data and if i click submit ,it reloads the same register page with no effect ,how to solve this problem
SQL Query Processing code: (class.newuser.php)
enter code here
class User
{
public $user_active = 0;
private $clean_email;
public $status = false;
private $clean_password;
private $clean_username;
private $unclean_username;
public $sql_failure = false;
public $mail_failure = false;
public $email_taken = false;
public $username_taken = false;
public $activation_token = 0;
function __construct($user,$pass,$email)
{
//Used for display only
$this->unclean_username = $user;
//Sanitize
$this->clean_email = sanitize($email);
$this->clean_password = trim($pass);
$this->clean_username = sanitize($user);
if(usernameExists($this->clean_username))
{
$this->username_taken = true;
}
else if(emailExists($this->clean_email))
{
$this->email_taken = true;
}
else
{
//No problems have been found.
$this->status = true;
}
}
public function userPieAddUser()
{
global $db,$emailActivation,$websiteUrl,$db_table_prefix;
//Prevent this function being called if there were construction errors
if($this->status)
{
//Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
//Construct a unique activation token
$this->activation_token = generateactivationtoken();
//Do we need to send out an activation email?
if($emailActivation)
{
//User must activate their account first
$this->user_active = 0;
$mail = new userPieMail();
//Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE",array("{$websiteUrl}/",$this->activation_token));
//Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array("#ACTIVATION-MESSAGE","#ACTIVATION-KEY","#USERNAME#"),
"subjectStrs" => array($activation_message,$this->activation_token,$this->unclean_username)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if(!$mail->newTemplateMsg("new-registration.txt",$hooks))
{
$this->mail_failure = true;
}
else
{
//Send the mail. Specify users email here and subject.
//SendMail can have a third parementer for message if you do not wish to build a template.
if(!$mail->sendMail($this->clean_email,"New User"))
{
$this->mail_failure = true;
}
}
}
else
{
//Instant account activation
$this->user_active = 1;
}
if(!$this->mail_failure)
{
//Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `".$db_table_prefix."users` (
`username`,
`username_clean`,
`password`,
`email`,
`activationtoken`,
`last_activation_request`,
`LostpasswordRequest`,
`active`,
`group_id`,
`sign_up_date`,
`last_sign_in`
)
VALUES (
'".$db->sql_escape($this->unclean_username)."',
'".$db->sql_escape($this->clean_username)."',
'".$secure_pass."',
'".$db->sql_escape($this->clean_email)."',
'".$this->activation_token."',
'".time()."',
'0',
'".$this->user_active."',
'1',
'".time()."',
'0'
)";
return $db->sql_query($sql);
}
}
}
}
?>
HTML register.php
enter code here
<?php
require_once("models/config.php");
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: index.php"); die(); }
?>
<?php
//Forms posted
if(!empty($_POST))
{
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
//Perform some validation
//Feel free to edit / change as required
if(minMaxRange(5,25,$username))
{
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT",array(5,25));
}
if(minMaxRange(8,50,$password) && minMaxRange(8,50,$confirm_pass))
{
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT",array(8,50));
}
else if($password != $confirm_pass)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if(!isValidemail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
//End data validation
if(count($errors) == 0)
{
//Construct a user object
$user = new User($username,$password,$email);
//Checking this flag tells us whether there were any errors such as possible data duplication occured
if(!$user->status)
{
if($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE",array($username));
if($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE",array($email));
}
else
{
if(!$user->userPieAddUser())
{
if($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if(count($errors) == 0)
{
if($emailActivation)
{
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
} else {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
}
?>
<!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 | <?php echo $websiteName; ?> </title>
<?php require_once("head_inc.php"); ?>
</head>
<body>
<div class="modal-ish">
<div class="modal-header">
<h2>Sign Up</h2>
</div>
<div class="modal-body">
<div id="success">
<p><?php echo $message ?></p>
</div>
<div id="regbox">
<form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Password:</label>
<input type="password" name="password" />
</p>
<p>
<label>Re-type Password:</label>
<input type="password" name="passwordc" />
</p>
<p>
<label>Email:</label>
<input type="text" name="email" />
</p>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Register" />
</div>
</form>
</div>
<div class="clear"></div>
<p style="margin-top:30px; text-align:center;">Login / Forgot Password? / Home Page</p>
</body>
</html>
Its all due to div tags:
2 divisions closed within the form tag but they are opened outside the form tag.
So try by enclosing the whole form within one div(regbox) Including submit.
And make sure that no div is closed within form tag which is opened outside form tag.
The code below is a login system that I am using. It is supposed to allow a new user to register and then send the new user an activation email. It is inserting the new user into the MySQL database, but it is not sending the activation email. Any ideas why it's not sending the activation email?
Thanks in advance,
John
header.php:
<?php
//error_reporting(0);
session_start();
require_once ('db_connect.inc.php');
require_once ("function.inc.php");
$seed="0dAfghRqSTgx";
$domain = "...com";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>The Sandbox - <?php echo $domain; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="sandbox.css">
<div class="hslogo"><img src="images/hslogo.png" alt="Example" border="0"/></div>
</head>
<body>
login.php:
<?php
if (!isLoggedIn())
{
// user is not logged in.
if (isset($_POST['cmdlogin']))
{
// retrieve the username and password sent from login form & check the login.
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
} else
{
echo "Incorrect Login information !";
show_loginform();
}
} else
{
// User is not logged in and has not pressed the login button
// so we show him the loginform
show_loginform();
}
} else
{
// The user is already loggedin, so we show the userbox.
show_userbox();
}
?>
function show_loginform($disabled = false)
{
echo '<form name="login-form" id="login-form" method="post" action="./index.php?'.$_SERVER['QUERY_STRING'].'">
<div class="usernameformtext"><label title="Username">Username: </label></div>
<div class="usernameformfield"><input tabindex="1" accesskey="u" name="username" type="text" maxlength="30" id="username" /></div>
<div class="passwordformtext"><label title="Password">Password: </label></div>
<div class="passwordformfield"><input tabindex="2" accesskey="p" name="password" type="password" maxlength="15" id="password" /></div>
<div class="registertext">Register</div>
<div class="lostpasswordtext">Lost password?</div>
<p class="loginbutton"><input tabindex="3" accesskey="l" type="submit" name="cmdlogin" value="Login" ';
if ($disabled == true)
{
echo 'disabled="disabled"';
}
echo ' /></p></form>';
}
register.php:
<?php
require_once "header.php";
if (isset($_POST['register'])){
if (registerNewUser($_POST['username'], $_POST['password'], $_POST['password2'], $_POST['email'])){
echo "<div class='registration'>Thank you for registering, an email has been sent to your inbox, Please activate your account.
<a href='http://www...com/sandbox/index.php'>Click here to login.</a>
</div>";
}else {
echo "Registration failed! Please try again.";
show_registration_form();
}
} else {
// has not pressed the register button
show_registration_form();
}
?>
New User Function:
function registerNewUser($username, $password, $password2, $email)
{
global $seed;
if (!valid_username($username) || !valid_password($password) ||
!valid_email($email) || $password != $password2 || user_exists($username))
{
return false;
}
$code = generate_code(20);
$sql = sprintf("insert into login (username,password,email,actcode) value ('%s','%s','%s','%s')",
mysql_real_escape_string($username), mysql_real_escape_string(sha1($password . $seed))
, mysql_real_escape_string($email), mysql_real_escape_string($code));
if (mysql_query($sql))
{
$id = mysql_insert_id();
if (sendActivationEmail($username, $password, $id, $email, $code))
{
return true;
} else
{
return false;
}
} else
{
return false;
}
return false;
}
Send Activation Email function:
function sendActivationEmail($username, $password, $uid, $email, $actcode)
{
global $domain;
$link = "http://www.$domain/sandbox/activate.php?uid=$uid&actcode=$actcode";
$message = "
Thank you for registering on http://www.$domain/,
Your account information:
username: $username
password: $password
Please click the link below to activate your account.
$link
Regards
$domain Administration
";
if (sendMail($email, "Please activate your account.", $message, "no-reply#$domain"))
{
return true;
} else
{
return false;
}
}
Maybe because the function for sending email is mail and not sendMail? If the function sendMail is defined maybe there is an error in that function.
if (mail($email, "Please activate your account.", $message, "no-reply#$domain"))
{
return true;
} else
{
return false;
}
In addition to needing to use the mail function as mentioned by others, which is your primary problem, there is a small problem with this:
"no-reply#$domain"
PHP is expecting a header:
"From: no-reply#$domain"
or
"Reply-To: no-reply#$domain"
This isn't the reason your script is failing (as mentioned above, it's using the wrong function), but it is still important to comply with the standards or else things may break when you don't expect them to.