Page 4 of 7

Re: Mixing php and html

Posted: Thu Mar 22, 2012 8:57 pm
by Pavilion
Celauran wrote:The trouble lies in differentiating between a mistakenly cleared field and an intentionally cleared one. You could add some sort of checkbox system; either uncheck to make the field editable or check to denote "update this field", but both hinder user experience IMO.

Validating phone numbers can be tricky depending on the scope of your audience. If you know you will only be dealing with North American numbers, then it's considerably simpler. Strip anything non-numeric (at least for validation, you can keep the formatting if you choose) then check that string length is either 7, 10, or 11. You can add additional rules to make this more robust (ie. if strlen is 11, first digit must be 1) as desired.
If I could force phone number input as follows "(555) 555-5555" it would be best. That is the input mask already in use within the current classical system. Porting data back and forth between the mySQL tables and the current system would be much easier if the phone numbers matched current input requirements.

Pavilion

Re: Mixing php and html

Posted: Thu Mar 22, 2012 9:02 pm
by Celauran
Shouldn't be too hard, then. Strip all non-numeric characters then check that string length is 10. If not, return an error. If it is, you can then force the mask through substrings.

Code: Select all

$phone = preg_replace('/[^0-9]/', '', $_POST['phone']);
if (strlen($phone) == 10)
{
    $masked = '(' . substr($phone, 0, 3) . ') ' . substr($phone, 3, 3) . '-' . substr($phone, 6);
}
else
{
    // Some error condition
}

Re: Mixing php and html

Posted: Thu Mar 22, 2012 9:19 pm
by Pavilion
Celauran wrote:Shouldn't be too hard, then. Strip all non-numeric characters then check that string length is 10. If not, return an error. If it is, you can then force the mask through substrings.

Code: Select all

$phone = preg_replace('/[^0-9]/', '', $_POST['phone']);
if (strlen($phone) == 10)
{
    $masked = '(' . substr($phone, 0, 3) . ') ' . substr($phone, 3, 3) . '-' . substr($phone, 6);
}
else
{
    // Some error condition
}
Yes - that makes sense. Thank you.

I'll work on the script during the next few days and run it by you for input early next week.

Re: Mixing php and html

Posted: Thu Mar 22, 2012 10:03 pm
by Pavilion
Celauran:

I've another question. This doesn't pertain to immediate need. But, when I finally get this project off the ground (and on it's home domain) I'll want to import all employee user data (including an existing password that is used for logging into their classical database).

How can I import the password data and run it through PHPHash?

Pavilion

Re: Mixing php and html

Posted: Fri Mar 23, 2012 6:17 am
by Celauran
If the password is hashed in the existing database you'll need to import the hash and use whatever hashing algorithm is currently being used, foregoing PHPass altogether. Otherwise, you can export the existing DB to CSV files (1 or many depending on the size) and have PHP read in the values, hash the password, and prepare the INSERT query.

Re: Mixing php and html

Posted: Fri Mar 23, 2012 9:36 pm
by Pavilion
Celauran:

I'm working on the profile.php. Is there someway to "refresh" the input controls after updating the MySQL tables? The input controls default to $_SESSION values.

Once the update query runs, I assume I have to re-assign $_SESSION variables to pick up new data (if not please let me know).

But... is there a way to "refresh" the page so that new values show in appropriate input controls?

Thanks Much:

Pavilion

Re: Mixing php and html

Posted: Sat Mar 24, 2012 5:17 am
by Celauran
Display POST values if they exist.

Code: Select all

<input type="text" name="foo" value="echo isset($_POST['foo']) ? $_POST['foo'] : (isset($_SESSION['foo']) ? $_SESSION['foo'] : '')" />

Re: Mixing php and html

Posted: Mon Mar 26, 2012 2:41 pm
by Pavilion
Pavilion wrote:
Celauran wrote:Shouldn't be too hard, then. Strip all non-numeric characters then check that string length is 10. If not, return an error. If it is, you can then force the mask through substrings.

Code: Select all

$phone = preg_replace('/[^0-9]/', '', $_POST['phone']);
if (strlen($phone) == 10)
{
    $masked = '(' . substr($phone, 0, 3) . ') ' . substr($phone, 3, 3) . '-' . substr($phone, 6);
}
else
{
    // Some error condition
}
Yes - that makes sense. Thank you.

I'll work on the script during the next few days and run it by you for input early next week.
Hello Celauran:

Well - the profile.php is almost done and the only real problem I'm having is with the phone numbers. Firstly - following is the script for profile.php

Code: Select all

<?php
session_start();
// include database connection file, if connection doesn't work the include file will throw an error message
include '../schedule/include/db_connect.php';
	
ob_start(); // output buffering starts here. Ask Celauran why this is necessary.
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
}
if (isset($_POST['formsubmitted']))
{ // This tests to make sure form is submitted before error handling. Without this check, error messages will appear on simply opening the page because defaults don't fill in BEFORE script runs.

// ___________________________________________________________________________________________________________//
// Error handling routine. 
$errors = array(); //Declare an Array to store any error message. As php process the following "if" statement, true results are added to the $errors array.

    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
        $errors['email'] = "Not a valid email address.";
    }
    if (!$_POST['fname']) // If NOT $_POST - again exclamation point is "not" in php.
    {
        $errors['fname'] = "First name cannot be empty.";
    }
    if (!$_POST['lname'])
    {
        $errors['lname'] = "Last name cannot be empty.";
	}

