I am trying to create a logout page using session_destroy() but all i get is a blank page.
This is my code about logging in(I assume the problem has to be somewhere here but i am a beginner at this).
What i thought it will work is creating a session for the username since it is used at isset() but apparently its not working.
<?php
session_start();
$dbhost = "";
$dbuser = "";
$dbpassword = '';
$db= 'system_dev';
mysql_connect($dbhost,$dbuser,$dbpassword);
mysql_select_db($db);
include 'test.php';
if (isset($_POST['username'] )) {
$username=$_POST['username'];
$password=$_POST['password'];
$_SESSION['username']=$username;
$sql ="Select * FROM Company WHERE username='".$username."'AND password = '".$password."'LIMIT 1";
$sqlid = "Select CompanyId FROM Company WHERE username='".$username."'";
$result = mysql_query($sql);
$resultid= mysql_query($sqlid) or die('Query failed: '. mysql_error());
while ($row =mysql_fetch_array($resultid,MYSQL_ASSOC) ) {
echo "<tr>\n";
foreach ($row as $col_value){
echo "$col_value\n";
}
}
$company = mysql_free_result($resultid);
$_SESSION['CompanyId'] = $col_value;
}
if ( mysql_num_rows ($result)==1){
header ("Location: webdesign.php");
exit();
}
else {
echo "Invalid input";
exit();
}
?>
On the code of "logout.php" I have only written this:
<?php
session_start();
session_destroy();
header ("website.php");
?>
Thanks in advance and sorry if the answer is not how it should be. I have read the rules but this is the 2nd post so far. I believe i will get better someday :)
You should use Location in your header argument like header("Location: page.php");
you can place this header after you destroyed the session, that should not give any problems.
As Dorco said:
You should use Location in your header
So the logout function should looks like this:
session_destroy();
session_regenerate_id(TRUE);
header("Location: login.php");
die();
And I strongly suggest you, so not simply insert the post value into the SQL query. That will cause a SQL injection. Use prepare statement instead. PHP: Prepared Statement
Related
I Have Solve The Problem From The Code But Now It Should Return The Array From The User_level But It Return In blank any idea from the error please
<?php
$user_level = $_GET['user_level'];
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user'])){
header("Location: index.php");
}
$res=mysql_query("SELECT user_level FROM users where user=".$_SESSION['user']);
while($rows=mysql_fetch_array($res)){
echo $rows['user_level'];
// close while loop
}
die();
?>
Hi hello I have perform this code but it seems to have an error can some one help me with please.
The error is
A página de bitcoinrotator.publiadds.org.pt is not working
bitcoinrotator.publiadds.org.pt can not process this request for time. 500
The Code is
<?php
$user_level = $row['user_level'];
$user_level = $_GET['user_level'];
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user'])) //if he isnt logged in
{
header("Location: index.php");
}
$res=mysql_query("SELECT user_level FROM users where user=".$_SESSION['user']);
$rows=mysql_fetch_array($res);
echo $user_level;
echo $rows['user_level'];
}
}
?>
You have a syntax error in your brackets and the way that you are getting your information. You have, first, leed of use mysql becasue this extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. Returning at your problem. Try this (Changes are commented):
<?php
session_start(); //put your session at the top
require_once 'dbconnect.php'; //not include_once, just require once
$user_level = $_GET['user_level'];
if(!isset($_SESSION['user'])) //if he isnt logged in
{
header("Location: index.php");
} //you are finish the if statement
else //you have to create an else of your if for determinate if your setence if is not complete or not true
{
//You have an error too in $_SESSION['user']. You have to close in " " or ' ' and use it after in your query. Also and in this example, we will save $_SESSION['user'] in a variable $user.
$user = $_SESSION['user'];
$res = mysql_query("SELECT user_level FROM users where user='$user' ");
//At this point, we will going to create a while for extract information of the query
while ($rows = mysql_fetch_array($res, MYSQL_NUM)) {
echo $user_level;
echo $rows['user_level'];
}
?>
Well I Finish To Discovery The Way To Do With A friend
There It is The Solution For
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
echo "You are not logged in.";
}else{
}
$res=mysql_query("SELECT user_level FROM users where user_id=".$_SESSION['user'])or die("We didnt did a sql query".mysql_error());
$rows=mysql_fetch_array($res);
$user_level = $rows['user_level'];
echo $user_level;
?>
Tanks For The Help
I'm trying to show welcome message with user name. I have a session setted up, everything is working without errors, however I can't make user name appear next to "welcome". I read loads of posts, most of the suggestions were asking to add session_start(); before echo. Still nothing..
Here is code for session.php if someone could help me:
<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("**.***.***.***", "*********", "*********");
mysql_select_db("*********",$conn);
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["user_name"])) {
header('Location: login.php');
}
?>
And here is code for the profile page where user name should appear:
<?php
include('session.php'); //file shown above
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i>
<?php
session_start();
echo $_SESSION['fname'];
?>
</i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
I'm just learning PHP and this is a basic test.
Thank You for any information.
Hava a nice day !
UPDATE:
loginscript.php
<?php
session_start();
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['uname']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$uname=$_POST['uname'];
$password=$_POST['password'];
$conn = mysql_connect("**.***.***.***", "*********", "*********");
$uname = stripslashes($uname);
$password = stripslashes($password);
$uname = mysql_real_escape_string($uname);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("*********", $conn);
$query = mysql_query("select * from WebsiteUsers where password='$password' AND uname='$uname'", $conn);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$uname;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
mysql_close($conn);
}
}
?>
logout.php:
<?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>
You need to quote your array keys, for example you have:
$_SESSION["UserID"] = $row[user_id];
But this should in fact be
$_SESSION["UserID"] = $row['user_id'];
Note the single quotes around the array key in $row. I see you use double quotes and I think there are minor differences but the point is, use quotes around array key strings. Please read https://stackoverflow.com/a/2317969/3536236 .
There also might be an issue that you set the value with double quotes and then call the value with single quotes --
$_SESSION["fname"] = $row['fname'];
print $_SESSION['fname'];
But that's just a theory there.
Further debugging:
Print_r($_SESSION); <== what does this give you after the values are set?
Use MySQLi or PDO rather than MySQL_ as this is now deprecated and should no longer be used.
Add exit; after your header relocation calls. Because the rest of the script will still execute before the relocation header call is run, so you need to tell the script to stop executing as soon as you reach the header(location: ) point.
Be consistent and have all single ' or all double " quotes in your array key identifiers.
Remove session_start() from inside your HTML, this function call MUST be at the very start/ top of the page, and nowhere else. You can replace this session_Start with the print_r referenced above, for debugging purposes.
Debugging
First step, you need to enable errors on your page, so whatever page you're working on add this code to the top:
error_reporting(E_ALL);
ini_set('display_errors', 1);
This will output any errors the code fines to your browser when you run the page. Extremely useful and informative.
Next, I will show you the process you need to establish where in the logic chain the data is being "lost".
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
print_r($result) <== should return something like "this is a type 4 element". False shows your DB is empty or your MySQL code is bad.
$row = mysql_fetch_array($result);
var_dump($row) <== should return the values from the DB. It should also tell you what data type this variable is, as you demand an array, below:
if(is_array($row)) {
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
}
else {
die("This will display if the IF statement does not show TRUE.");
}
The die statement above would show you that the error is not in the session but more in your handling of the MySQL output,
I reaffirm you should use single quotes on all your array keys everywhere! Keep it consistent!!
Restructure your MySQL to be more this shape:
mysql_query($query) or print_r("line ".__LINE__.": ".mysql_error());
So that if there is any issue with your MySQL code it is found and shown to you. Much of programming is about finding where the error comes from, rather than the error itself.
Try something like this:
$db_result = mysql_fetch_array($result); $row = $db_result[0];
instead of :
$row = mysql_fetch_array($result);
<?php
session_start();
$message="";
if(count($_POST)>0) {
$conn = mysql_connect("**.***.***.***", "*********", "*********");
mysql_select_db("*********",$conn);
$result = mysql_query("SELECT * FROM WebsiteUsers WHERE user_name='" . $_POST["fname"] . "' and password = '". $_POST["password"]."'");
if(mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
$_SESSION["UserID"] = $row[user_id];
$_SESSION["fname"] = $row[user_name];
} else {
$message = "Invalid Username or Password!";
}
}
if($_SESSION["fname"]=="") {// changed from $_SESSION['user_name'],checks if sesison is empty , will redirect to login page.
header('Location: login.php');
}
?>
You have to use session_start(); in the start of the profile.php
How can I show an error if the user entered an incorrect username or password?
Thanks in advance
if(isset($_POST['submit']))
{
SignIn();
}
function SignIn()
{
session_start(); //starting the session for user profile page
if(!empty($_POST['user'])) //checking the 'user' name which is from Sign-In, is it empty or have some text
{
$query = mysql_query ("SELECT * FROM websiteusers WHERE userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(" db not available" . mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) and !empty($row['pass']) )
{
if ($row['usertype']=="admin")
{
session_start ();
$_SESSION['name'] = $row['fullname'];
$_SESSION['userID'] = $row['userID'];
header("location:admin.php");
}
elseif ($row['usertype']=='designer')
{
session_start ();
$_SESSION['name'] = $row['fullname'];
$_SESSION['userID'] = $row['userID'];
header("location:designer.php");
}
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
Benio summed it up. You are checking it in a wrong way. Instead, you could do something like:
//I hope this die() here is only for testing purpose.
//In a live version available to public, you should use some better way of
//displaying errors such as exception handling
$query = mysql_query ("SELECT * FROM websiteusers WHERE userName = '".mysql_real_escape_string($_POST[user])."' AND pass = '".mysql_real_escape_string($_POST[pass]."'") or die(" db not available" . mysql_error());
if(mysql_num_rows($query)>0){ //this means username and password is found
//the die() here is not needed, since a match is found, it will fetch it
$row = mysql_fetch_array($query) or die(mysql_error());
if ($row['usertype']=="admin")
{
session_start ();
$_SESSION['name'] = $row['fullname'];
$_SESSION['userID'] = $row['userID'];
header("location:admin.php");
}
elseif ($row['usertype']=='designer')
{
session_start ();
$_SESSION['name'] = $row['fullname'];
$_SESSION['userID'] = $row['userID'];
header("location:designer.php");
}
}
else //no match for that username and password is found
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
When user will pass wrong pair of ID and password, mysql_query will return nothing, so mysql_fetch_array will fail too and finally you will trigger the or die(mysql_error()) fragment.
Pass only username to WHERE statement and check only if the password matches given.
i have a problem with $_GET to authenticfiate an owner of his site.
im using this code to check, if the users id is registrated or not:
<?php
session_start();
include('scripts/db_connect.php');
if(isset($_SESSION['id'])){
$url_auth = $_GET['id'];
}else{
echo "no user found";
exit();
}
$sql = "SELECT * FROM table WHERE id='".$url_auth."'";
$query = $db->query($sql);
if($query->num_rows !=1){
header("Location: index.php");
exit();
i having problems with reading out that $_GET id. it seems that something is going wrong and i dont know why. is there maybe another way to check for users registration when someone is calling any id in the browser? thanks.
Try this way.
<?php
session_start();
include('scripts/db_connect.php');
$id=mysql_escape_string($_GET['id']); //Sanitized the variable to avoid SQL Injection attacks
$sql = "SELECT * FROM table WHERE id='".$id."'";
$query = $db->query($sql);
if($query->num_rows !=1){
header("Location: index.php");
exit();
}
else
{
$_SESSION["loggedIn"]="Success";
header("authenticationSuccess.php");
}
?>
Now check this $_SESSION["loggedIn"]="Success" on all your other pages to check whether the user is genuine.
Changes for Comment:
If you really think $_GET is the problem , try this.
<?php
session_start();
#extract($_GET);
include('scripts/db_connect.php');
$sql = "SELECT * FROM table WHERE id='".mysql_escape_string($id)."'";
$query = $db->query($sql);
if($query->num_rows !=1){
header("Location: index.php");
exit();
}
else
{
$_SESSION["loggedIn"]="Success";
header("authenticationSuccess.php");
}
?>
I am trying to do a simple login with PHP and mysql, and using Sessions as well. I have the code, which should work in theory, however it keeps redirecting me to the login page (refreshing it) instead of taking me to the profile.
$username = $_POST['username'];
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1){
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
$uid = $row[0];
session_register($uid);
header('location:profile.php?conf='.$row[0]);
}
else{
echo 'Wrong username';
}
no it shouldn't work in theory
try this
<?php
$username = mysql_real_escape_string($_POST['username']);
$query = "SELECT `confirmcode` FROM `fb_network`
WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if ($row = mysql_fetch_row($result)){
session_start();
$_SESSION['conf_code'] = $row[0];
header('Location: profile.php');
exit;
} else {
echo 'Wrong username';
}
but there can be other issues, from code you didn't post here r other reasons.
as a matter of fact, only debugging can tell you what's the problem for sure
I would use a user defined function and make it to check the login credentials and return true or false from the function.
you can use something like this.
function check_login ($username, $password) {
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( mysql_num_rows($result) == 0) {
return false;
}
if( mysql_num_rows($result) == 1) {
$_SESSION['loggedin'] = "true";
header('location:profile.php?conf='.$row[0]);
return true;
}
}
and then call the function easily and display the appropriate message.
check the following code..
<?php
session_start();
/** If the User is already Logged in then redirect to login.php **/
if(isset($_SESSION['loggedin'])){
header("Location: login.php");
}
else {
if( check_login($_POST['username'], $_POST['password'])) {
header('location:profile.php?conf='.$row[0]);
}
}
althoough the code is not exact but this might be enough to get you going.
I see that your code has only two options - display "wrong code" or redirect to the other page. no place where you are redirecting to the login page?
You need to initiate the session by sessions_start() before the rest of the code.
If you have any sort of 'test' script on the profile page that re-directs you if you're not logged in, it may be that the above code logs you in, but does not carry the session variable correctly to the profile page...and subsequently sends the user back to log in again.
Make sure the session is properly initiated on each page using the variable and make sure they match on both ends.
You have two main problems:
You are not using session_start to tell PHP to start tracking sessions
You are using session_register. session_register requires register_globals to be on, which it hopefully is not in your environment. It also expects its argument to be a string which is the name of the variable you wish to store. You should instead use $_SESSION['uid'] = $row[0];
You should also read about SQL injection, a very serious and common security flaw that your code exhibits.
Here is a corrected version of your code:
<?php
session_start(); //it's fine to just do this by habit at the top of every page
$username = $_POST['username'];
//I added mysql_real_escape_string - please read about "sql injection", as it is a very serious and common problem!
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '".mysql_real_escape_string($username)."' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
//not sure if this is what you weree going for or not
$_SESSION['uid'] = $row[0];
header('location:profile.php?conf='.$row[0]);
}
else {
echo 'Wrong username';
}
Then in profile.php, to check if someone is logged in:
<?php
session_start();
if( ! isset($_SESSION['uid']))
//Not logged in!
if( $_SESSION['uid'] != $_GET['conf'])
//trying to access someone else's page!