New to php. I have a form that is only for members to submit. What php code do I need for the form to check that the email address on the form is found my members database and then its okay to submit the form?
If email address is not in the members database then I want to echo "Only members can submit this form." What php code do I need to connect to database in the form and do the check so I don't get forms submitted from non members?
Thanks
At the top of your php file you could do something like this:
if(isset($_POST['email'])) {
mysql_connect("hostname","username","password");
$result = mysql_query("SELECT * FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'");
if($row = mysql_fetch_array($result)) {
// found email
} else {
// email wasn't found
}
}
Of course you would need to replace the hostname, username and password to correct values, also you should change the users and email in the select query to the name of your table and field.
Here is a dummy form:
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<input type="text" name="email" />
<input type="submit" value="Send" />
</form>
You want to study Mysql query and other mysql functions. The code would basically look like:
$c = mysql_connect( ...);
mysql_select_db( 'database', $c);
$q = mysql_query( "SELECT COUNT(*) FROM users WHERE email = '" .
mysql_real_escape_string( $_POST['email'],$c) . "'");
$row = mysql_fetch_row( $q);
if( $row[0]){
echo "Thanks for submitting...";
} else {
echo "Only members...";
}
This is only brief example which is far from perfection but I think it's good place for you to start.
If someone is a registered member that implies you're very likely using a $_SESSION['id_member'] variable.
This will set the cookie's name that can be seen by the client to 'member'...
if (!headers_sent() && !isset($_SESSION))
{
session_name('member');
}
...then when a user authenticates assign a session variable and their permission...
$_SESSION['member_id'] = $mysql_row['id'];
$_SESSION['member_status'] = $mysql_row['id'];
Here is a status hierarchy that you might use or change but it should be a good point of reference...
10 - Super Admin (only you)
9 - Admin// mid-level admin
8 - Assistant//restrictive admin
7 - Moderator//Don't give this status to any jerks
6 - Premium Member//they gave you money!
5 - Registered Member//normal account status
4 - Frozen Account//not banned but did something wrong, will "thaw"
3 - Unverified Email Address//registered but did not verify email
2 - Unregistered Visitor//human
1 - Good Bots
0 - Banned
Generally first determine how to catch the form...
if ($_SERVER['REQUEST_METHOD']=='GET')
{
}
else if ($_SERVER['REQUEST_METHOD']=='POST')
{
if (isset($_POST['submit_button_name_value'])) {blog_post_ajax_comment();}
}
I add the name="value" attribute/value to submit buttons, why? Have two submit options (preview and publish in example) you may want to have the server trigger one function or the other, VERY simple and valid (X)HTML.
You should check if the variable isset (keep permissions in mind).
Then check if their user permissions are adequate, you can use a simple integer to represent this.
Then wrap the isset and permission if statements around two things, one the form and secondly make sure you use these conditions when PROCESSING the form.
I always test against things to reject and throwing in database query error handling to give you a little extra boost...
//function module_method_ajax_purpose()
function blog_post_ajax_comment()
{
if (!isset($_SESSION['member'])) {http_report('403',__FUNCTION__,'Error: you must be signed in to do that.');}
else if ($_SESSION['member_status']<=4) {http_report('403',__FUNCTION__,'Error: permission denied; your account has been flagged for abuse.');}
else if (flood_control($datetime,'60')!=1) {http_report('403',__FUNCTION__,'Error: you can only post a comment once every X seconds.');}
else if (!isset($_POST['post_form_name_1']) || !isset($_POST['post_form_name_2'])) {http_report('403',__FUNCTION__,'Error: permission denied.');}
else
{
// NOW process
$query1 = "SELECT * FROM table";
$result1 = mysql_query($query1);
if ($result1)
{
//successful, increment query number for further queries
}
else {mysql_error_report($query1,mysql_error(),__FUNCTION__);}
}
Error reporting is VERY powerful, use it for HTTP, JavaScript, PHP and MySQL. You could also benefit from my answer about real-time log reading here: jQueryUI tabs and Firefox: getBBox broken?
Related
***the question has been answered. Here is the solution:
Ok, so I need to address a few things before answering the problem. First, the database is meant to have the numerous security flaws. This is a security class, and I am trying to hack into it on purpose. Then after I hack in, i'm supposed to prevent my own attacks.
Second thing I wish to clear up, is that this is a local database only, and never used by anyone but myself, classmates and instructor.
now for the answer: The first thing I was doing wrong was that the code was supposed to be logged into from the localhost webpage. I was trying to log in from the login.php file.
Second thing, was that I was mixing my mysql * and mysqli * methods. You cannot have multiple versions of the same method in the code.
Thanks to all who posted and for the fast responses.
A brief explanation of the problem:
I have been coding a database for a school project. I have the school database set up correctly, as per the instructor's review. The code I have is supposed to take a user input, check it with a "enrolled" list of students and compare the student ID and passsword to a pre-existing list.
After the check, the code is to start a session based on the student being enrolled. If the student is not enrolled it redirects them to the login page again.
The trouble I am having is that the code simply doesn't work. I get a error that says I have an issue on line 35 of my login.php file. Here is my code:
<?php
//Connect to DB
$con=mysql_connect("localhost","root","cravenreach","univ");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Succeed to connect to MySQL. ";
}
//Session setup
session_start();
if( isset($_POST['sid']) && isset($_POST['password']))
{
$checklogin = mysql_query($con, "SELECT * FROM students WHERE sid=".$_POST['sid']." AND password=".$_POST['password']);
echo $count1 = mysql_num_rows($checklogin);
if($count1==1)
{
// auth okay, setup session
$_SESSION['sid'] = $_POST['sid'];
// redirect to required page
header( "Location: main.php" );
}
else {
// didn't auth go back to login
header( "Location: login.php" );
}
}
else {
// username and password not given so go back to login
//header( "Location: login.php" );
//This code is broken, causes a redirect loop.
echo "failure to start";
//header( "location: .php");
}
?>
here is the index.php code:
<html>
<body>
<form action="login.php" method="post">
<p><label>Student ID: <input type="text" name="sid"></label></p>
<p><label> Password: <input type="password" name="password"></label></p>
<input type="submit">
<input type="reset" value="Clear">
</form>
</body>
</html>
The error I receive is this: "Succeed to connect to MySQL. failure to start."
I understand that the code is not evaluating the login as true, and is skipping down to the last else statement. I just dont understand why.
To recap: My code will not actually accept the correct student input (or incorrect for that matter) and will not allow the user to login. It simply throws an error. My question is: what is wrong with my code? Is my query wrong, or implementation of the session?
You need to replace mysql_* functions into mysqli_* and also, You need add " end of the query before )
$checklogin = mysqli_query($con, "SELECT * FROM students WHERE sid='".mysqli_real_escape_string($_POST['sid'])."' AND password='".mysqli_real_escape_string($_POST['password'])."' ");
Your query should be like
//Prevnt from SQL injection
$sid = mysql_real_escape_string($_POST['sid']);
$password = mysql_real_escape_string($_POST['password']);
checklogin = mysql_query("SELECT * FROM students WHERE sid='$sid' AND password='$password'",$con);
Note MySQL is deprecated use MySQLi or PDO
I looked all over. I cannot figure this out.
<?php
session_start();
if (!empty($_POST[username]))
{
require_once("connect.php");
// Check if he has the right info.
$query = mysql_query("SELECT * FROM members
WHERE username = '$_POST[username]'
AND password = '$_POST[password]'")
or die ("Error - Couldn't login user.");
$row = mysql_fetch_array($query)
or die ("Error - Couldn't login user.");
if (!empty($row[username])) // he got it.
{
$_SESSION[username] = $row[username];
echo "Welcome $_POST[username]! You've been successfully logged in.";
exit();
}
else // bad info.
{
echo "Error - Couldn't login user.<br /><br />
Please try again.";
exit();
}
if($isadmin["admin"]==1)
{
echo $admin;
}
else
{
}
}
$admin = <<<XYZ
<div id="admintab">
Admin »
<div id="admin">
ADMIN PANEL
<div id="exitadmin">
</div>
<div id="artistline" />
</div>
</div>
XYZ;
?>
I do know that the $admin value is working. I have tested it. Basically, I have a register system. By default, it sets your admin value to '0'. But let's say i want to add an admin. I change the '0' to a '1' via mysql. I want to know how to make php find users with their admin value set to '1' that are in the database (row name: admin), and display the admin panel to them only.
Why have you used
if($isadmin["admin"]==1)
as you have
$row = mysql_fetch_array($query)
so convert
if($isadmin["admin"]==1)
to
if($row["admin"]==1)
you should check the value before insert and select the data and also use
mysql_real_escape_string($_POST['username'])
so that sql injection not apply
You need to change if($isadmin["admin"]==1) to if($row['admin'] == 1) -- you can leave out the == 1 part if 1 & 0 are the only answers as 1 will always be true and 0 will be false.
Obligitarily, I need to mention that storing passwords in your database in plain text is a bad idea, you should be at the very least hashing them before you store them. Something like $password = hash('sha256', $salt.$_POST['password']) at the registration and login stages.
I should also point out that you shouldn't feed naked values into your database with a query, you don't need to worry about password if you're hashing it, but you do if you're not and you need to do username anyway otherwise anyone can run SQL queries in your database:
$username = mysql_real_escape_string($_POST['username'])
Firstly, I am obligated to point out that not filtering $_POST (and $_GET and $_COOKIE and so on) is very dangerous, because of SQL injection. Secondly, the variable $isadmin doesn't magically exist until you've defined it.
I would suggest designing a more capable user group system, but just to answer the question, the variable you want to check is $row["is_admin"], given that is_admin is a valid column in the table. Also, you don't need to do if ($row["is_admin"] == 1) - 1 evaluates to TRUE in PHP.
I'm trying to create a webpage with users and information that can only be accessed by registered users. Is it possible to limit the files an unregistered user can see? If so, how? I already have a MySQL database with a connection in index.php. Here's what I have so far:
<head></head>
<body>
<h3>Signup Here:</h3>
<form method="post" action="userindex.php">
Please enter user name: <input type="text" name="username" value="" /><br />
Please enter password: <input type="password" name="password" value="" />
<br />
<input type="submit" value="Submit"/>
</form>
</body>
<?php
include ("dbroutines.php");
if (isset($_POST['username'])) {
if ($_POST['username']>'' && $_POST['password']>'' ) {
$q="insert into users (Name, Password ) values ('".$_POST['username']."', '".$_POST['password']."')";
echo 'query='.$q;
$conn=db_connect();
$result=$conn->query($q);
echo '<br />xxx'.$conn->error."xxx";
unset($_POST['username']);
unset($_POST['password']);
} else {
echo 'Please enter both username AND password!';
}
}
$q="select Name, Password from users";
$conn=db_connect();
$result=$conn->query($q);
echo 'xxx'.$conn->error."xxx";
if ($result){
echo '<hr />';
for ($count=0; $row=$result->fetch_row(); ++$count ) {
echo $count." Name=".$row[0]." password=".$row[1].'<br />';
}
echo '<b style="color:red;">there are '.$count.' users in your database!'.'</b><hr />';
}
From this, can you specify what kind of user gets access to certain files like the userindex.php?
I think verifying user is not the fool proof solution . You have to keep a token in the Session to remember that this user is registered user. You have to create a common php page , called Security.php where you will put the following code , because a smart user can directly type the URL and reach to your confidential pages. You need to include this page at the top of each php page you want to secure.
if (!isset($_SESSION['AuthId'])) {
header('Location:Login.php');
exit;
}
Yes. Query your database for someone with the given username and password using a query that would look something like this:
select * from users where Name = 'john.doe' and Password = 'hunter2' limit 1
If it yields any rows, the user exists, and you should let them in. If there are no rows, then that combination of username and password is invalid and you should not let them in.
That's the basics, but if you're actually going to put this into production, you'll want to make a few more changes:
Escape the data you're putting in the query appropriately or use prepared queries. As is, your code is vulnerable to an SQL injection attack. Say, for example, I tried to create an account with an apostrophe in the username or password. Your code would break. This could be leveraged for malicious means, too, so you really should patch that up.
The simplest way to patch it up would be to escape everything before you put it into the query, using, say, mysql_real_escape_string. That'll probably work, but even better (since the whole mysql_ family of functions is deprecated) would be to use prepared queries and PDO, as I've shown below.
Hash and salt your passwords so a database compromise (which could happen rather easily if the above vulnerability is left unpatched) will not reveal all the passwords.
Your code might then look like this:
// You'd probably want to put these in a separate configuration file.
$db = new PDO('mysql:dbname=test', 'my_mysql_user', 'hunter2');
// Make any errors throw an exception.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db->prepare('select * from users where Name = :name limit 1');
$query->bindValue(":name", $_POST['username'], PDO::PARAM_STR);
$row = $query->fetch(PDO::FETCH_ASSOC);
if($row === FALSE) {
// User not in the database; don't let them in.
}
$calculatedHash = hash("sha512", $row['PasswordSalt'] . $_POST['password']);
if($calculatedHash === $row['PasswordHash']) {
// Password's right. Let them in.
}else{
// Password's wrong. Keep them out.
}
Further improvements would be to use, say, bcrypt rather than salted SHA-512.
You can put the one extra field in the loggin table name 'Role'.
Each login time. Check if it is Master user,then It can access the more access.
If it is extra user then limited access.
You got my point? Or any Query?
I have made an app in which the scenario is as below:
user can register and that registration information goes to a PHP server and is stored in a MySQL database.
This is my PHP file:
<?php
// Check if he wants to login:
if (!empty($_POST[username]))
{
require_once("connect.php");
// Check if he has the right info.
$query = mysql_query("SELECT * FROM gen_users
WHERE username = '$_POST[username]'
AND password = '$_POST[password]'")
or die ("Error - Couldn't login user.");
$row = mysql_fetch_array($query)
or die ("Error - Couldn't login user.");
if (!empty($row[username])) // he got it.
{
echo "success";
exit();
}
else // bad info.
{
echo "comes in else part";
exit();
}
}
?>
If I enter a username and password that match from MySQL database, then it throws the word "success" to Android class and will go further in the app. I have a display list-view of registered people in my app.
How can I know how many people use my app right now? The people who are logged-in in app are to appear as a green image in a list view and other people are to appear as a red image.
How can I achieve this?
in addition to #GlaciesofPacis answer you can do one of the following:
send a request for the server in intervals and check who's online or not.
you can use a client-server mechanism - which -is much more complicated but much more efficient and elegant - and make the server push to all online clients when some client is now off or on.
i don't really know what your app is supposed to do, but option number 2 - for my opinion - worth the hard work..
links:
intro to socket servers in php
intro to socket servers in java
Try adding a column to your users table regarding logged-in status (tinyint(1) since it's a MySQL table). It will be populated as either 0 (indicating logged out) or 1 (logged in). Upon logging in, the value needs to be set in the database as 1, and within your logout function, set back to 0. This way, you can use something similar to the below (which assumes the use of User objects):
<?php
$users = getUsers();
foreach($users as $user)
{
$display = "";
if($user->isLoggedIn())
{
$display .= '<img src="green.png" alt="Logged In" />';
}
else
{
$display .= '<img src="red.png" alt="Logged Out" />';
}
$display .= $user->getUsername().'<br />';
echo $display;
}
?>
The SQL command to alter your table:
ALTER TABLE gen_users ADD COLUMN loggedin TINYINT(1) DEFAULT 0;
Im starting a sms website and im nearly complete - just one feature i need to add into it and im a but stuck,
Ive got a form that they fill out with their name , number and message and then they click send , that gets sent to another form to proceed with the validation of the message etc,
What i need is to be able to crosslist the number field against a known database list of blacklisted numbers that dont want messages sent to their phone.
This is the checking code at the moment: so if you imagine at the moment there is a button called send and a button called check number.
When you click check number it will either find the number or not , I know its strange having 2 numbers but its the way its built at the moment.
NOW , instead of it saying number not found id like it to enable the send button , I know how to disable it via disabled="disabled" but i dont know how to automate it , Id like the button greyed out when users go to the form , then when this checks the numbers id like it to ungrey the button if the number isnt in the list.
<?php
$con = mysql_connect("localhost","xxx_members","xxxx");
if(!$con)
{
die("could not connect:".mysql_error());
}
mysql_select_db("xxx_number",$con);
$mobile = $_GET['c'];
$count = mysql_num_rows(mysql_query("select * from mobileCheck where number = '".$number."'"));
if($count > 0) {
echo "Number found">";
}else{
echo "Number Not Found">";
}
?>
Any help on this would be appreciated , its starting to drive me up the wall
Thanks
First of all you need to correct your php code that you listed:
if($count > 0) {
echo "1";
}else{
echo "0";
}
Now you need to make and ajax call to the above file when the first button is clicked using JS and collect back the server response, i.e, either 1 or 0. Now you need to do a client side checking of the server response and enable the button dynamically using javascript it the server echoed 1.
number_check.php
<?php
$con = mysql_connect("localhost","xxx_members","xxxx");
if(!$con)
die("could not connect:".mysql_error());
mysql_select_db("xxx_number",$con);
$number = $_POST['number'];
$count = mysql_num_rows(mysql_query("select * from mobileCheck where number = '".$number."'"));
if($count > 0)
{
echo 1;
}else{
echo 0;
}
?>
html:
<input type="text" id="number" value="" />
<input type="button" id="btn_send" value="Send SMS" disabled />
javascript - jQuery:
$.post("number_check.php", { number: $('#number').value},
function(data) {
if (data == '1')
$('#btn_send').disabled = false;
else
$('#btn_send').disabled = true;
});
I'm sorry but I didn't test the solution, but I think this is your answer. You will of course need to test the number with the db on post, because enabling the button is simple and could be a possible flaw, so you cannot rely on disabling the button, it is only for ergonomic purposes.