// Error handling is complete. 
// ___________________________________________________________________________________________________________//
// clean phone numbers and apply variables before updating table.
// Clean desk phone first and assign to a variable for updating table.
$raw_dphone = mysql_real_escape_string(trim($_POST['dphone']));

if (!$raw_dphone)
{
	$d_phone = NULL;
}
	else
	{
	$dphone_replaced = preg_replace('/[^0-9]/', '', $raw_dphone); // takes out all characters except numbers.
		if (strlen($dphone_replaced) == 10)
		{
		$d_phone = '(' . substr($dphone_replaced, 0, 3) . ') ' . substr($dphone_replaced, 3, 3) . '-' . substr($dphone_replaced, 6);
		}
		else
		{
		$errors['dphone'] = $raw_dphone . " is not a valid phone number.";
		}
	}

// Now clean cell phone and assign to a variable for updating table.
$raw_cell = mysql_real_escape_string(trim($_POST['cell']));

if (!$raw_cell)
{
	$cell = NULL;
}
	else
	{
	$cell_replaced = preg_replace('/[^0-9]/', '', $raw_cell); // takes out all characters except numbers.
		if (strlen($cell_replaced) == 10)
		{
		$cell = '(' . substr($cell_replaced, 0, 3) . ') ' . substr($cell_replaced, 3, 3) . '-' . substr($cell_replaced, 6);
		}
		else
		{
		$errors['cell'] = $raw_cell . " is not a valid cell phone number.";
		}
	}
// Next declare remaining variables from $_POST data and run update query.
// ___________________________________________________________________________________________________________//

