Stop PHP from running if a GET variable doesn't exist - php

On my page, the user has a choice of what data to display. I did this simply using a dropdown list and GET parameters. It currently looks like this:
The form:
<form method="get" action="contents.php">
<select name="TutorialBlock">
<option value="tuts1">Block One - Starting</option>
<option value="tuts2">Block Two</option>
<option value="tuts3">Block Three</option>
</select>
<input type="submit">
</form>
The script that loads the data depending what option the user chose:
<?php
$var_value = $_GET['TutorialBlock'];
include '/includes/'.$var_value.'.php';
?>
This works fine, and PHP includes the correct file depending on what option the user chose, the issue is, if the user hasn't chosen an option, PHP just throws up file not found errors, since it is looking for a file which isn't there. Is there a way that I can stop the PHP script from running if the GET parameter is not set?

What you're doing now is causing some serious vulnerabilities. You can never trust user input.
You should be running your $_GET['TutorialBlock'] against a whitelist. Here is an example for you.
$whitelist = array(
'page',
'blockpage',
//....etc
);
if(isset($_GET['TutorialBlock']) && !empty($_GET['TutorialBlock'])) {
// now make sure it's in the whitelist.
if(!in_array($_GET['TutorialBlock'], $whitelist)) {
die('bad page');
} else {
include '/includes/'.$_GET['TutorialBlock'].'.php';
}
} else {
// user didn't select page... do something here..
}
The above is only pseudo code (example), you still need to ensure user input is vaid.

$var_value = isset($_GET['TutorialBlock']) ? $_GET['TutorialBlock'] : false;
if($var_value) {
include '/includes/'.$var_value.'.php';
} else {
// query value wasn't there
exit("TutorialBlock is required");
}
Important
You're vulnerable to directory traversal attacks with your code as is.

if(isset($_GET['TutorialBlock'])) {
$var_value = $_GET['TutorialBlock'];
include '/includes/'.$var_value.'.php';
} else {
//not set
}

Related

Execute Function based on the selection on Drop down list

