Solved

detect wrong entry php

Posted on 2013-06-28
10
558 Views
Last Modified: 2013-06-30
Hi,

I am sure I have asked this before but I cant find the post.

In a form entry with php, if the user enters a username for examples with anything other than numbers or letters then I want this detected and a messgae to appear along side of the textbox eg invalid entry.

Also if the entry is valid but the username doesnt exist then do i send back the header with a variable eg no username
0
Comment
Question by:jagguy
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 15

Expert Comment

by:Jagadishwor Dulal
ID: 39286083
Use Regular Expression to check username validation:
^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$

Open in new window

You can check using See username availability
http://web.enavu.com/tutorials/checking-username-availability-with-ajax-using-jquery/
http://phpseason.wordpress.com/2013/02/17/live-username-availability-checking-using-ajax-and-jquery/
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39286146
All of us who work in software development have a professional teaching library.  Here are some ways to get yours started!

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39286335
To answer your question

There are essentially two ways of validating user input

1. In browser
2. Server side

Option 1 means writing some javascript code to validate the input and notify the user without posting back to the server

Option 2 you check the values posted back to your server side code

In reality you should do Option 2 on its own or Both - it is not advisable to only validate in browser for various practical and security reasons.

Here is a link that describes how to do this in javascript

Sample javascript numbers / letters validation

To do it on the server you can use a similar method changing the

.match javascript function

For the  PHP preg_match function

To answer the second part of the question you would need to give us more information about your application.

However, bear in mind that the purpose of EE is to assist you in reaching a solution not in writing the solution for you.

Either you need to be able to follow the links provided and from those work out what you need to do (with assistance from EE if required) or consider employing a professional developer who can write the code for you.
0
 

Author Comment

by:jagguy
ID: 39286337
I can test the username for correct entry but to pass back a variable to tell the user "invalid user" I need to do       header("location:home.htm?myvar='invalid user'"); ?