if (empty($errors)) // if empty $errors then proceed.
{
	$user = $_SESSION['user_id'];

    $fname = mysql_real_escape_string(trim($_POST['fname']));
    $lname = mysql_real_escape_string(trim($_POST['lname']));
    $ext = mysql_real_escape_string(trim($_POST['ext']));
	
	// Update mySQL table user record. 
	$query = "UPDATE UserTbl
	SET UserTbl.FName = '$fname', UserTbl.LName = '$lname', UserTbl.EmailAddress = '$email', UserTbl.DeskPhone = '$d_phone', UserTbl.Ext = '$ext', UserTbl.CellPhone = '$cell'
	WHERE (((UserTbl.user_id)='$user'));";
	
	mysql_query($query) or $errors['email'] = "The email address: ". $email ." is already registered.";
	
	if (empty($errors)) // if phone numbers are masked as "(555) 555-5555" they are not displaying properly within the input control. The following script has been created to do some testing. Since all input controls display a $_SESSION variable I wanted to assure my $_SESSION variables were picking up the most recent data.
	{

		$find_new_data = 
		"SELECT UserTbl.EmailAddress, UserTbl.FName, UserTbl.LName, UserTbl.EmailAddress, DeskPhone, Ext, CellPhone
		FROM UserTbl
		WHERE (((UserTbl.user_id)='$user'));";
		
		$result = mysql_query($find_new_data);
		while($row = mysql_fetch_array($result))
		{
			$table_fname = $row['FName'];
			$table_lname = $row['LName'];
			$table_email = $row['EmailAddress'];
			$table_deskphone = $row['DeskPhone'];
			$table_ext = $row['Ext'];
			$table_cell = $row['CellPhone'];
		
			// re-assign appropriate variables to $_SESSION.
			$_SESSION['fname'] = $table_fname;
			$_SESSION['lname'] = $table_lname;
			$_SESSION['email'] = $table_email;
			$_SESSION['deskphone'] = $table_deskphone;
			$_SESSION['ext'] = $table_ext;
			$_SESSION['cell'] = $table_cell;
		}
	}
}
}			
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Control Center</title>
        <link rel="stylesheet" type="text/css" href="../schedule/include/formats.css"/>
    </head>
    <body>
	<div class="shadow"><div class="header"></div></div>
        <div class="shadow">
        <?php
        include '../schedule/include/menu.php';
        ?>
        </div>
	<h1>Welcome to your Control Center, <?php echo $_SESSION['fname'];?>.</h1><br />
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
		<fieldset id="standardForm">
		<div class="headingbx">Edit Your Profile Here.</div><br />
			<div id="standFormLeft">               
				<label>First Name</label>
				<input tabindex="1" type="text" name="fname" <?php if (isset($_SESSION['fname'])){?> value= <?php echo $_SESSION['fname'];}?> /><br />
				<label>Last Name</label>
				<input tabindex="2" type="text" name="lname" <?php if (isset($_SESSION['lname'])){?>  value= <?php echo $_SESSION['lname'];}?> /><br />
				<label>Email Address</label>
				<input tabindex="3" type="email" name="email" <?php if (isset($_SESSION['email'])){?>  value= <?php echo $_SESSION['email'];}?> /><br />
			</div>
			<div id="standFormRight">               
				<label>Desk Phone</label>
				<input tabindex="4" type="tel" name="dphone" <?php if (isset($_SESSION['deskphone'])){?> value= <?php echo $_SESSION['deskphone'];}?> /><br />
				<label>Ext</label>
				<input tabindex="5" type="text" name="ext" <?php if (isset($_SESSION['ext'])){?> value= <?php echo $_SESSION['ext'];}?> /><br />
				<label>Cell Phone</label>
				<input tabindex="6" type="tel" name="cell" <?php if (isset($_SESSION['cell'])){?> value= <?php echo $_SESSION['cell'];}?> /><br />
				<input type="hidden" name="formsubmitted" value="TRUE" />
			</div>
				<input tabindex="7" type="submit" value="Submit" />	<br />

		<?php if (!empty($errors)): ?>
		<div class="headingbx">
		<p class="error">The following errors were detected:</p>
		<ul class="error">
			<?php if (isset($errors['fname'])): ?>
			<li><?php echo $errors['fname']; ?></li>
			<?php endif; ?>

			<?php if (isset($errors['lname'])): ?>
			<li><?php echo $errors['lname']; ?></li>
			<?php endif; ?>

			<?php if (isset($errors['email'])): ?>
			<li><?php echo $errors['email']; ?></li>
			<?php endif; ?>
			
			<?php if (isset($errors['dphone'])): ?>
			<li><?php echo $errors['dphone']; ?></li>
			<?php endif; ?>

			<?php if (isset($errors['cell'])): ?>
			<li><?php echo $errors['cell']; ?></li>
			<?php endif; ?>
		</ul>
		</div>
		<?php endif; ?>
		</fieldset>
	</form>
	</body>
