Jump to content
Larry Ullman's Book Forums

Recommended Posts

I am having a problem with the registration page in Chapter 4, Example 1.  When I complete the registration form, a simply get a blank page below the header.  It stays on register.php and does not advance to thankyou.php. 

 

Error checking indicates an undefined index for all the variables.  Not sure why that is happening, as I am using the script from the book.

 

Any suggestions would be appreciated.

Link to comment
Share on other sites

I was able to correct the issue in which an error message was reported.  However, the problem remains that once I complete the registration form and click submit, I remain on the registration page and no "thank you" message is given.  Likewise, I check the database and obviously a user hasn't been added.

Link to comment
Share on other sites

<?php

// This is the registration page for the site.
// This file both displays and processes the registration form.
// This script is begun in Chapter 4.

// Require the configuration before any PHP code as the configuration controls error reporting:
require('includes/config.inc.php');
// The config file also starts the session.

// Require the database connection:
require(MYSQL);

// Include the header file:
$page_title = 'Register';
include('includes/header.html');

// For storing registration errors:
$reg_errors = array();

// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

	// Check for a first name:
	if (preg_match('/^[A-Z \'.-]{2,45}$/i', $_POST['first_name'])) {
		$fn = escape_data($_POST['first_name'], $dbc);
	} else {
		$reg_errors['first_name'] = 'Please enter your first name!';
	}
	
	// Check for a last name:
	if (preg_match('/^[A-Z \'.-]{2,45}$/i', $_POST['last_name'])) {
		$ln = escape_data($_POST['last_name'], $dbc);
	} else {
		$reg_errors['last_name'] = 'Please enter your last name!';
	}
	
	// Check for a username:
	if (preg_match('/^[A-Z0-9]{2,45}$/i', $_POST['username'])) {
		$u = escape_data($_POST['username'], $dbc);
	} else {
		$reg_errors['username'] = 'Please enter a desired name using only letters and numbers!';
	}
	
	// Check for an email address:
	if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === $_POST['email']) {
		$e = escape_data($_POST['email'], $dbc);
	} else {
		$reg_errors['email'] = 'Please enter a valid email address!';
	}

	// Check for a password and match against the confirmed password:
	if (preg_match('/^(\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,}$/', $_POST['pass1']) ) {
		if ($_POST['pass1'] === $_POST['pass2']) {
			$p = $_POST['pass1'];
		} else {
			$reg_errors['pass2'] = 'Your password did not match the confirmed password!';
		}
	} else {
		$reg_errors['pass1'] = 'Please enter a valid password!';
	}
	
	if (empty($reg_errors)) { // If everything's OK...

		// Make sure the email address and username are available:
		$q = "SELECT email, username FROM users WHERE email='$e' OR username='$u'";
		$r = mysqli_query($dbc, $q);
	
		// Get the number of rows returned:
		$rows = mysqli_num_rows($r);
	
		if ($rows === 0) { // No problems!
			
			// Add the user to the database...
			
			// Include the password_compat library, if necessary:
			include('includes/lib/password.php');
			
			// Temporary: set expiration to a month!
			// Change after adding PayPal!
			 $q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires) VALUES ('$u', '$e', '"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln', ADDDATE(NOW(), INTERVAL 1 MONTH) )";
			
			// New query, updated in Chapter 6 for PayPal integration:
			// Sets expiration to yesterday:
			//$q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires) VALUES ('$u', '$e', '"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln', SUBDATE(NOW(), INTERVAL 1 DAY) )";

			$r = mysqli_query($dbc, $q);

			if (mysqli_affected_rows($dbc) === 1) { // If it ran OK.
	
				// Get the user ID:
				// Store the new user ID in the session:
				// Added in Chapter 6:
				//$uid = mysqli_insert_id($dbc);
//				$_SESSION['reg_user_id']  = $uid;		

				// Display a thanks message...

				// Original message from Chapter 4:
				// echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! You may now log in and access the site\'s content.</p></div>';

				// Updated message in Chapter 6:
				echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! To complete the process, please now click the button below so that you may pay for your site access via PayPal. The cost is $10 (US) per year. <strong>Note: When you complete your payment at PayPal, please click the button to return to this site.</strong></p></div>';

				

				// Send a separate email?
				$body = "Thank you for registering at <whatever site>. Blah. Blah. Blah.\n\n";
				mail($_POST['email'], 'Registration Confirmation', $body, 'From: admin@simplehomesales.net');
	
				// Finish the page:
				include('includes/footer.html'); // Include the HTML footer.
				exit(); // Stop the page.
				
			} else { // If it did not run OK.
				trigger_error('You could not be registered due to a system error. We apologize for any inconvenience. We will correct the error ASAP.');
			}
			
		} else { // The email address or username is not available.
			
			if ($rows === 2) { // Both are taken.
	
				$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';			
				$reg_errors['username'] = 'This username has already been registered. Please try another.';			

			} else { // One or both may be taken.

				// Get row:
				$row = mysqli_fetch_array($r, MYSQLI_NUM);
						
				if( ($row[0] === $_POST['email']) && ($row[1] === $_POST['username'])) { // Both match.
					$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';	
					$reg_errors['username'] = 'This username has already been registered with this email address. If you have forgotten your password, use the link at left to have your password sent to you.';
				} elseif ($row[0] === $_POST['email']) { // Email match.
					$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';						
				} elseif ($row[1] === $_POST['username']) { // Username match.
					$reg_errors['username'] = 'This username has already been registered. Please try another.';			
				}
		
			} // End of $rows === 2 ELSE.
			
		} // End of $rows === 0 IF.
		
	} // End of empty($reg_errors) IF.

} // End of the main form submission conditional.