function IsSafe($string)
{
    if(preg_match('/[^a-zA-Z0-9_]/', $string) == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

if (IsSafe($myusername) == 0) {
   // echo "<p>Invalid username</p>";
	header("location:home.html");
}

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39286352
Why?

If you post back the browser is making a request - you can simply just output the form again.

Difficult to advise without know more about the layout of your code.

The other option is to use session variables to store the form data and then redirect to the generation page and pull the values from Session - if they exist.

But all up in the air pending more info from you on how your  code is structured.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:jagguy
ID: 39286507
Here is the html code and how do I display php code when I enter a user name and click button from the form code as below?

I also check the reg entry in a file

	<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
		<tr>
		<form name="form1" method="post" action="checkreg.php">
		<td>
		<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
		<tr>
		<td colspan="3"><strong>Computer Course Login </strong></td>
		</tr>
		
        <tr>
		<td width="78">Username</td>
		<td width="6">:</td>
		<td width="294"><input name="myusername" type="text" id="myusername"></td>
		</tr>
		<tr>
		<td>Password</td>
		<td>:</td>
		<td><input name="mypassword" type="text" id="mypassword"></td>
		</tr>
        
		<tr>
		<td width="78">Firstname</td>
		<td width="6">:</td>
		<td width="294"><input name="myfirstname" type="text" id="myfirstname"></td>
		</tr>
		<tr>
		<td>Surname</td>
		<td>:</td>
		<td><input name="mysurname" type="text" id="mysurname"></td>
		</tr>
        
        <tr>	
		<td>&nbsp;</td>
		<td>&nbsp;</td>
		<td><br /><input type="submit" name="Submit" value="Login"></td>
		</tr>
		</table>
		</td>
		</form>
		</tr>
		</table>

Open in new window

0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 39286581
To enter a php value into the form name your page .php and then output what you need to like so

<?php echo $username;?>

Assuming the $username variable exists

Example

<?php
// Set the username and errorMsg fields to blank so we can use them without
// effect if the form is being used for the first time

$username = '';
$errorMsg = '';

// Check to see if a username as posted back to the form

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

  // If it was save it in username variable
  $username = $_POST['username'];

  // Check if the username is valid
  if (checkUserName()) {

    // If it is redirect here to success page 
    // NB: You might want to do additional form validation here before redirecting

  }
  else {

    // If you get here then there was a problem with the username
    // So create an error message div (or span - depending on your markup)
    // To display after the field

    $errorMsg = '<div class="error">Username does not exist</div>';
  }
}
?>

<!-- Output the field html - if username and errorMsg are blank this will result in an
empty field being output.
If the username check failed then populate the username field with the value entered
(if required - you may not want to do this) - and append the error message to the field.
You might want to use something other than a <div> which is used for illustrative 
purposes -->

<input type="text" name="username" value="<?php echo $username;?>" /><?php echo $errorMsg;?>

Open in new window

The above is just an example you will need to adapt for your specific requirements
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39286584
Most of it is described here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

A regular expression that allows only letters and numbers would look something like this:

/[^A-Z0-9]/i

That regular expression says, "return TRUE if the text contains anything that is not between A-Z or 0-9, and make the test case-insensitive."

Good luck with your project.
0
 

Author Comment

by:jagguy
ID: 39287349
Oh I am to check the form entry in the same file as the form html.
This is where I got it wrong. I only go to another file if all the data checks out .
I just post to the same file which checks the data and I can add an error message easily.

<?php // RAY_EE_register.php
require_once('RAY_EE_config.php');

// WE ASSUME NO ERRORS OCCURRED
$err = NULL;

// WAS EVERYTHING WE NEED POSTED TO THIS SCRIPT?
if ( (!empty($_POST["uid"])) && (!empty($_POST["pwd"])) && (!empty($_POST["vwd"])) )
{
    // YES, WE HAVE THE POSTED DATA. ESCAPE IT FOR USE IN A QUERY
    $uid = mysql_real_escape_string($_POST["uid"]);
    $pwd = mysql_real_escape_string($_POST["pwd"]);
    $vwd = mysql_real_escape_string($_POST["vwd"]);

    // DO THE PASSWORDS MATCH?
    if ($pwd != $vwd) $err .= "<br/>FAIL: CHOOSE AND VERIFY PASSWORDS DO NOT MATCH";

    // DOES THE UID ALREADY EXIST?
    $sql = "SELECT uid FROM EE_userTable WHERE uid = '$uid' LIMIT 1";
    if (!$res= mysql_query($sql)) die( mysql_error() );
    $num = mysql_num_rows($res);
    if ($num) $err .= "<br/>FAIL: UID $uid IS ALREADY TAKEN.  CHOOSE ANOTHER";

    // IF THERE WERE NO ERRORS THAT PREVENT REGISTRATION
    if (!$err)
    {
        // MAKE THE UNIQUE USER KEY
        $uuk = md5($uid . $pwd . rand());
        $sql = "INSERT INTO EE_userTable (uid, pwd, uuk) VALUES ('$uid', '$pwd', '$uuk')";
        if (!$res = mysql_query($sql)) die( mysql_error() );

        // STORE THE USER-ID IN THE SESSION ARRAY
        $_SESSION["uid"] = $uid;

        // IS THE "REMEMBER ME" CHECKBOX SET?
        if (isset($_POST["rme"]))
        {
            remember_me($uuk);
        }

        // REGISTRATION AND LOGIN COMPLETE
        echo "<br/>WELCOME $uid. REGISTRATION COMPLETE.  YOU ARE LOGGED IN.";
        echo "<br/>CLICK <a href=\"/\">HERE</a> TO GO TO THE HOME PAGE";
        die();
    }

    // IF THERE WERE ERRORS
    else
    {
        echo $err;
        echo "<br/>SORRY, REGISTRATION FAILED";
    }
} // END OF FORM PROCESSING - PUT UP THE FORM
?>
<form method="post">
PLEASE REGISTER
<br/>CHOOSE USERNAME: <input name="uid" />
<br/>CHOOSE PASSWORD: <input name="pwd" type="password" />
<br/>VERIFY PASSWORD: <input name="vwd" type="password" />
<br/><input type="checkbox" name="rme" />KEEP ME LOGGED IN (DO NOT CHECK THIS ON A PUBLIC COMPUTER)
<br/><input type="submit" value="REGISTER" />
</form>

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39287857
I just post to the same file which checks the data and I can add an error message easily.
Exactly!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now