Sessions in php do not load profiles, php + mysql - php

I need to be able to orientate with a php code that communicates with data from a mysql database, this file is called "validate.php". Its main functions are to verify that there are no empty fields at the time of login, and assign a profile if a user has value 1 and another profile when the value is 0 in the records of the table "users"
The idea is that "validate.php" check the user and direct it to a page according to their profile, but I can not do that.
My code is:
<?php
require('access_db.php');
session_start();
if(isset($_POST['send'])) { // We verify that the form data has been sent
//We verify that the user_name and the user_pass fields are not empty
if(empty($_POST['user_name']) || empty($_POST['user_pass'])) {
echo"
<script>
alert('Please enter your username and password correctly ');
location.replace('login.php');
</script>
";
}else {
//"Clean" the form fields of possible malicious code
$user_name = mysqli_real_escape_string($link,trim($_POST['user_name']));
$user_pass = mysqli_real_escape_string($link,trim($_POST['user_pass']));
// We verify that the data entered in the form match those of the DB
$query=mysqli_query($link,"select user_id,user_name,user_admin FROM users WHERE user_name='".$user_name."' and user_pass ='".$user_pass."'");
$row = mysqli_fetch_array($query);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row["user_name"];
$_SESSION['user_admin'] = $row["user_admin"];
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
{
}
}else{
header("Location: login.php");
}?>
My main problem is here:
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
When I login with my admin user in my page "login.php" you should check the information and go to a page according to your profile, only appears in the browser "http://localhost/proyect/validate.php" and the text "dashboard" on the page, But, if I write in the browser "http://localhost/proyect/dashboard.php" load the page with all the information.
I do not know what I'm doing wrong.
Someone can help me, I'll be very grateful, I've been on this for days.
Thanks.

Don't print, try this instead:
if($_SESSION['user_admin']==1){
header('location:dashboard.php');
exit;
}else{
header('location:dashboard2.php');
exit;
}
Thanks for the suggestion Magnus Eriksson

you need to redirect not echo out the contents of the php file
and also do check for { as there are extra ones
if($_SESSION['user_admin']==1){
header("Location: dashboard.php");
}else{
header("Location: dashboard2.php");
}

Related

Redirect page after delete account in php

I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help

Check role of user logged in (PHP)

first, I have searched for a question that is the same with mine, unfortunately I can't understand the answers. It says use Auth, etc... bla bla bla. I only know basics so far.
So here is my question: how to check the user currently logged in and its role?
I thought I could do it so easily, actually I did, but the user of the site I'm building should only be one. lol. I have two columns named session and membership. Anyway, my code is written below (It is definitely wrong, I just realized it this 2AM in the morning. It would 100% work if the user of the side is again only one.
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
header("Location: http://localhost/se/");
}
//if(!empty($_SESSION['user']) )
else
{
//This following codes are for checking the session in DB
$query = "
SELECT
id,
password,
emailAddress,
membership
FROM memberlist
WHERE
session = :var_val
";
// The parameter values
$query_params = array(
':var_val' => 'True'
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if ( $row['membership'] == 'Officer' || $row['membership'] == 'Member' )
{
header("Location: http://localhost/memberdir/index.php");
}
}
If a user's membership == 1, then go to admin directory.
else go to members directory.
Please help :(
To start a user session:
session_start();
To add parameters to that session:
$_SESSION['parameter'] = $parameter;
To get that parameter:
$getParameter = $_SESSION['parameter'];
So make sure you put session_start(); before any output to the page (before you print anything):
if ( $row['membership'] == 'Officer' || $row['membership'] == 'Member' )
{
session_start();
$_SESSION['membership'] = $row['membership'];
include('memberdir/index.php');
//or header("Location: http://localhost/memberdir/index.php");
}
So in your member file that you show a particular user (or only one user, doesn't make a difference), you check that the session parameter exists and what to do with it:
if (isset($_SESSION['membership'])) {
//membership parameter is set
if($_SESSION['membership'] == 'Officer') {
echo "Hey, your membership is Officer, here is your page";
} else if ($_SESSION['membership'] == 'Member') {
echo "Hey your membership is Member, here is your page";
}
}
This should help you understand the basics and you can go from there.
when the user login success you can do like this:
if(login success)
{
$_SESSION['user']=array('id'=>$id,
'emailAddress'=>$emailAddress,
'membership'=>$membership);//the three values are selected from database when login in
}else
{
// do some thing
}
then when you check the user ,you can use:
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
header("Location: http://localhost/se/");
}else
{
//get user info from session
}

Clearing the cookie programmatically

I have a login page called signin.php where a user can enter an email and password. On clicking submit button, page directs to connection_validate.php. This page validates the user entered data with database. If it's a registered user, the page directs to calendar.php. If the entered data is incorrect, it should redirect to signin.php. If the entered data is incorrect, I have placed cookie like this:
//action to be done if e mail id and password matches with database records
if(mysql_num_rows($result)>0)
{
header('location:calendar.php');
}
//action to be done if e mail id and password does not matches with database records
else
{
setcookie('message','incorrect login data');
header('location:signin.php');
}
In signin.php, I have written the code for displaying an alert if login information is incorrect like this:
<?php
include("include/minfooter.php");
if(isset($_COOKIE["message"]))
{
if(!($_COOKIE["message"]==" "))
{
echo "<script>
alert('Incorrect login information');
</script>";
setcookie("message"," ",time()-3600);
}
}
?>
My issue is that alert is displaying each time when I load the signin page if I have entered a error login data once. If I press the back button from the calendar.php to signin.php also, alert starts showing. I understood that the problem is with cookie. Cookie has not been removed. How can I solve this issue?
Update your signin.php as follows
<?php
include("include/minfooter.php");
if (isset($_COOKIE["message"]))
{
echo "<script>
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
var msg = '" . $_COOKIE["message"] . "';
if (msg != '')
alert('Incorrect login information');
delete_cookie('message');
</script>";
}
?>
If you are using a session you can use the $_SESSION variable instead of a cookie value. Also you can not use setcookie() AFTER you have output content since setcookie() will send an HTTP header which must be sent prior to any content being sent.
session_start();
//action to be done if email id and password matches with database records
if (mysql_num_rows($result) > 0)
{
header('Location: calendar.php');
exit;
}
//action to be done if email id and password does not matches with database records
else
{
$_SESSION['message'] = 'incorrect login data';
header('Location: signin.php');
exit;
}
Then:
<?php
session_start();
include("include/minfooter.php");
if (!empty($_SESSION['message']))
{
echo "<script>alert('" . $_SESSION["message"] . "');</script>";
$_SESSION['message'] = '';
}
?>
Ok maybe is better to use session for that use a index ['messages'] on the $_SESSION array, then cleanup, the cookie should be used when you want reference some info after the user get out of your page. I made your code on using cookies, but consider using session:
<?php include("include/minfooter.php");
if(isset($_COOKIE["message"]) && !empty($_COOKIE["message"])
{
echo "<script>
var msg = '<?php echo $_COOKIE["message"];?>';
if (msg != "")
alert('Incorrect login information');
</script>";
unset($_COOKIE["message"]);
}
?>

Refresh button on Browser

I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!
Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference
It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.
You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}
Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.

Make a div visible from an outside php

I'm working on a log in session, and I want to display errors on the same page, for example - "Invalid Password" or "User does not exist".
Heres my code:
<?php
session_start();
mysql_connect('mysql.database.com','user','database')or die ('Connection Failed: '.mysql_error());
mysql_select_db('database')or die ('Error when selecting Database: '.mysql_error());
function remove($mensaje)
{
$nopermitidos = array("'",'\\','<','>',"\"");
$mensaje = str_replace($nopermitidos, "", $mensaje);
return $mensaje;
}
if(trim($_POST["usuario"]) != "" && trim($_POST["password"]) != "")
{
$usuario = strtolower(htmlentities($_POST["usuario"], ENT_QUOTES));
$password = $_POST["password"];
$result = mysql_query('SELECT password, usuario FROM usuarios WHERE usuario=\''.$usuario.'\'');
if($row = mysql_fetch_array($result)){
if($row["password"] == $password){
$_SESSION["k_username"] = $row['usuario'];
header( 'Location: diseno.php' ) ;
}else{
echo '<p class="message2">Invalid password</p>';
}
}else{
echo '<p class="message2"User does not exist</p>';
}
mysql_free_result($result);
}else{
echo '<p class="message2">Must enter a user and password</p>';
}
mysql_close();
?>
<SCRIPT LANGUAGE="javascript">
location.href = "index.php";
</SCRIPT>
As you can see that's my validation and action for the log in form. Instead of echoing errors in a new page I want to display it in the same page. I tried with javascript and it didn't work I used.
var page = document.URL = "http://www.mysite.com/login.php"
page.getElementById( 'wrongpassword' ).style.display = 'block';
All divs I want to display are set as none in the login.php file.
Anyone could help me?
The easiest way to accomplish this is to process the login and then include the PHP code which displays the normal page. I'm not sure how you've designed your site, but including index.php at the end might do the trick. Right now, you are using a JS redirect, which won't give you the result that you want.
Instead of echoing the message, I like to set a $message variable which includes the message. When you render the main page, simply echo this variable in the appropriate place if it is set.
For doing it simply you can make use of JQuery. I have done it on my website so I can say it really works.
Start your session, checking the values and either assign the value in global variables of javascript or print it there only
eg.
<?php
session_start();
//checking ur values
echo "<script src=\"js/jquery-1.8.3.min.js\"></script>
<script type=\"text/javascript\">
$(document).ready(function(){
//you can assign values here or print error messages to any div
('.div_class').html("unuthorised user");
});
</script>";
?>
Here I have used a downloaded JQuery file from
http://jquery.com/download/
You can choose other wise to use the online version of this JQuery file. The syntax for that is
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
Feel free to get back in case of any further query/issues regarding the above code.

Categories