// Need the form functions script, which defines create_form_input():
// The file may already have been included by the header.
require_once('includes/form_functions.inc.php');
?><h1>Register</h1>
<p>Access to the site's content is available to registered users at a cost of $10.00 (US) per year. Use the form below to begin the registration process. <strong>Note: All fields are required.</strong> After completing this form, you'll be presented with the opportunity to securely pay for your yearly subscription via <a href="http://www.paypal.com">PayPal</a>.</p>
<form action="register.php" method="post" accept-charset="utf-8">
<?php 
create_form_input('first_name', 'text', 'First Name', $reg_errors); 
create_form_input('last_name', 'text', 'Last Name', $reg_errors); 
create_form_input('username', 'text', 'Desired Username', $reg_errors); 
echo '<span class="help-block">Only letters and numbers are allowed.</span>';
create_form_input('email', 'email', 'Email Address', $reg_errors); 
create_form_input('pass1', 'password', 'Password', $reg_errors);
echo '<span class="help-block">Must be at least 6 characters long, with at least one lowercase letter, one uppercase letter, and one number.</span>';
create_form_input('pass2', 'password', 'Confirm Password', $reg_errors); 
?>
	<input type="submit" name="submit_button" value="Next →" id="submit_button" class="btn btn-default" />
</form>
<br>
<?php // Include the HTML footer:
include('includes/footer.html');
?>

It is the register.php script, working in Chapter 4 (and excluding any PayPay linkage.)  Server runs PHP 5.3.13 but accepts the password_hash fix.  The script as I am trying to run it:

 

 

 

Link to comment
Share on other sites

  • 2 months later...

I too would like to see the step by step solution to this problem because when I attempt to register, I get the following Fatal Error:

 

Fatal error: Call to undefined function password_hash() in /home/content/82/11778682/html/html/register.php on line 86

 

The codes on line 86 is as follow:

$q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires) VALUES ('$u', '$e', '"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln', SUBDATE(NOW(), INTERVAL 1 DAY) )";

 

I would really appreciate it if some can indicate to me what it is am over looking here.

 

cheers

Thanks.
 

Link to comment
Share on other sites

Thank you Larry for your quick response. I have attempted everything conceivable to resolve the issue and unfortunately, I have not been able to get it right. Am not too sure what function that is hinder my progress. Very frustrating cause it's been quite sometime I have been dealing with this  issue.  If you are able to provide further insight, I along with others would greatly benefit from it a clearer explanation.

Thanks .

Link to comment
Share on other sites

Thanks Larry. I followed your previous recommendation and it seem to be working now. The problem is initially, I did not  add the lib folder consisting of the password.php file in the includes folder. Because I am using godaddy server, I thought they were running the latest php. However, when I checked, my version was lower so I just need to download the file and add it into my includes folder and now it's worked like a charm.