</html>
Celauran - the tip you gave me for masking phone numbers is working. When I give the profile.php a phone number it is properly masked and the field is updated at table level. However, the phone number does not properly display if it is masked. It does display if it is not masked. Following is a screen shot:
phonenumber.jpg
If you will notice desk phone is not masked (I edited it at table level) and it is displaying just fine. Cell phone is masked. It updates fine at table level and displays with all 10 digits, masked as they should be. However, when displaying through an input control only "(222)" shows up. It is almost as if the ")" is acting as a delimiter and cutting off the rest of the cell phone number.

Any advice you have on this particular problem would be welcome.

You will notice in reading through the profile.php script the "if (empty($errors)" block after running a successful update query. I completely understand this block is not necessary in a functioning page. I put the block in to assign new values to the $_SESSION variables and then to echo those new values out. You should know that when I echo the phone number $_SESSION variables, they echo just fine as masked numbers.
______________________________________________________________

I do want your input on the overall script but would prefer to wait until this problem is solved before moving on to analysis of the entire script.

Thanks Much:

Pavilion

Re: Mixing php and html

Posted: Mon Mar 26, 2012 3:34 pm
by Celauran
You don't have quotes around value= values, so the space is being interpreted as the end of the value= value. Try this instead:

Code: Select all

<input tabindex="6" type="tel" name="cell" value="<?php echo isset($_SESSION['cell']) ? $_SESSION['cell'] : ''; ?>" /><br />
Also, that's not Donald Duck's phone number.

Re: Mixing php and html

Posted: Mon Mar 26, 2012 4:02 pm
by Pavilion
You don't have quotes around value= values, so the space is being interpreted as the end of the value= value. Try this instead:

Code: Select all