I am trying to learn php today and I on the part of experimenting. I encountered problem using the drop down list, if and else and the function.
It's seems that its not working. I have no idea how to debug it. What I'm trying to do is that when the user selects "employed", it will simply return a "Do THIS!" text. but if the user selects any of the 3 (self employed, Voluntary member & OFW), it will display "DO THAT!".
It's really simple but i can't get it work, i just started php 6 hours ago. :)
Please help!
<form method="POST">
Salary: <input id="salarytext" type="text" name="salary" onkeypress="return isNumberKey(event)"><br>
Membership Type:
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
<br/>
<input type="submit" />
</form>
<?php
$a = (isset($_POST['salary'])) ? $_POST['salary'] : '';
$b = (isset($_POST['membershiptype'])) ? $_POST['membershiptype'] : '';
function employed () {
if (empty ($a)) {echo "";}
elseif ($a<10000) {$a * 2.0}
elseif ($a<20000) {$a * 2.3}
elseif ($a<30000) {$a * 2.7}
elseif ($a>30000) {$a * 3.0}
}
function sevmofw() {
if (empty ($a)) {echo "";}
elseif ($a<10000) { $a * 1.3}
elseif ($a<20000) { $a * 1.5}
elseif ($a<30000) { $a * 1.8}
elseif ($a>30000) { $a * 2.0}
}
if ( $_POST['membershiptype'] == 'employed' ){employed();
} elseif ( $_POST['membershiptype'] == 'SE' ){sevmofw();
} elseif ( $_POST['membershiptype'] == 'VM' ){sevmofw();
} elseif ( $_POST['membershiptype'] == 'OFW' ){sevmofw();
}
?>
Here's a flowchart of what i'm trying to do.
<select name="membershiptype" method="POST">
<option value="Employed" name="employed">Employed</option>
<option value="SE" name="sevmofw">Self Employed</option>
<option value="VM" name="sevmofw">Voluntary Member</option>
<option value="OFW" name="sevmofw">OFW</option>
</select>
should be
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
and your code should be
if (isset($_POST['membershiptype'])) {
if ( $_POST['membershiptype'] == 'employed' ){
employed();
} elseif ( $_POST['membershiptype'] == 'SE' ){
sevmofv();
}
}
...
I want to add this answer, because there is more potential in this topic and you're learning PHP so all bits add up.
Let's start with the PHP Tag. In your .php files you only need to add <?php once at the top and no close tag ?> at the end. Why? See this SO answer https://stackoverflow.com/a/4499749/2493918 .
Then put all the functions you want to be executed via the select in your script:
<?php
/**
* functions.php
*/
function employed()
{
return 'Employed function called.';
}
function sevmofw()
{
return 'Sevmofw function called.';
}
Note here that I replaced the " quotes with single ' quotes. Why? See this answer here:
https://stackoverflow.com/a/3446286/2493918 .
Then create another .php file containing your form (let's call it form.php):
<?php include 'functions.php'; // include the functions ?>
<!DOCTYPE html>
<html>
<head>
<title>Form Function Test</title>
</head>
<body>
<?php
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset('membershiptype'))
{
// If the requested function exists, call it
if (function_exists($_POST['membershiptype']))
{
$func = $_POST['membershiptype'];
echo $func();
}
}
?>
<form action="" method="POST">
<div>
<label>
Salary: <input id="salarytext" type="text" name="salary" onkeypress="return isNumberKey(event);">
</label>
</div>
<div>
<label>
Membership Type:
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
</label>
</div>
<div>
<input type="submit" name="submit_btn" value="Submit form">
</div>
</form>
</body>
</html>
You see we include the functions into this forms page. This way you separate the functions from the so called view. Now you could include the same functions on other pages as well.
Then if you use PHP inside HTML you need to use both php tags <?php and ?> to separate the php part from the html.
If you submit the form the php part will check if the form was submitted and if the membershiptype is set. Then it continues and checks if the requested function exists. If so, it calls the function and returns the output.
Remember: It's better to return values inside functions and echo them where you want (see the example above).
A good resource to learn about PHP are the docs which can be found here:
For example the function_exists() documentation page http://www.php.net/manual/en/function.function-exists.php .
Try to switch to a PHP Framework as soon as you can. It'll help you immense. I recommend Codeigniter as it has a thorough documentation and a low learning curve. Later you could switch to something like Laravel, but I tell you, that's too soon now.
Good luck learning PHP :-)
Here's the answer for your help request after the question edit:
First of all, I love flow charts too! It's a clean way to plan a project or function.
I see you've used ternary operators. That's great :-)
Ok, so you've got a good idea of what you want to achieve (flowchart). I'll try to point you into the right direction with an example.
According to your flowchart "start" means the "form". This example shows the php part and expects that the form was submitted with the required data:
<?php
// START - Check if all required data was submitted
if ( isset($_POST['salary'], $_POST['membershiptype']))
{
// Get the form data
$salary = $_POST['salary'];
$member_type = $_POST['membershiptype'];
// USER SELECTS EMPLOYED?
$user_employed = ($member_type == 'employed') ? true : false;
// Create the multiplication table
// for the salary calculations
$multiBy = array(
'10000' => 1.3,
'20000' => 1.5,
'30000' => 1.8,
'30001' => 2.0,
'employed' => array(
'10000' => 2,
'20000' => 2.3,
'30000' => 2.7,
'30001' => 3.0,
),
);
// Create the calculation function
function calcSalary($s = 0, $employed = false)
{
// Use global here so you can access the
// $multiBy array from inside this function
// without the need to pass it separately
// like $s and $employed
global $multiBy;
// Check if $s is specified
if (empty($s)) return false;
// Round the $s value to be able to use
// it as key for the $multiBy array
// PHP Documentation: http://php.net/manual/en/function.round.php
$value = round($s, -4);
// Set the multiplication values
$multi = $multiBy;
if ($employed) $multi = $multiBy['employed'];
if ($value > 30000) $value = 30001;
if ($value < 10000) $value = 10000;
// Calculate the salary and return the result
return $s * $multi[$value];
}
// GET SALARY INPUT
// Putting the result in a var so you can process however you like
$calculated_salary = calcSalary($salary, $user_employed);
// END - Print the calculated salary
echo $calculated_salary;
}
else
{
// I guess this is self-explanatory :P
echo 'Please enter all required data and try again.';
}
This is a basic example. If you're going to accept user input (public form) remember to secure the input. With "secure" I mean htmlentities, CSRF (Cross Site Request Forgery), XSS (Cross Site Scripting), Code Injection (also SQL Injection if you're going to use Databases).
Also don't forget error handling e.g. missing form input (like if( ! isset($_POST['field'])) echo 'ERROR: Missing input'; else ...).
Here are some resources related to php security you might find useful:
PHP Functions…
PHP htmlentities()
PHP htmlspecialchars()
PHP strip_tags()
Articles with code examples…
Ned Batchelder: Xss with utf-7
Cross-Site Request Forgeries by Chris Shiflett
and some StackOverflow Questions:
"Why my code vulnerable to xss attack?"
How to prevent SQL injection in PHP?
Have fun reading and happy coding!

Language - automatic and by user