So for anyone encountering a similar problem ensure that you are running the correct php version otherwise do exactly as Larry recommends in the book and it should work.

Again thanks.

Cheers.

Link to comment
Share on other sites

Here are how my final codes looks like:

 

<?php

// This is the registration page for the site.
// This file both displays and processes the registration form.
// This script is begun in Chapter 4.

// Require the configuration before any PHP code as the configuration controls error reporting:
require('./includes/config.inc.php');
// The config file also starts the session.

// Require the database connection:
require('./includes/mysql.inc.php');


// Include the header file:
$page_title = 'Register';
include('./includes/header.html');

// For storing registration errors:
$reg_errors = array();

// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Check for a first name:
    if (preg_match('/^[A-Z \'.-]{2,45}$/i', $_POST['first_name'])) {
        $fn = escape_data($_POST['first_name'], $dbc);
    } else {
        $reg_errors['first_name'] = 'Please enter your first name!';
    }
    
    // Check for a last name:
    if (preg_match('/^[A-Z \'.-]{2,45}$/i', $_POST['last_name'])) {
        $ln = escape_data($_POST['last_name'], $dbc);
    } else {
        $reg_errors['last_name'] = 'Please enter your last name!';
    }
    
    // Check for a username:
    if (preg_match('/^[A-Z0-9]{2,45}$/i', $_POST['username'])) {
        $u = escape_data($_POST['username'], $dbc);
    } else {
        $reg_errors['username'] = 'Please enter a desired name using only letters and numbers!';
    }
    
    // Check for an email address:
    if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === $_POST['email']) {
        $e = escape_data($_POST['email'], $dbc);
    } else {
        $reg_errors['email'] = 'Please enter a valid email address!';
    }

    // Check for a password and match against the confirmed password:
    if (preg_match('/^(\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,}$/', $_POST['pass1']) ) {
        if ($_POST['pass1'] === $_POST['pass2']) {
            $p = $_POST['pass1'];
        } else {
            $reg_errors['pass2'] = 'Your password did not match the confirmed password!';
        }
    } else {
        $reg_errors['pass1'] = 'Please enter a valid password!';
    }
    
    if (empty($reg_errors)) { // If everything's OK...

        // Make sure the email address and username are available:
        $q = "SELECT email, username FROM users WHERE email='$e' OR username='$u'";
        $r = mysqli_query($dbc, $q);
    
        // Get the number of rows returned:
        $rows = mysqli_num_rows($r);
    
        if ($rows === 0) { // No problems!
            
            // Add the user to the database...
            
            // Include the password_compat library, if necessary:
             include('./includes/lib/password.php');
            
            // Temporary: set expiration to a month!
            // Change after adding PayPal!
              $q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires) VALUES ('$u', '$e', '"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln', ADDDATE(NOW(), INTERVAL 1 MONTH) )";
            
            // New query, updated in Chapter 6 for PayPal integration:
            // Sets expiration to yesterday:
            // $q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires) VALUES ('$u', '$e', '"  .  password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln', SUBDATE(NOW(), INTERVAL 1 DAY) )";

            $r = mysqli_query($dbc, $q);

            if (mysqli_affected_rows($dbc) === 1) { // If it ran OK.
    
                // Get the user ID:
                // Store the new user ID in the session:
                // Added in Chapter 6:
                $uid = mysqli_insert_id($dbc);
//                $_SESSION['reg_user_id']  = $uid;        

                // Display a thanks message...

                // Original message from Chapter 4:
                // echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! You may now log in and access the site\'s content.</p></div>';

                // Updated message in Chapter 6:
                echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! To complete the process, please now click the button below so that you may pay for your site access via PayPal. The cost is $10 (US) per year. <strong>Note: When you complete your payment at PayPal, please click the button to return to this site.</strong></p></div>';

                // PayPal link added in Chapter 6:
                echo '<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
                <input type="hidden" name="cmd" value="_s-xclick">
                    <input type="hidden" name="email" value="' . $e . '">
                <input type="hidden" name="hosted_button_id" value="8YW8FZDELF296">
                <input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
                <img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
                </form>
                ';

                // Send a separate email?
                $body = "Thank you for registering at <whatever site>. Blah. Blah. Blah.\n\n";
                mail($_POST['email'], 'Registration Confirmation', $body, 'From: admin@example.com');
    
                // Finish the page:
                include('./includes/footer.html'); // Include the HTML footer.
                exit(); // Stop the page.
                
            } else { // If it did not run OK.
                trigger_error('You could not be registered due to a system error. We apologize for any inconvenience. We will correct the error ASAP.');
            }
            
        } else { // The email address or username is not available.
            
            if ($rows === 2) { // Both are taken.
    
                $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';            
                $reg_errors['username'] = 'This username has already been registered. Please try another.';            

            } else { // One or both may be taken.

                // Get row:
                $row = mysqli_fetch_array($r, MYSQLI_NUM);
                        
                if( ($row[0] === $_POST['email']) && ($row[1] === $_POST['username'])) { // Both match.
                    $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';    
                    $reg_errors['username'] = 'This username has already been registered with this email address. If you have forgotten your password, use the link at left to have your password sent to you.';
                } elseif ($row[0] === $_POST['email']) { // Email match.
                    $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';                        
                } elseif ($row[1] === $_POST['username']) { // Username match.
                    $reg_errors['username'] = 'This username has already been registered. Please try another.';            
                }
        
            } // End of $rows === 2 ELSE.
            
        } // End of $rows === 0 IF.
        
    } // End of empty($reg_errors) IF.

} // End of the main form submission conditional.

