Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hi all: I am just starting to work on the pursue for chapter 11 on the register.php file.The instructions say to create a system to guarantee unique usernames in register.php. Before you attempt to create the directory, use PHP to check your list of existing usernames for a match to the just-registered name. If no match is found, thenew name is acceptable. If the username is already in use, the PHP can create an error message requesting a new username.

 

I am needing a new way of thinking - I guess. The lines of code that I added that was not given to me, I placed in bold. I am hoping this will search the directory for the usernames listed...But this is where I get stumped... In the line of code I have written, I am asking it to search the text file for the names that were submitted - thus the scandir() function. How do I write this if statement so that it all makes sense with the rest of the code? and when the directions "before" you create your directory, do they mean that I should have placed my new code up above this line of text:

$dir = '../users/';

$file = $dir . 'users.txt';

Or am I supposed to create a new directory. That really won't make sense to me, because the data is already being stored in a text file as indicated in this line: $file = $dir . 'users.txt';

 

<!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" xml:lang="en" lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<title>Register</title>

<style type="text/css" media="screen">

.error { color: red; }

</style>

</head>

<body>

<h1>Register</h1>

<?php // Script 11.6 - register.php

/* This script registers a user by storing their information in a text file and creating a directory for them. */

 

// Identify the directory and file to use:

$dir = '../users/';

$file = $dir . 'users.txt';

 

if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.

 

$problem = FALSE; // No problems so far.

 

// Check for each value...

if (empty($_POST['username'])) {

$problem = TRUE;

print '<p class="error">Please enter a username!</p>';

}

 

if (empty($_POST['password1'])) {

$problem = TRUE;

print '<p class="error">Please enter a password!</p>';

}

 

if ($_POST['password1'] != $_POST['password2']) {

$problem = TRUE;

print '<p class="error">Your password did not match your confirmed password!</p>';

}

 

if (!$problem) { // If there weren't any problems...

 

if (is_writable($file)) { // Open the file.

 

// Create the data to be written:

$subdir = time() . rand(0, 4596);

$data = $_POST['username'] . "\t" . md5(trim($_POST['password1'])) . "\t" . $subdir . PHP_EOL;

 

// Write the data:

file_put_contents($file, $data, FILE_APPEND | LOCK_EX);

 

// Create the directory:

mkdir ($dir . $subdir);

 

// Print a message:

print '<p>You are now registered!</p>';

 

} else { // Couldn't write to the file.

print '<p class="error">You could not be registered due to a system error.</p>';

}

 

} else { // Forgot a field.

print '<p class="error">Please go back and try again!</p>';

}

 

} else { // Display the form.

 

$search_dir + '.';

$file = scandir($search_dir);

foreach($contents as $item) {

if

}

 

// Leave PHP and display the form:

?>

 

<form action="register.php" method="post">

<p>Username: <input type="text" name="username" size="20" /></p>

<p>Password: <input type="password" name="password1" size="20" /></p>

<p>Confirm Password: <input type="password" name="password2" size="20" /></p>

<input type="submit" name="submit" value="Register" />

</form>

 

<?php } // End of submission IF. ?>

</body>

</html>

Link to post
Share on other sites
  • Replies 64
  • Created
  • Last Reply

Top Posters In This Topic

I think (although I don't have the book, I'm on my phone and its very late ha) that the idea seems to be that you take the forms input and validate that it isn't empty and that the username isn't in use before you try to make them a directory.I don't think you currently do this.

Link to post
Share on other sites

Perhaps I've gone about this all wrong - maybe the code needs to be added in between write the data and the create the directory?

Take a look at my theory below: What are you thoughts? Do you think I may be onto something? If so - How can I put My "english" into "php"

 

// Write the data:

file_put_contents($file, $data, FILE_APPEND | LOCK_EX);

 

//Check to see if the name field has been entered in the text file yet

 

// if statement

If it has been then produce and error message

if it hasn't then continue onto creating the directory

 

// Create the directory:

mkdir ($dir . $subdir);

Link to post
Share on other sites

The text file will contain both user names and text files. Here is something i was toying with- but of course... it's not working.... I have tried multiple others too...

 

 

$count_user = "Select count(*) from profiles where username = '$username'";

 

