Yii How to getState() and display the variable - php

Im currently doing login and result are worked fine. However , I wish to get the firstname and lastname of the user from DB.
As I know getState() able to get the variable data from the DB.
Following bellow is the code for login:
$username = $_POST['username'];
$userpass = $_POST['userpass'];
$record=Games::model()->findByAttributes(array('email'=>$username));
if($record===null){
//somethings
}else if($this->checkPassword($record->password,$userpass)){
//somethings
}else
{
$this->_id=$record->id;
$this->_email=$record->email;
Yii::app()->user->setState('id', $record->id);
Yii::app()->user->setState('email', $record->email);
Yii::app()->user->setState('firstname', $record->firstname);
Yii::app()->user->setState('lastname', $record->lastname);
//go to somethings
}
In View
<?php
$username_first = Yii::app()->user->getState('firstname');
$username_last = Yii::app()->user->getState('lastname');
?>
<a href="#" ><?php echo $username_first.' '.$username_last; ?></a>
What is the problem of my code in view ? Any better suggestion to getState() the data I need ?
Updated :
I tried print out in controller ... it worked ... but why view cant ?
print_r(Yii::app()->user->getState('firstname'));

getState() is not dedicated to get variable from database. As Yii's official document defines it:
Returns the value of a variable that is stored in user session.
By setting state you store your variable's value into user session and you can get that value via getState().
As a suggestion, when you use getState(), pass a default value into the second parameter like below:
$email=Yii::app()->user->getState('email',NULL);
if(!is_null($email)) //do something
It is even better to check state before getting it by hasState() like below:
if(Yii::app()->user->hasState('email')){
$email=Yii::app()->getState('email',NULL);
}
Another note is that, it is better to get stored values in Controller and pass them to the view, not getting them in view. Take a look:
Controller
$email=Yii::app()->user->getState('email'); //it is better to check it via has state, and also passing a default value
$this->render('view',array(
'userEmail'=>$email
));
View
<h2><?php echo $email; ?></h2>
UPDATE
There is a condition that you may need to just get stored value into session (by setState()), So you can just do like below in view:
if(Yii::app()->user->hasState('firstname')) { echo Yii::app()->user->getState('firstname'); } //All done

Related

How to store the list of data into session with single line in codeigniter