// Need the form functions script, which defines create_form_input():
// The file may already have been included by the header.
require_once('./includes/form_functions.inc.php');
?><h1>Register</h1>
<p>Access to the site's content is available to registered users at a cost of $10.00 (US) per year. Use the form below to begin the registration process. <strong>Note: All fields are required.</strong> After completing this form, you'll be presented with the opportunity to securely pay for your yearly subscription via <a href="http://www.paypal.com">PayPal</a>.</p>
<form action="register.php" method="post" accept-charset="utf-8">
<?php
create_form_input('first_name', 'text', 'First Name', $reg_errors);
create_form_input('last_name', 'text', 'Last Name', $reg_errors);
create_form_input('username', 'text', 'Desired Username', $reg_errors);
echo '<span class="help-block">Only letters and numbers are allowed.</span>';
create_form_input('email', 'email', 'Email Address', $reg_errors);
create_form_input('pass1', 'password', 'Password', $reg_errors);
echo '<span class="help-block">Must be at least 6 characters long, with at least one lowercase letter, one uppercase letter, and one number.</span>';
create_form_input('pass2', 'password', 'Confirm Password', $reg_errors);
?>
    <input type="submit" name="submit_button" value="Next →" id="submit_button" class="btn btn-default" />
</form>
<br>
<?php // Include the HTML footer:
include('./includes/footer.html');
?>

Link to comment
Share on other sites

  • 4 weeks later...

Sorry for the late replies as I have gotten busy on another site that popped up.  I've spent a couple days here again trying to fix this issue, but I'm still getting blank pages when registering.

 

Register.php

 

<?php
require('./includes/config.inc.php');
require(MYSQL);
$page_title = 'Register';
include('./includes/header.html');
 
$reg_errors = array();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Check for a first name:
if (preg_match('/^[A-Z \'.-]{2,45}$/i', $_POST['first_name'])) {
        $fn = escape_data($_POST['first_name'], $dbc);
    } else {
        $reg_errors['first_name'] = 'Please enter your first name!';
    }
    
    // Check for a last name:
if (preg_match('/^[A-Z \'.-]{2,45}$/i', $_POST['last_name'])) {
        $ln = escape_data($_POST['last_name'], $dbc);
    } else {
        $reg_errors['last_name'] = 'Pleaes enter your last name';
    }
    
    // Check for a username:
if (preg_match('/^[A-Z0-9]{2,45}$/i', $_POST['username'])) {
        $u = escape_data($_POST['username'], $dbc);
    } else {
        $reg_errors['username'] = 'Please enter a desired name using only letters and numbers!';
    }
    
    // Check for an email address:
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === $_POST['email']) {
        $e = escape_data($_POST['email'], $dbc);
    } else {
        $reg_errors['email'] = 'Please enter a valid email address!';
    }
    
    // Check for a password and match against the confirmed password:
if (preg_match('/^(\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,}$/', $_POST['pass1']) ) {
        if ($_POST['pass1'] === $_POST['pass2']) {
            $p = $_POST['pass1'];
        } else {
            $reg_errors['pass2'] = 'Your password did not match the confirmed password!';
        }
    } else {
        $reg_errors['pass1'] = 'Please enter a valid password!';
    }
    
    if (empty($reg_errors)) {
        $q = "SELECT email, username FROM users WHERE email='$e' OR username='$u'";
        $r = mysqli_query($dbc, $q);
        $rows = mysqli_num_rows($r);
        if ($rows === 0) {
            include('./includes/lib/password.php');
            $q = "INSERT INTO users (username, email, pass, first_name, last_name, date_expires) VALUES ('$u', '$e', '" . password_hash($p, PASSWORD_BCRYPT) .  "', '$fn', '$ln', ADDDATE(NOW(), INTERVAL 12 MONTH) )";
            $r = mysqli_query($dbc, $q);
            
            if (mysqli_affected_rows($dbc) === 1) {
                echo '<div class="alert alert-success"><h3>Thanks!</h3>
                <p>Thank you for registering!</p></div>';
                $body = "Thank you for registering with Summit Learning and Technologies";
                mail($_POST['email'], 'Registration Confirmation', $body, 'From:  admin@summitlt.com');
                include('./includes/footer.html');
                exit();
            } else {
                trigger_error('You could not be registered due to a system error.  We apologize for any inconvenience.  We will correct the error ASAP.');
            }
            
            if ($rows === 2) {
                $reg_errors['email'] = 'This email address has already been registered.  If you have forgotten your password, use the left to have your password sent to you.';
                $reg_errors['username'] = 'This username has already been registered.  Please try another.';
            } else {
                $row = mysqli_fetch_array($r, MYSQLI_NUM);
                if( ($row[0] === $_POST['email']) && ($row[1] === $_POST['username'])) {
                    $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';
                    $reg_errors['username'] = 'This username has already been registered with this email address. If you have forgotten your password, use the link at left to have your password sent to you.';
                } elseif ($row[0] === $_POST['email']) {
                    $reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link at left to have your password sent to you.';
                } elseif ($row[1] === $_POST['username']) {
                    $reg_errors['username'] = 'This username has already been registered. Please try another.';
                }
            }
        }
    }
}
?>
 
<h1>Register</h1>
 
<form action="register.php" method="post" accept-charset="utf-8">
<?php 
create_form_input('first_name', 'text', 'First Name', $reg_errors); 
create_form_input('last_name', 'text', 'Last Name', $reg_errors); 
create_form_input('username', 'text', 'Desired Username', $reg_errors); 
echo '<span class="help-block">Only letters and numbers are allowed.</span>';
create_form_input('email', 'email', 'Email Address', $reg_errors); 
create_form_input('pass1', 'password', 'Password', $reg_errors);
echo '<span class="help-block">Must be at least 6 characters long, with at least one lowercase letter, one uppercase letter, and one number.</span>';
create_form_input('pass2', 'password', 'Confirm Password', $reg_errors); 
?>
<input type="submit" name="submit_button" value="Next →" id="submit_button" class="btn btn-default" />
</form>
<br>
<?php // Include the HTML footer:
include('./includes/footer.html');
?>
Link to comment
Share on other sites

form_functions.inc.php

 