I´m trying to play around with languages and an own Database/CMS structure. I´ve got so far, that the Browserset language is selected. This works well. I know there are better solutions (other domains for each language, i´ve google´d a lot)...with an own added cookie (setcookie) it worked, too.
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$langCookie = $_COOKIE['language'];
if(!empty($langCookie)){
$lang = $_COOKIE['language'];
}
if($lang == en){
//Select from database, got three languages, text (en), textOther1 (otherlang1) and textOther2
}elseif($lang == xy){
//other selecet
}else{
//select if nothing fits
}
My problem at this point is:
How can I let the user choose a language with a select on the page. I want to let the user choose the language by a select...but i can´t get it done to set my cookie as I selected an option...
I know that I have got to reload the page after this (header_location), but I can´t get further...
Any help or tipps for solving this would be very nice.
I think you can use the GET method to sent request to a page, just add the language code as a paramter, then check whether this parameter exists -- if not, take your value as it's now.
You can use this markup for example:
<form id="langForm" action="" method="GET">
<select name="lang" onchange="this.form.submit();">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</form>
Then on-server side you should check if lang parameter exists:
<?php
if( isset( $_GET ) && ! empty( $_GET['lang'] ) ) {
// do something
} else {
// do something else
}
?>
Hope that helps!

Enable/disable div according to guest/user entrance using php and jquery

I want to enable or disable a div according to the session if it starts with an user or a guest. I want to do something like this:
First, i will evaluate if it is user or not by doing this:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
?>
then in jquery, i would like to say:
$('.box').click(function(){ // labBox appears when box is clicked
if(<?php $guest?>)
$("#LabBox").hide();
else
$("#LabBox").show();
});
Question: how can i use my php boolean var $guest to disable or hide some elements of my website?
Do i have to do two distinct php files? one for users and other for guest (e.g, home.php and home_guest.php)?
you could do the alternative such as
<script>
var guest = '<?php echo $guest; ?>';
$('.box').click(function(){ // labBox appears when box is clicked
if(guest === "true") {
$("#LabBox").hide();
} else {
$("#LabBox").show();
}
});
</script>
This would simply allow you to pass the PHP value to a Javascript variable, in order for you to use it within the onClick.
Remember: everything that reaches the client can be manipulated. Therefore, if you send an hidden element (say, an hidden <div>) any tech-savvy user can, and will, easily make them visible.
You MUST perform the checks about the login/guest status in your PHP script, and don't rely on jQuery to assemble the page at client side (hey, after all, the user may have disabled javascript altogether!)
You don't need two pages (eg: home.php and home_guest.php) to render different content based on the user level. Just use appropriately session/cookies and different echos.
Use a hidden input, populated by PHP, which jQuery can grab:
<?php
echo "<input type=hidden id=guestcheck value=$guest/>"
?>
if ("#guestcheck").val()) {
}
I personally like this method because it allows me to check the source when debugging to find out where any errors may be (for instance you can plainly see in the source when viewing the page whether or not GUEST is true)
It depends on contents of those files. If the only difference is visibility of the block, it's more reasonable to do the check inline.
<?php if (isset($_SESSION['idUser'])) { ?>
$('.box').click(function() { $("#LabBox").show(); }
<?php } ?>
Personally I would do it in the HTML rather than the JS file...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$loggedin=true;
} else {
$loggedin=false;
}
?>
Then later on..
<?php if($loggedin===true){?>
<div>User is logged in</div>
<?php }else{?>
<div>Guest is viewing page</div>
<?php }?>
This means that the div for the user is not shown to the guest, whereas your currently solution only hides it from view (user could just use firebug/viewsource!
Why don't you just show/hide your div in the php depended on if they are a guest or not...
So...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
if($guest===true){
echo "<div></div>";
}
else{
//dont echo div
}
?>
PHP / server-side:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
// add #LabBox element from here to avoid junk/hidden elements for guests
}
?>
JQuery / client-side:
$('.box').click(function(){ // labBox appears when box is clicked
if (!<?php echo $guest?> && $('#LabBox').length > 0) {
$('#LabBox').show();
}
});
Then it is critical that any action requested by the user pass the "guest or not?" test before being granted from the server-side.

