Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

detect wrong entry php

Posted on 2013-06-28
10
Medium Priority
?
596 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 111

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 59

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
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 

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 59

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
 

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 59

Accepted Solution

by:
Julian Hansen earned 1000 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 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 59

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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

662 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