<?php echo isset($_SESSION['cell']) ? $_SESSION['cell'] : ''; ?>" /><br />
That did the trick. Thanks. If I understand the syntax properly the above statement is doing the following:
  • You moved my previous "if" condition INSIDE the Value. That makes sense.
  • the value echos the result of a conditional statement checking for isset($_SESSION). The question mark designates the condition (I'm assuming).
  • After the condition question mark, the "TRUE" portion of the conditional statement executes.
  • But what are the : and the single quotes about?
Also, that's not Donald Duck's phone number.
Well then I'm going to have to give Mickey Mouse "what for" ... he's the one that gave it to me. He even told me I could use his name. :D

Thanks again Celauran - Pavilion

Re: Mixing php and html

Posted: Mon Mar 26, 2012 4:22 pm
by Pavilion
OH - Celauran -

I'm assuming I have to reassign $_SESSION variables - please correct me if this is a wrong assumption.

But... I should be able to reassign them from the variables I inserted into the UPDATE query. There really is no legitimate reason to run a new SELECT query, and assign variables to table data before reassigning $_SESSION variables (right)???

Thanks again - Pavilion

Re: Mixing php and html

Posted: Mon Mar 26, 2012 4:41 pm
by Celauran
Pavilion wrote:That did the trick. Thanks. If I understand the syntax properly the above statement is doing the following:
  • You moved my previous "if" condition INSIDE the Value. That makes sense.
  • the value echos the result of a conditional statement checking for isset($_SESSION). The question mark designates the condition (I'm assuming).
  • After the condition question mark, the "TRUE" portion of the conditional statement executes.
  • But what are the : and the single quotes about?
It's a ternary operator. The bit after the colon is the FALSE condition, in this case an empty string.

Re: Mixing php and html

Posted: Mon Mar 26, 2012 4:43 pm
by Celauran
Pavilion wrote:I'm assuming I have to reassign $_SESSION variables - please correct me if this is a wrong assumption.
Do you mean after the form has been submitted? You could do that at the same time as your UPDATE query, yes.

Re: Mixing php and html

Posted: Mon Mar 26, 2012 9:10 pm
by Pavilion
Celauran wrote:
Pavilion wrote:I'm assuming I have to reassign $_SESSION variables - please correct me if this is a wrong assumption.
Do you mean after the form has been submitted? You could do that at the same time as your UPDATE query, yes.
Thanks Celauran:

I just finished reassigning $_SESSION variables and testing. All is working as it should. Now, I've just a few questions. Following is the script:

Code: Select all

<?php
session_start();
// include database connection file, if connection doesn't work the include file will throw an error message
include '../schedule/include/db_connect.php';
	
ob_start(); // output buffering starts here.
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
}
if (isset($_POST['formsubmitted']))
{ // This tests to make sure form is submitted before error handling. Without this check, error messages will appear on simply opening the page because defaults don't fill in BEFORE script runs.

// ___________________________________________________________________________________________________________//
// Error handling routine. 
$errors = array(); //Declare an Array to store any error message. As php process the following "if" statement, true results are added to the $errors array.

    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
        $errors['email'] = "Not a valid email address.";
    }
    if (!$_POST['fname']) // If NOT $_POST - again exclamation point is "not" in php.
    {
        $errors['fname'] = "First name cannot be empty.";
    }
    if (!$_POST['lname'])
    {
        $errors['lname'] = "Last name cannot be empty.";
	}

// Error handling is complete. 
// ___________________________________________________________________________________________________________//
// Clean phone numbers and apply variables before updating table. Start with desk phone.
$raw_dphone = mysql_real_escape_string(trim($_POST['dphone']));

if (!$raw_dphone)
{
	$d_phone = NULL;
}
	else
	{
	$dphone_replaced = preg_replace('/[^0-9]/', '', $raw_dphone); // takes out all characters except numbers.
		if (strlen($dphone_replaced) == 10)
		{
		$d_phone = '(' . substr($dphone_replaced, 0, 3) . ') ' . substr($dphone_replaced, 3, 3) . '-' . substr($dphone_replaced, 6);
		}
		else
		{
		$errors['dphone'] = $raw_dphone . " is not a valid phone number, please include area code.";
		}
	}

// Now clean cell phone and assign to a variable for updating table.
$raw_cell = mysql_real_escape_string(trim($_POST['cell']));

if (!$raw_cell)
{
	$cell = NULL;
}
	else
	{
	$cell_replaced = preg_replace('/[^0-9]/', '', $raw_cell); // takes out all characters except numbers.
		if (strlen($cell_replaced) == 10)
		{
		$cell = '(' . substr($cell_replaced, 0, 3) . ') ' . substr($cell_replaced, 3, 3) . '-' . substr($cell_replaced, 6);
		}
		else
		{
		$errors['cell'] = $raw_cell . " is not a valid cell phone number, please include area code.";
		}
	}
// Next declare remaining variables from $_POST data and run update query.
// ___________________________________________________________________________________________________________//

if (empty($errors)) // if empty $errors then proceed.
{
	$user = $_SESSION['user_id'];

    $fname = mysql_real_escape_string(trim($_POST['fname']));
    $lname = mysql_real_escape_string(trim($_POST['lname']));
    $ext = mysql_real_escape_string(trim($_POST['ext']));
	
	// Update mySQL table user record. 
	$query = "UPDATE UserTbl
	SET UserTbl.FName = '$fname', UserTbl.LName = '$lname', UserTbl.EmailAddress = '$email', UserTbl.DeskPhone = '$d_phone', UserTbl.Ext = '$ext', UserTbl.CellPhone = '$cell'
	WHERE (((UserTbl.user_id)='$user'));";
	
	mysql_query($query) or $errors['email'] = "The email address: ". $email ." is already registered.";
	
	if (empty($errors)) // If errors are empty - then reassign new values to $_SESSION.
	{
		$_SESSION['fname'] = $fname;
		$_SESSION['lname'] = $lname;
		$_SESSION['email'] = $email;
		$_SESSION['deskphone'] = $d_phone;
		$_SESSION['ext'] = $ext;
		$_SESSION['cell'] = $cell;
	}
}
}			
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Control Center</title>
        <link rel="stylesheet" type="text/css" href="../schedule/include/formats.css"/>
    </head>
    <body>
	<div class="shadow"><div class="header"></div></div>
        <div class="shadow">
        <?php
        include '../schedule/include/menu.php';
        ?>
        </div>
	<h1>Welcome to your Control Center, <?php echo $_SESSION['fname'];?>.</h1><br />
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
		<fieldset id="standardForm">
		<div class="headingbx">Edit Your Profile Here.</div><br />
			<div id="standFormLeft">               
				<label>First Name</label>
				<input tabindex="1" type="text" name="fname" value="<?php echo isset($_SESSION['fname']) ? $_SESSION['fname'] : ''; ?>" /><br />
				<label>Last Name</label>
				<input tabindex="2" type="text" name="lname" value="<?php echo isset($_SESSION['lname']) ? $_SESSION['lname'] : ''; ?>" /><br />
				<label>Email Address</label>
				<input tabindex="3" type="email" name="email" value="<?php echo isset($_SESSION['email']) ? $_SESSION['email'] : ''; ?>" /><br />
			</div>
			<div id="standFormRight">               
				<label>Desk Phone</label>
				<input tabindex="4" type="tel" name="dphone" value="<?php echo isset($_SESSION['deskphone']) ? $_SESSION['deskphone'] : ''; ?>" /><br />
				<label>Ext</label>
				<input tabindex="5" type="tel" name="ext" value="<?php echo isset($_SESSION['ext']) ? $_SESSION['ext'] : ''; ?>" /><br />
				<label>Cell Phone</label>
				<input tabindex="6" type="tel" name="cell" value="<?php echo isset($_SESSION['cell']) ? $_SESSION['cell'] : ''; ?>" /><br />
				<input type="hidden" name="formsubmitted" value="TRUE" />
			</div>
				<input tabindex="7" type="submit" value="Submit" />	<br />

		<?php if (!empty($errors)): ?>
		<div class="headingbx">
		<p class="error">The following errors were detected:</p>
		<ul class="error">
			<?php if (isset($errors['fname'])): ?>
			<li><?php echo $errors['fname']; ?></li>
			<?php endif; ?>

			<?php if (isset($errors['lname'])): ?>
			<li><?php echo $errors['lname']; ?></li>
			<?php endif; ?>

			<?php if (isset($errors['email'])): ?>
			<li><?php echo $errors['email']; ?></li>
			<?php endif; ?>
			
			<?php if (isset($errors['dphone'])): ?>
			<li><?php echo $errors['dphone']; ?></li>
			<?php endif; ?>

			<?php if (isset($errors['cell'])): ?>
			<li><?php echo $errors['cell']; ?></li>
			<?php endif; ?>
		</ul>
		</div>
		<?php endif; ?>
		</fieldset>
	</form>
	</body>