<?php
function create_form_input($name, $type, $label = '', $errors = array(), $options = array()) {
 
// Assume no value already exists:
$value = false;
 
// Check for a value in POST:
if (isset($_POST[$name])) $value = $_POST[$name];
 
// Strip slashes if Magic Quotes is enabled:
if ($value && get_magic_quotes_gpc()) $value = stripslashes($value);
 
// Start the DIV:
echo '<div class="form-group';
 
// Add a class if an error exists:
if (array_key_exists($name, $errors)) echo ' has-error';
 
// Complete the DIV:
echo '">';
 
// Create the LABEL, if one was provided:
if (!empty($label)) echo '<label for="' . $name . '" class="control-label">' . $label . '</label>';
 
// Conditional to determine what kind of element to create:
if ( ($type === 'text') || ($type === 'password') || ($type === 'email')) {
 
// Start creating the input:
echo '<input type="' . $type . '" name="' . $name . '" id="' . $name . '" class="form-control"';
 
// Add the value to the input:
if ($value) echo ' value="' . htmlspecialchars($value) . '"';
 
// Check for additional options:
if (!empty($options) && is_array($options)) {
foreach ($options as $k => $v) {
echo " $k=\"$v\"";
}
}
 
// Complete the element:
echo '>';
 
// Show the error message, if one exists:
if (array_key_exists($name, $errors)) echo '<span class="help-block">' . $errors[$name] . '</span>';
 
} elseif ($type === 'textarea') { // Create a TEXTAREA.
 
// Show the error message above the textarea (if one exists):
if (array_key_exists($name, $errors)) echo '<span class="help-block">' . $errors[$name] . '</span>';
 
// Start creating the textarea:
echo '<textarea name="' . $name . '" id="' . $name . '" class="form-control"';
 
// Check for additional options:
if (!empty($options) && is_array($options)) {
foreach ($options as $k => $v) {
echo " $k=\"$v\"";
}
}
 
// Complete the opening tag:
echo '>';
 
// Add the value to the textarea:
if ($value) echo $value;
 
// Complete the textarea:
echo '</textarea>';
 
} // End of primary IF-ELSE.
 
// Complete the DIV:
echo '</div>';
 
Link to comment
Share on other sites

mysqli.inc.php

 

// Make the connection:
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
 
// Set the character set:
mysqli_set_charset($dbc, 'utf8');
 
// Function for escaping and trimming form data.
// Takes one argument: the data to be treated (string).
// Returns the treated data (string).
function escape_data ($data, $dbc) { 
 
// Strip the slashes if Magic Quotes is on:
if (get_magic_quotes_gpc()) $data = stripslashes($data);
 
// Apply trim() and mysqli_real_escape_string():
return mysqli_real_escape_string ($dbc, trim ($data));
 
} // End of the escape_data() function.
 
// Omit the closing PHP tag to avoid 'headers already sent' errors!
 
The SQL for users
 
-- phpMyAdmin SQL Dump
-- version 3.5.8.2
--
-- Host: localhost
-- Generation Time: Sep 02, 2014 at 02:20 PM
-- Server version: 5.5.38-35.2-log
-- PHP Version: 5.4.23
 
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
 
 
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
 
 
DELIMITER $$
--
-- Procedures
--
DROP PROCEDURE IF EXISTS `add_customer`$$
$$
 
DELIMITER ;
 
-- --------------------------------------------------------
 
--
-- Table structure for table `users`
--
 
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `type` enum('member','admin') NOT NULL DEFAULT 'member',
  `username` varchar(45) NOT NULL,
  `email` varchar(80) NOT NULL,
  `pass` varchar(255) NOT NULL,
  `first_name` varchar(45) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `date_expires` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username_UNIQUE` (`username`),
  UNIQUE KEY `email_UNIQUE` (`email`),
  KEY `login` (`email`,`pass`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
 
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
 
Link to comment
Share on other sites

This is what my error log is currently telling me.  Something on the password.php file.

 

[03-Sep-2014 09:29:28] PHP Parse error:  syntax error, unexpected T_IF in /home4/fryemult/public_html/fryemultimedia/includes/lib/password.php on line 5

 

<?php
 
namespace {
 
if (!defined('PASSWORD_DEFAULT')) {
 
    define('PASSWORD_BCRYPT', 1);
    define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
 
    /**
     * Hash the password using the specified algorithm
     *
     * @param string $password The password to hash
     * @param int    $algo     The algorithm to use (Defined by PASSWORD_* constants)
     * @param array  $options  The options for the algorithm to use
     *
     * @return string|false The hashed password, or false on error.
     */
    function password_hash($password, $algo, array $options = array()) {
        if (!function_exists('crypt')) {
            trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
            return null;
        }
 
Everything on here is copied exactly.
Link to comment
Share on other sites

So if the error is with password.php, then that's where you'll need to start looking. It's very strange to have an error like that in a third-party library. My inclination is that it's the namespace line that's causing the problem.

 

What version of PHP are you using?

Link to comment
Share on other sites

Larry,

 

Loving the book!! Your a genius.. :-)

 

I just wanted to say that in my book (Effortless E-Commerce: second edition) on page 93-94 just before the we create the "IF" to determine whether the email, or username is at fault when validating the script.  Line 127 of your supplied code shows an "ELSE" before the "IF" on line 129, which the book does not. 

 

I checked the books forum for an errata but none exists.  

 

I don't know if this will help anyone, but it did me as my code would not validate the culprit (username, or email, or both). This may help those following along coding by hand?

 

Thanks, and I look forward to buying the Yii book, looks interesting.  

-eon-

Link to comment
Share on other sites

Question:

I have never created a menu system dynamically.  I can not figure out how to hide() the register tab if a user is logged in.  I am unsure where to start in the header file to do so.

 

Near the bottom of the code is where we decide if we should show the log in page within the index page.  I figure I would have to start there, or change the dynamic code to check for this first?  I'm such a newbie... LOL

 

Any help, or ideas would be most appreciated.

 

Thank you,

 

The Code:

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
 
    <title><?php // Use a default page title if one was not provided...
if (isset($page_title)) { 
echo $page_title; 
} else { 
echo 'Knowledge is Power: And It Pays to Know'; 
?></title>
 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 
    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
 
    <!-- Custom styles for this template -->
    <link href="css/sticky-footer-navbar.css" rel="stylesheet">
 
  </head>
  <body>
 
    <!-- Wrap all page content here -->
    <div id="wrap">
 
      <!-- Fixed navbar -->
      <div class="navbar navbar-fixed-top">
        <div class="container">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="index.php">Knowledge is Power</a>
          <div class="nav-collapse collapse">
            <ul class="nav navbar-nav">
            
<?php // Dynamically create header menus...
 
 
// Array of labels and pages (without extensions):
$pages = array (
'Home' => 'index.php',
'About' => '#',
'Contact' => '#',
'Register' => 'register.php' 
);
 
// The page being viewed:
$this_page = basename($_SERVER['PHP_SELF']);
 
// Create each menu item:
foreach ($pages as $k => $v) {
 
// Start the item:
echo '<li';
 
// Add the class if it's the current page:
if ($this_page == $v) echo ' class="active"';
 
// Complete the item:
echo '><a href="' . $v . '">' . $k . '</a></li>
';
 
} // End of FOREACH loop.
 
// Show the user options:
if (isset($_SESSION['user_id'])) {
 
// Show basic user options:
// Includes references to some bonus material discussed in Part Four!
echo '<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Account <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="logout.php">Logout</a></li>
<li><a href="renew.php">Renew</a></li>
<li><a href="change_password.php">Change Password</a></li>
<li><a href="favorites.php">Favorites</a></li>
<li><a href="recommendations.php">Recommendations</a></li>
</ul>
</li>';
 
// Show admin options, if appropriate:
if (isset($_SESSION['user_admin'])) {
echo '<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Admin <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="add_page.php">Add Page</a></li>
<li><a href="add_pdf.php">Add PDF</a></li>
<li><a href="#">Something else here</a></li>
</ul>
</li>';
}
 
} // user_id not set.
 
?>
            </ul>
          </div><!--/.nav-collapse -->
        </div><!--/container-->
      </div><!--/navbar-->
 
      <!-- Begin page content -->
      <div class="container">
 
<div class="row">
 
<div class="col-3">
<h3 class="text-success">Content</h3>
<div class="list-group">
<?php // Dynamically generate the content links:
$q = 'SELECT * FROM categories ORDER BY category';
$r = mysqli_query($dbc, $q);
while (list($id, $category) = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo '<a href="category.php?id=' . $id . '" class="list-group-item" title="' . $category . '">' . htmlspecialchars($category) . '
</a>';
}
?>
 <a href="pdfs.php" class="list-group-item" title="PDFs">PDF Guides
 </a>
</div><!--/list-group-->
 
<?php // Should we show the login form?
if (!isset($_SESSION['user_id'])) {
require('login_form.inc.php');
}
//I figure here is where I could add an (islet($_SESSION['user_id']. hide() or something.  I can't figure it out.
?>
</div><!--/col-3-->
 
 
 <div class="col-9">
<!-- CONTENT -->
Link to comment
Share on other sites

Eon, could you post your question in a new topic, since it's unrelated to this thread?

 

Daniel, very strange that you'd see this in 5.4.23. Just to be safe, I'd make sure you're using the most current version of the password library. 

Link to comment
Share on other sites

 Share

×
×
  • Create New...