I want to store the list of data into session with single line and then how to extract that data on view.userData variable contains list of data.I can store the data like below that i know.but instead of writing multiple line can i store with single line.and how can i extract that data to use on view.Thanks in Advance.
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('userdata',$userData['id']);
$this->session->set_userdata('username',$userData['given_name'];
Can I store the data like below?
$this->session->set_userdata('userdata',$userData);
How can use the variable on view like this it is giving nothing
<?php if(!empty($userdata['given_name'])){?>
<li>HI <?php echo $userdata['given_name'];?></li>
<?php }
After reading the Codeigniter User Guide on sessions, where this is explained ( as we all have ), you could do the following...
This is demonstration code which is really good for testing stuff out like this.
The View auth_view.php for want of a better name
<h1> View </h1>
<?php if(!empty($this->session->given_name)){?>
<li>Hi <?= $this->session->given_name;?></li>
<?php }
The Controller
// $userData=$google_oauthV2->userinfo->get();
// Recreate the Array from google_oauthV2
$userData['id'] = 1;
$userData['given_name'] = 'Fred Flintstone';
$this->session->set_userdata($userData); // Save ALL the data from the array
var_dump($this->session->userdata()); // DEBUG- Lets look at what we get!
$data = $this->load->view('auth_view', NULL, true);
echo $data;
Does that help explain the possibilities?
I highly recommend reading the user guide, because I did to get this answer.
This is hard for me to answer as I don't know how the set_userdata() function works, ie will it accept an array.
But you could try:
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('data',$userData);
And on the view page:
<?php if(!empty($data['userData']['given_name'])){?>
<li>HI <?php echo $data['userData']['given_name'];?></li>
If that does not work this is what I would do.
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('userdata',$userData['id']);
$this->session->set_userdata('username',$userData['given_name']);
$_SESSION['data'] = $userData;
And on the view page:
<?php if(!empty($_SESSION['data']['userData']['given_name'])){?>
<li>HI <?php echo $_SESSION['data']['userData']['given_name'];?> </li>
<?php }
Also you are missing a right paren on:
$this->session->set_userdata('username',$userData['given_name'];
in your orginal code.
Yes, you can store data like this:
$this->session->set_userdata('userdata',$userData);
To access it from view, just store the session data into a local variable.
$userData = $_SESSION['userdata'];
then you can use it.
<?php if(!empty($userData['given_name'])){ ?>
<li>HI <?php echo $userData['given_name'];?> </li>
<?php } ?>
NOTE:
To use session in codeigniter you have to load the session library in your controllers.You can load it in constroctor or top of the method where you are going set session.(you don't have to load it to view.)
$this->load->library('session');

PHP Hide id from being shown in a href url

I have two MySQL tables. The first one is for the user's credentials i.e. username, password, business_id (system generated). The second one has the user's profile for multiple entities e.g. business name, location, profile_id and business id (system genrated - the same number for the business_id).
The user can edit the details of their business details i.e. their details in the second table. The business id would be say 'abcdef' and profile id would be say 1234567, if they have a second business profile it would be say 1235879.
In order to edit each profile I would have to have the following URL
Edit Business Profile
For the second one it would be
Edit Business Profile
In turn when the a href is clicked the url in the browser would be edit_profile.php?id=1234567 and for the second one would be edit_profile.php?id=1235879
Would it be possible that instead of having edit_profile.php?id=1234567 and edit_profile.php?id=1235879 in the URL I would have edit_profile.php?id=1234567 and for the second one would be edit_profile.php
I don't want the User to see the id i.e. have only edit_profile.php
Ideally, I would like to use a PHP solution, please.
Yes, it is possible, but not exactly what are you trying to do
Solution #1
Intoduction
First of all, it should work only on users who are currently logged in and are trying to see their profile. The final results to reach is to not display ID in URL if ID is equal to current logged user's ID. It is more common than Solution #2 but if you want to hide all IDs, skip this solution.
Pluses:
There is not too much to change, just add a few more lines for checking current user ID
You can still use <a></a> tags for Edit Business Profile links.
Minuses:
Only current logged user's ID will be hidden in the URL
So what to do...
You probably use sessions to let users remain logged in even if they refreshed the page. You are on the right path, but you should add at least one more element to $_SESSION (Profile identification, so we can call it as profile_id for example).
Assume you are using this login formula:
function check_login($username, $password)
{
// query to find user with these inputs (encrypted password, prepared statements, etc)
if($query->num_rows > 0) // user exists
{
// fetch your query
// ...
session_start();
// set the session probably user is logged
// some return on success (probably redirect)
}
else
{
// some return on false
}
}
Now you should add one more $_SESSION element to save your current profile_id value:
session_start();
// ...
$_SESSION['profile_id'] = $result->profile_id; // <--- THIS IMPLEMENT
// some return on success (probably redirect)
1/2 is done!
Half of the problem is already finished, now all you need to do is compare $_GET input with $_SESSION.
Again, assuming your edit_profile.php file looks like this:
if(isset($_GET['id']) && !empty(trim($_GET['id'])))
{
$profile_id = intval($_GET['id']);
// ...
}
else
{
// probably an error profile id is not defined
}
// rest of the code ...
So now instead of error profile id is not defined we can assign to $profile_id variable index profile_id of superglobal $_SESSION:
else
{
$profile_id = intval($_SESSION['profile_id']);
}
Notice that I am assuming you have condition to reject access to this script, if user is not logged (some condition at the start).
Now your code should work but maybe you are asking the question what if user knows his ID and types it into URL?
So you have two choices:
Let it be as it is
Add condition to check if $_GET['id'] equals to $_SESSION['profile_id'] then redirect to edit_profile.php
Final thoughts...
Maybe if you are generating the list of the users, where the user can edit the others' users profiles including himself's, you want to remove id parameter of the edit_profile.php URL if the user's ID is equal to current ID in fetch loop. You can inspire by this simple function:
function generate_profile_edit_url($id)
{
session_start(); // for the case, you don't have started session yet
return 'Edit Business Profile';
}
Just in every fetch iteration you will use this function, like in the example below:
// ...
echo generate_profile_edit_url($result->profile_id);
// ...
Solution #2
Introduction
This solution will reach to the editing user's profile without any ID parameter in URL. It is designed for situation where user has rights to edit someone else's profile (for example, a moderator or an admin) and you still don't want to have the users' ID in the URL.
Pluses:
No ID parameter in URL needed for all users
Minuses:
you have to change every profile link to little form using POST action without JavaScript knowledge
no more <a></a> links for profile edit, again without JavaScript knowledge
users are still able to get their id if they want to
So what to do...
Firstly, we need to change edit_profile.php file. We have to recieve $_POST data containing target's profile_id.
Like in Solution #1, assume your edit_profile.php looks like:
if(isSet($_GET['id']) && !empty(trim($_GET['id'])))
{
$profile_id = intval($_GET['id']);
// ...
}
else
{
// probably an error profile id is not defined
}
// rest of the code ...
Most of the changes will be just replacing $_GET with $_POST:
if(isSet($_POST['profile_id']) && !empty(trim($_POST['profile_id'])))
{
$profile_id = intval($_POST['profile_id']);
// ...
}
else
{
// probably an error profile id is not defined
}
// rest of the code ...
For this file, it is enough.
Now there is some more work to do if you have a placed profile links in different files. But we can make it easier using one simple function like this:
function get_profile_edit_button($profile_id)
{
$html = '<form action="edit_profile" method="POST">';
$html .= '<input type="hidden" name="profile_id" value="' . intval($profile_id) . '">';
$html .= '<input type="submit" value="Edit Business profile">';
$html .= '</form>';
return $html;
}
The last thing is replace current edit profile links with this function. For example you have fetch loop of users:
// ...
echo 'Edit Business Profile';
// ...
So you will replace this string with your function get_profile_edit_button():
// ...
echo get_profile_edit_button($result->profile_id);
// ...
Final thoughts...
As I mentioned in minuses, profiles' ids cannot be totally hidden. If someone opened Source code of your page, he can see profile_id in hidden form type:
<input type="hidden" name="profile_id" value="1234567">
It is only on you what solution you prefer, but I can recommend you Solution #1. There is nothing bad about having IDs in URL. Stack Overflow has it too as you can see it on questions, answers, comments and users.
Useful resources:
PHP Session Security
PHP form token usage and handling
When logging in, try saving the user ID and business ID inside session.
As for example..
$logged_in = some_logic_stuffs();
if($logged_in){
session_start();
$_SESSION['user_id'] = SOME_ID_FETCHED_FROM_LOGIN_LOGIC;
$_SESSION['business_id'] = SOME_ID_FETCHED_FROM_LOGIN_LOGIC;
}
Now, when user goes to edit_profile.php, do
session_start();
$business_id = $_SESSION['business_id'];
$user_id = $_SESSION['business_id'];
For the login logic, try reading this tutorial:
http://www.formget.com/login-form-in-php/
If the user can edit multiple business profiles, the $_SESSION solutions would not work. You would need to disguise what gets sent to the address bar:
You would need to change your code to POST the data rather than sending it as a GET request.
To do this you could either use JavaScript to fake a form post on the link click, or wrap your link in a form tag and set method="POST".
POST sends the data "behind the scenes" rather than exposing it in the browser. I should add that this would still be visible to anyone wanting to discover your IDs, but it would hide it from the casual user at least.
If you really wanted security, #BobBrown's suggestion to tokenise would be a great way forward. You may find, however, that just hiding the ID from display on-screen is enough. Just make sure your user management system will restrict who can edit a particular business.
Try this
<?php
session_start();
include('dbconnect.php');
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
$userid = $_SESSION['id'];
}
else
{
$_SESSION['id'] = "";
$_SESSION['username'] = "";
}
if($username <> "")
{
$username = 'username';
$userid = 'id';
}
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 900))
{
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
then
<?php
#if the form is set (meaning that the information was submitted then define what the parameters are for each
if(isset($_REQUEST['username']) == TRUE)
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
#make sure there are no blank fields
if($username == "" OR $password == "")
{
echo '<p class="text-danger">Please enter a Username and Password</p>';
}
else
{
$userid = finduser($username, $password);
if($userid > 0)
{
loginuser($userid);
}
else
{
echo '<p class="lead text-danger">The Username and/or Password enter is incorrect</p><br />';
}
}
}
?>
after that then this
<?php
if(isset($_SESSION['username']))
{
if($_SESSION['username'] <> "")
{
//do something
}
else{
//form or something else
?>
<form>form goes here</form>
<p> or something else you want</p>
<?php
}
}
?>
Start your PHP with session_start(); then when the user logs in make a session value for the ID:
$_SESSION['profile-id'] = 1235879; //Select it from database
after in your edit_profile.php do that:
if (!isset($id)) {
$id = $_SESSION['profile-id'];
}
And then edit the $id.
Store the id in session on the first page:
$_SESSION['id'] = 12345;
And on edit_profile.php you can get the value by:
$id = $_SESSION['id'];
And start the session on every page by session_start();
Easiest and simplest way to handle your situation if you want to use Id or any information in URL and pass it through URL
then you can have a scret combination with your values like below
Firt you have to encode the value with your secret stuff for example
$sshhh="ITSMY_SECRET_VALUECODE";
$encrypted_id = base64_encode($your_value . $sshhh);
Then pass it (encrpyted_id) in URL
for example href="all-jvouchers.php?id=<?= $encrypted_id; ?>
and while getting value use below code to get back your value
$sshhh="ITSMY_SECRET_VALUECODE";
$decrypted_id_raw = base64_decode($_GET['id']);
$decrypted_id = preg_replace(sprintf('/%s/', $sshhh), '', $decrypted_id_raw);
Use $decrypted_id wherever and however you want to securely

Do I have an instance of this object?

I keep getting an 'Undefined variable' notice when I call on an object I 'think' I have instantiated, but apparently haven't. I can't put a finger on my the error. The object is $fgmembersite, according to my error messages it doesn't exist, I'm confused about why. It maybe a simple case of me messing up my directories in the include/require portion of my scripts but I've been looking at them and can't see anything wrong. Tell me if you guys want to look at my file hierarchy.
And again thanks for the help!
I have three PHP files that are at play.
First one is login-home.php
<?PHP
require_once("./profile_settings/view.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
?>
/*a bunch of stuff*/
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation(); ?>"></img>
/*a bunch of stuff*/
Next I have view.php which holds a function I use to generate the path-name of where I store my picture.
<?php
include("./include/membersite_config.php");
function fetchAvatarLocation()
{
$user_id = $fgmembersite->UserId();
$query = mysql_query("SELECT * FROM ddmembers WHERE id_user = '$user_id'");
if(mysql_num_rows($query)==0)
die("User not found!");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
return $location;
}
}
?>
And finally I have membersite_config.php
<?PHP
include("fg_membersite.php");
$fgmembersite = new FGMembersite();
//Provide your site name here
$fgmembersite->SetWebsiteName('Mysitename.com');
//Provide the email address where you want to get notifications
$fgmembersite->SetAdminEmail('My.Email#Provider.net');
//Provide your database login details here:
//hostname, user name, password, database name and table name
//note that the script will create the table (for example, fgusers in this case)
//by itself on submitting register.php for the first time
$fgmembersite->InitDB(/*hostname*/'localhost',
/*username*/'user',
/*password*/'password',
/*database name*/'database',
/*table name*/'table');
//For better security. Get a random string from this link: http://tinyurl.com/randstr
// and put it here
$fgmembersite->SetRandomKey('**************');
?>
fg_membersite is a file that contains the class fgmembersite that stores a bunch of functions, the ones that I need it for are...
function UserId()
{
return isset($_SESSION['userid_of_user'])?$_SESSION['userid_of_user']:'';
}
function UserName()
{
return isset($_SESSION['username_of_user'])?$_SESSION['username_of_user']:'';
}
The object is not in the scope of the function, so it is undefined. You need to pass it in as a parameter:
function fetchAvatarLocation( $fgmembersite)
Then call it with the object as a parameter:
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation( $fgmembersite); ?>"></img>
An alternative is to use global variables, but I wouldn't recommend it.

My Codeigniter method for safely deleting database entries

I've been searching about deleting db entries in Codeigniter and I finally created a solution that I think is secure. I would really appreciate any feedback! I'm not sure if I'm doing this right..
Advantages:
Uses POST request
ID of entry to be deleted is
validated
Uses CSRF protection (automatically
generated by Codeigniter)
In my example I'm deleting user submitted links (a DB table row contains a link title, link URL, an link description).
HTML: Database entires are contained within a form. Each entry has a form button with the respective link id in the id attribute.
<?php echo form_open('profile/remove_link'); ?>
<?php echo form_hidden('link_id', ''); //value will be populated via jquery ?>
<ul id="user_links">
<?php foreach($query as $row): ?>
<li><?php echo $row->link_title; ?></li>
<li><?php echo auto_link($row->link_url, 'url', TRUE); ?></li>
<li><?php echo $row->link_description; ?></li>
<button type="submit" class="remove" id="<?php echo $row->link_id ?>" value="remove">Remove Link</button>
<?php endforeach; ?>
</ul>
</form>
JQUERY: When user clicks on the remove button, the respective link id is added to the the hidden text input named link_id.
$(document).ready(function(){
$('.remove').click(function() {
var link_to_remove = $(this).attr("id");
$("input[name=link_id]").val(link_to_remove);
});
});
Upon clicking a remove button, it sends the id of link to be removed to controller profile and function remove_link
function remove_link()
{
$this->load->model('Profile_model');
$links_data['query'] = $this->Profile_model->links_read(); //get links from db to add in view
//Validation
$this->form_validation->set_rules('link_id', 'Link ID', 'trim|required|xss_clean|max_length[11]|numeric'); //validate link id
if ($this->form_validation->run() == FALSE) //if validation rules fail
{
$this->load->view('profile/edit_links_view', $links_data);
}
else //success
{
$link_id = $this->input->post('link_id'); //get id of link to be deleted
$seg = 'user_links'; //used to redirect back to user links page
$this->Profile_model->links_delete($link_id, $seg); //send link id to model function
}
}
MODEL
function links_delete($link_id, $seg)
{
$this->db->where('user_id', $this->tank_auth->get_user_id());
$this->db->where('link_id', $link_id);
$this->db->delete('user_links');
redirect("/profile/$seg/");
}
If the ids are unique integers in your database, you could remove these rules:
trim|xss_clean|numeric
And add this one:
is_natural_no_zero
Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.
The numeric rule allows some characters you probably don't want, like decimals and negative. Here's the source (one line):
return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
If for some reason you are echo'ing the input back in your HTML output before validating, or are just paranoid, then by all means: xss_clean it up. Otherwise it's not really needed, as I don't think there's any possible method of XSS attacks that only use a number.
Reference:
https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
http://ha.ckers.org/xss.html
Also, you might want to add a LIMIT 1 clause to your query, and definitely make sure to return a value (probably TRUE/FALSE) from your model so you know whether or not the query was successful, so you can give feedback to the user instead of assuming everything went well.
The only thing that I see wrong is that you don't validate who can and can't delete records. That's the only issue you should focus on. Permissions to check if the person sending the request of deletion is allowed to perform such operations. Other than that it's just a matter of preference.
I would suggest rewriting controller and model a bit to make the flow more logical and provide better performance:
controller:
function remove_link()
{
if ($this->input->post('link_id'))
{
//Validation
$this->form_validation->set_rules('link_id', 'Link ID', 'is_natural_no_zero');
if ($this->form_validation->run())
{
$seg = 'user_links'; //do you really need to assign it to variable ??
$this->load->model('Profile_model');
if ($this->Profile_model->links_delete($this->input->post('link_id')) //send link id to model function
{
redirect('/profile/user_links'); // redirect user in controller and only when model returns true
}else{
// inform user about error somehow, eg. by setting session flashdata and redirecting back to /profile/user_links
}
}
} // else statement here was a mistake as in case of form_validation failure nothing happened
$this->load->model('Profile_model');
$links_data['query'] = $this->Profile_model->links_read(); //get links from db to add in view
$this->load->view('profile/edit_links_view', $links_data);
}
model:
function links_delete($link_id)
{
$this->db->where('user_id', $this->tank_auth->get_user_id())
->where('link_id', $link_id)
->delete('user_links'); // you can chain methods without writing always $this->db->
return $this->db->affected_rows(); // returns 1 ( == true) if successfuly deleted
}
And as a side note in your jQuery code I suggest using $('#some_id') instead of $('input[name=XXXX]') - it saves some javascript code execution thus is faster

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