</html>
The following code snippet was included to redirect users if they are not logged in:

Code: Select all

ob_start(); // output buffering starts here.
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
}
I found this approach with some research. But I'm not quite sure what "output buffering " is and why it is necessary. In my mind the code snippet should check to see if $_SESSION has user_id. If there is no user_id the user should be redirected to login.php. It does work, but is ob_start() necessary?

Code: Select all

if (isset($_POST['formsubmitted']))
{ // This tests to make sure form is submitted before error handling. Without this check, error messages will appear on simply opening the page because defaults don't fill in BEFORE script runs.
paired with

Code: Select all

<input type="hidden" name="formsubmitted" value="TRUE" />
I only used this combination because it prevents error messages from displaying BEFORE the input control default values fill in. Is there a better way to stop error messages from prematurely filling in?

Code: Select all

session_start();
Is it necessary to start a session on every php page? Once a session is started at the login page, is it necessary to start a session on every page afterward?
____________________________________________________________

Overall, is there anything you would change with this script?

Thanks Much:

Pavilion

Re: Mixing php and html

Posted: Mon Mar 26, 2012 9:19 pm
by Pavilion
One other thing, Celauran:

When I'm successfully logged in and using the profile.php page php is not tracking this as effectively as it should. If I open a new window and put in the profile.php url I am directed to login.php (as if I'm not logged in).

Typically when using a website, the site can tell you're logged in - even if you use a new window. What do I need to do to assure this capability with my site?

Thanks again - Pavilion