if (don't know what function to put here!($count_user, 0, "count(*)") != 0)

{

$problem = TRUE;

print '<p class="error">Your name has already been chosen, please choose a different name</p>';

// There's someone else with this.

} else {

Link to post
Share on other sites

Well you can validate the form inputs. Then when you came to writing the data, you'd need to know prior to that process whether the username existed, so you'd need to get the contents of the file and parse it to check. Then depending on the outcome write the data or produce an error as the username already exists.

Link to post
Share on other sites

The form inputs are validated....

 

I can find all sorts of code examples on the internet about how to match the input data with what is stored on the database, but nothing on how to write the code to match it to what is stored in the text field.

 

Based on your last comment, as best as I can comprehend right now, I need to put something like this in... My problem is - I know this syntax isn't correct and I don't know where in the script I should place this.

 

//check the directory for duplicate names

$file = scandir($file);

 

// if the number of rows returned = 0 then the name has not been used and it available.

if (username($name) >= 1) { // already in use?

$error[] ='This name is already in use please try another name.';

}else{

//email is alright and no error

Link to post
Share on other sites

This is what I am finding on line and I am thinking I should put this right after my line item that checks if the username has been submitted: However, this line of code is checking against a database... and I haven't learned that yet, so it's pretty unfamliar code to me. I have no idea what !get_magic_quotes_gpc means! Basically though - I think I need to write something like this only I need to refer it to the text file. Again - if you remember, I can fluently read PHP, but I am just barely learning to write it - so I am struggling.... I am getting lots of practice by taking scripts and modifying them....

/* check they filled in what they supposed to, passwords matched, username

isn't already taken, etc. */

if(!$_POST['uname'] | !$_POST['passwd'] | !$_POST['passwd_again'] | !$_POST['email']) {

die('You didn\'t fill in a required field.');

}

// check if username exists in database.

if(!get_magic_quotes_gpc()) {

$_POST['uname'] = addslashes($_POST['uname']);

}

$name_check = $db_object->query("SELECT username FROM users WHERE username = '".$_POST['uname']."'");

if(DB::isError($name_check)) {

die($name_check->getMessage());

}

$name_checkk = $name_check->numRows();

 

if($name_checkk != 0) {

die('Sorry, the username: '.$_POST['uname'].' is already taken, please pick another one.');

Link to post
Share on other sites

At this stage in your reading this is of absolutely no use to you (sadly). You will meet magic_quotes i'm sure. But ignore them for the moment. This style of PHP is also Object Orientated (OOP), which you won't be able to follow just yet either. so if you see anything like $obj->query or anything like -> you're dealing with OOP so you can ignore it. As for your problem I suggest an approach to this, though there is always alternative ways to program.

 

 

Well after this line

 


if (!$problem) { // If there weren't any problems...

if (is_writable($file)) { // Open the file.

 

You could use this function to get the contents of the txt file.

file_get_contents()

 

Look at this function on the PHP.net to see what it takes as arguments and what it returns. Then from there its a case of searching the string for the username.

Link to post
Share on other sites

Okay - Great! that's just what I was looking for! I didn't know what function to use to call the script. Here's what I've got - only it returned an error. I am thinking it's because of this line here...if $_POST['username'] = $file. You stated I should be searching for the string of the username... I expect file should be replaced with something else.... But what?

 

file_get_contents($file)

if $_POST['username'] = $file {

$problem = TRUE;

print '<p class="error">That username has been taken</p>';

}

Link to post
Share on other sites

If possible remember to tell people what the error is.

Secondly, remember that '=' is an assignment operator not a equality '==' / '===' operator.

 

Also get used to using the php manual its very useful, it shows you what arguments it takes, if there are any optional arguments, what it returns and usually examples of how to use it. http://php.net/manua...et-contents.php

 

Notice that it says here that "except that file_get_contents() returns the file in a string"

 

Essentially your code above is logically and syntactically invalid. You need to use the $_POST['username'] value to see if it exists within the value that is returned from the file_get_contents()

Link to post
Share on other sites

So sorry - my error was this:

 

Parse error: syntax error, unexpected T_IF in C:\xampp\htdocs\register1.php on line 45

 

and I did change the code a little now too:

file_get_contents($file) //Reads the file contents

if ($_POST['username'] == $_POST['username']) {

$problem = TRUE;

print '<p class="error">That username has been taken</p>';

}

Link to post
Share on other sites

the semi colon is missing from the first line.

 

What text editor are you using?

 

 

secondly file_get_contents($file); doesn't do much because you need to assign it to a variable. Then query the variable, which is to say that this line

if ($_POST['username'] == $_POST['username']) {

 

is wrong. Look at what you're checking here, basically its saying is the input i put into the form the same as what i put into the form. Which is always true, a bit like is 1 = 1.

 

So work to get the contents of your file into a variable, then we need to check the input against what's in the txt file.

Link to post
Share on other sites

Okay - I ran the file - no errors. I am looking into what you are saying and when I ran my script, I made sure my text file was empty and entered my name and my made up password and it told me that "that username has already been taken" .. So yes, I see that it is not pulling from the text file. But to be honest.... I have no idea how to get those contents into a variable. I thought they were in one! The $data variable. See how lost I am?

Link to post
Share on other sites

Lets concentrate on just accessing the file first and getting information from it. I suggest you just put a username in it just so you can check that its pulling data from the file.

 


$dir = '../users/';
$file = $dir . 'users.txt';

 

So $file holds the reference to where the text file is.

 

so

file_get_contents($file);

 

Gets all the data.

 

So how would you think that you could get and use the data from the line above?

Link to post
Share on other sites

Look at my last post and lets start there. But think about the if statement here.

 

your asking php if the submitted username from the form is equal to the submitted file location. You are only submitting the username to be the checked. That's all, the file is not posted to the server it is already on the server. And even if you were able to do this, you're not actually using the data from the text file as that is all still in the file_get_contents()

Link to post
Share on other sites

Not exactly.

 

$file = $mydata

 

means all you're doing is assigning $mydata (that doesn't exist) to $file

 

And secondly, if you could get all the data from the text file,

 

if($_POST['username'] == $mydata)

 

would only work if there was only 1 record in the file, because file_get_contents() returns a string. So entry 1 was say 'myusername' then another person registers and their username is 'jonathon', so then file_get_contents() would return 'myusername jonathon' as 1 string, so every other time the check was done it would likely fail.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...