header('Location: ) in php switch to execute url with onclick function

To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>

How should I handle the case in which a username is already in use?

To practice PHP and MySQL development, I am attempting to create the user registration system for an online chess game.
What are the best practices for:
How I should handle the (likely) possibility that when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values? Should I make a separate SELECT query before the INSERT query?
How to handle varying page titles?($gPageTitle = '...'; require_once 'bgsheader.php'; is rather ugly)
(An excerpt of the code I have written so far is in the history.)
Do a separate SELECT to check whether the username is already in use before attempting to INSERT.
More importantly, I would suggest something like the following structure for the script you're writing. It has a strong separation of presentation logic (e.g. HTML) from your other processing (e.g. validation, database, business logic.) This is one important aspect of the model-view-controller paradigm and is generally considered a best-practice.
<?php
// The default state of the form is incomplete with no errors.
$title = "Registration";
$form_completed = false;
$errors = array();
// If the user is submitting the form ..
if ($_POST) {
// Validate the input.
// This includes checking if the username is taken.
$errors = validate_registration_form($_POST);
// If there are no errors.
if (!count($errors)) {
// Add the user.
add_user($_POST['username'], $_POST['password']);
// The user has completed.
$form_completed = true;
// Optionally you could redirect to another page here.
} else {
// Update the page title.
$title = "Registration, again!"
}
}
?>
<html>
<head>
<title>Great Site: <?= $title ?></title>
<body>
<?php if ($form_complete): ?>
<p>Thanks for registering!</p>
<?php else: ?>
<?php if (count($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit">
</form>
<?php endif; ?>
</body>
</html>
Well, one thing you can do instead of repeating code down near the bottom is this:
if( $result === true ) {
$gPageTitle = 'Registration successful';
$response = <p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>';
} elseif( $result == 'exists' ) {
$gPageTitle = 'Username already taken';
$response = '<p>Someone is already using the username you have chosen. Please try using another one instead.</p>';
} else {
trigger_error('This should never happen');
}
require_once 'bgsheader.php';
echo $response;
require_once 'bgsfooter.php';
Also, you can return false rather than the string 'exists' in the function, not that it makes much difference.
Checking the error number isn't bad, I'm sure that's why it's an included feature. If you really wanted to do something different, you could check if there already is a user by that name by selecting the username. If no result exists, then insert the user, otherwise, give the error.
One thing I like to do with error handling on forms is save all the error strings into an array like $error['username'], $error['email'], etc., and then have it run through the error checking on each input individually to set all the error strings, and then have a function that does something like this:
function error($field)
{
global $error;
if(isset($error[$field]))
{
echo $error[$field];
}
}
and then call that after each field in the form to give error reporting on the form. Of course, the form page must submit to itself, but you could have all the error checking logic in a separate file and do an include if $_POST['whatever'] is set. If your form is formatted in a table or whatever, you could even do something like echo '<tr><td class="error">' . $error[$field] . '</td></tr>, and automatically insert another row directly below the field to hold the error if there is one.
Also, always remember to filter your inputs, even if it should be filtered automatically. Never pass post info directly into a DB without checking it out. I'd also suggest using the specific superglobal variable for the action, like $_POST rather than $_REQUEST, because $_REQUEST contains $_GET, $_POST, and $_COOKIE variables, and someone could feasibly do something strange like submit to the page with ?username=whatever after the page, and then you have both $_POST['username'] and $_GET['username'], and I'm not sure how $_REQUEST would handle that. Probably would make there be a $_REQUEST['username'][0] and $_REQUEST['username'][1].
Also, a bit about the page titles. Don't know if you have it set up like this but you can do something like this in your header:
$pageTitle = "My Website";
if(isset($gPageTitle))
{
$pageTitle .= "- $gPageTitle";
}
echo "<title>$pageTitle</title>";
Which would make the page load normally with "My Website" as the title, and append "- Username already exists" or whatever for "My Website - Username already exists" as the title when $gPageTitle is set.
I think the answer from Mr. Neigyl would require a separate trip to the database, which is not a good idea because it would only add performance overhead to yuor app.
I am not a PHP guru, but I know my way around it, although I don't recall the === operator. == I remember.
You could pass the function call directly into the IF statement.
if (addUser($username, $passwd));
I don't see anything wrong with using the $gPageTitle variable, but you will probably have to declare it "global" first and then use namespaces so you can actually access it within the "header.php" because "header.php" will not know how to address this page's variables.
Although I personally don't like messing with namespaces and I would rather call a function from the "header.php" and pass the page title into it
display_title($pgTitle);
or
display_title("Registration Successfull");
or
$header->display_title("Registration Successfull")
if you like OO style better
Let me know if that helps. :)
You should get into forms and allow your page to redirect to another page where you have there the 'insert username to database'.
Suppose the username entered is in a post variable such as $_POST['username'].
Have your database check where that username exist:
$res = mysql_query("SELECT * FROM table WHERE username='$_POST['username']'") or die(mysql_error());
if(mysql_num_rows($res) > 0) {
echo "Username exists.";
// more code to handle username exist
} else {
// ok here.
}
What is basically done is we check if your table already contains an existing username. mysql_num_rows($res) will return 0 if no username exist.

Categories