I am creating a social network website where each user has his own profile, but there is a problem when I log in, the profile page does not appear. I used cookies and sessions I did lot of research about the problem but without any success, so I think that the problem is in the cookies. I do not know how to fix it; if anyone can help me, I will appreciate that.
profile.php
<?php
ob_start();
require_once('for members/scripts/global.php');
if($logged == 1){
echo("you need to be loged in to view profiles");
exit();
}
if(isset($_GET['id'])){
$id=$_GET['id'];
$id= preg_replace("#[^0-9]#","",$id);
}else{
$id=$_SESSION['id'];
}
//collect member information
$query = mysql_query("SELECT * FROM members WHERE id='$id'LIMIT 1") or die("could not collect user information ");
$count_mem = mysql_num_rows($query);
if($count_mem == 0){
echo("the user does not exit");
exit();
}
while($row = mysql_fetch_array($query)){
$username = $row['username'];
$fname = $row['firstname'];
$lname = $row['lastname'];
$profile_id= $row['id'];
if($session_id == $profile_id){
$owner = true;
}else{
$owner = false;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php print("$fname"); ?> <?php print("$lname"); ?>'s profile</title>
<link href="style/stylesheet.css" type="text/css"/>
</head>
<body>
<div class="container center">
<h1><?php print("$username"); ?></h1>
<?php
if($owner == true ){
header("Location: profile.php");
?>
<!--
edit profile<br />
account settings<br />
-->
<?php
}else{
header("Location: index.php");
?>
<!--
private message<br />
add as friend<br />
-->
<?php
}
?>
</div>
</body>
</html>
<?php flush(); ?>
If you need other related code, let me know. Thank you.
There are quite a few things wrong with the code that you have displayed. For starters, Do not use mysql_ functions. From the PHP manual
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
Secondly, your header redirects are imbedded in your HTML, which is bad practice and you've only been saved by ob_start(). With that though, you have a conditional that will either redirect to 'profile.php' or 'index.php', be lucky you get redirected to 'index.php', otherwise you'd have a forever self-redirecting page.
I can't see if/where you ever set the variable $session_id, but from what can be seen, it's null and will never == $profile_id, so $owner will always be false.
With that, you have a while loop while fetching one row...remove it, no need for it.
Now for some of the logic in your code. If you have to be the profile owner in order to view it, check that immediately after your query, and if not the owner, header("Location: index.php"); die; and don't have an else, anything following it means that it's the profile owner viewing the page.
Also, you need to make sure session_start(); is at the top of the page if you plan on using the session variables. You have ob_start(); up there, but at the end you call flush(). Read up on ob_start() and call the proper flush function for the buffer you started.
Related
I just trying to get a value from the row, but it's not happening and I only get a notice which says:
Notice: Undefined index: sm_value in D:\xampp\htdocs_header.php on line 16
<?php
require "./conf/db.php"; // Additional data
session_start();
if (isset($_SESSION["UserID"])) {
}
else {
header('Location: login.php?=redirect');
}
// If user click to logout
if (isset($_GET["account"]) && $_GET['account'] == "logout") {
unset($_SESSION["UserID"]);
session_destroy();
header("Location: index.php"); // Redirect him/her to index.php
exit();
}
$name = mysqli_escape_string($mysqli, $_POST['sm_value']);
$GetTitle = $mysqli->query("select * from sm_options where sm_value='$name'");
$row = $GetTitle->fetch_array(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?php echo $row['sm_name'];?></title>
....
Maybe something is wrong with the syntax? Or the method? How do I get the value?
The database looks like this:
I appreciate any kind of help :)
This happens when your form is not submitted yet.
So you need to add a condition before your statement, something like this:
if(!empty($_POST) and array_key_exists("sm_value", $_POST)) {
$name = mysqli_escape_string($mysqli, $_POST['sm_value']);
$GetTitle = $mysqli->query("select * from sm_options where sm_value='$name'");
$row = $GetTitle->fetch_array(MYSQLI_ASSOC);
// Every statement and HTML which is required under it when the value is not empty
}
else {
// An error message, when you say the details are not available.
}
For the record, I DID see this entry - Passing sessions variables through an iframe, php which is asking the exact same question, but the answer (even when I followed it to a T) still isn't working for me.
I have two pages - one is the landing page, the other is the page pulled in to the landing page via iframe. I start the session on the landing page and assigned $_SESSION a value, and I want that value pulled in to the iframe.
Here's my code for the landing page:
<?php
session_start();
$_SESSION['vendorname'] = $this->getVendorId(); // store session vendor name data
echo "Vendor = ". $_SESSION['vendorname']; // test to see if the vendor name was properly set
session_write_close();
?>
<html>
<body>
....blah blah...
<iframe width="100%" src="http://www.somewhere.com/iframe.php"></iframe>
<body>
</html>
Here's the code from the page within the iframe:
<?php
session_start();
?>
<html>
<head>
<link href="css/something.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
if(isset($_SESSION['vendorname']) && is_array($_SESSION['vendorname'])) {
echo "vendor = ". $_SESSION['vendorname']; }
else {
echo "Meh, back to the drawing board"; }?>
</body>
</html>
On the landing page, the $_SESSION displays correctly. It retrieves the vendor's name via our database and spits it out on the screen. In the iframe however, it only displays my failure message ("Meh, back to the drawing board"). I am missing something. :(
EDIT:
Per Marc B's suggestion, I'm now checking the session_id(). So for this code (on landing page):
<?php
session_start();
echo session_id();
echo "<br>";
$_SESSION['vendorname'] = $this->getVendorId(); // store session vendor name data
echo "Vendor = ". $_SESSION['vendorname']; //test to see if the vendorname was properly set
echo "<br>";
echo session_id();
session_write_close();
?>
I'm getting the following output:
0lq5gb79p52plgd9mcknpife60
Vendor = SUPERVEND
0lq5gb79p52plgd9mcknpife60
On the iframe page, for this code:
<?php
session_start();
echo session_id();
?>
<html>
<head>
<link href="css/something.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
echo session_id();
if(isset($_SESSION['vendorname'])) {
echo "vendor = ". $_SESSION['vendorname']; }
else {
echo "vendor = ". $_SESSION['vendorname']; }
?>
I'm getting the following output:
0lq5gb79p52plgd9mcknpife60
0lq5gb79p52plgd9mcknpife60
vendor =
Start the iframe with the following:
header('P3P: CP="CAO PSA OUR"');
session_start();
you should then be able to access the session variables in the normal fashion.
Can you please let me know why my session setting is not working correctly? I have a simple Form in index.php file as:
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<body>
<form method="POST" action="validate.php">
Password: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I also have a validate.php file which is like this:
<?php
session_start();
$err="You Have to Insert The Password to Get into Page";
if(($_POST['name']) == $_SESSION['uid']){
header ("Location: target.php");}
else{ echo $err; }
?>
and finally the target.php page is like this
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<body>
<img src="session.jpg">
</body>
</html>
Now my problem is when ever I run the validate.php or target.php URLs directly from the browser address bar like (..localhost/PHP/Session_3/validate.php) I still get access to the target page!
Can you please let me know why this is happening? and how I can set a better isset() function to prevent this?
Thanks for you time and comments
You have to check for session on every page you load,
Adding
if(!isset($_SESSION['uid'])){
header ("Location: index.php");
}
may help on each page. And dont forget to delete the session on every logout.
//Four Steps to close a session
//i.e. logging out
//1. Find the Session
session_start();
//2. Unset all the session variables
$_SESSION=array();
//3. Destroy the session cookie
if(isset($_COOKIE[session_name()])){
setcookie(session_name(),'',time()-42000,'/');
}
//4. Destroy the session
session_destroy();
//redirect_to("index.php?logout=1");
You have code to validate a password but that's all you've written so far. You are neither storing the result of the validation, nor preventing access to protected pages.
To store validation result:
if ($_POST['name']==$_SESSION['uid']) {
$_SESSION['validated'] = true;
}
To protect a page:
if (!isset($_SESSION['validated'])) {
header('Location: http://example.com/');
exit;
}
($_POST['name']) will return a Boolean value, its an if statement on his self ( because of the ( and ) you put around it. It will give you a true value when the $_POST is available.
So what you get is if ((True) == $_SESSION['uid']). Because the code sees the True value it will not run the code after it, its allready true in it.
Thats why it always comes the the header line
So this should do the trick in your case ( there are better ways to do it btw )
if($_POST['name'] == $_SESSION['uid']){
header ("Location: target.php");
}
else
{
echo $err;
}
You have almost done it. There is no need of validate.php. just copy below code in index.php,
<?php
session_start();
if(!empty($_POST['name']) and ($_POST['name']=='test') ){
$_SESSION['uid']='test';
header ("Location: target.php");
}
?>
and update form action to
<form method="POST" action="**index.php**">
and in index.php form, use below code.
<?php
session_start();
if(empty($_SESSION['uid'])){
header ("Location: index.php");
}
?>
You can access target.php if you close and reopen browser. Because at the start there is no value in session and post
So this line,
if(($_POST['name']) == $_SESSION['uid'])
equals
if ( "" == "" ) //true
You should use isset(),
validate.php
<?php
session_start();
$err="You Have to Insert The Password to Get into Page";
if (isset($_POST['name']) && isset($_SESSION['uid'])) {
if ($_POST['name'] == $_SESSION['uid']) {
$_SESSION["logged"] = "logged";
header ("Location: target.php");
} else {
echo $err;
}
} else {
header ("Location: index.php");
}
?>
And If you want to make target.php inaccessible directly if not logged, That would be like this,
target.php
<?php
session_start();
if (!isset($_SESSION["logged"])) {
//No access directly if not logged
header ("Location: index.php");
}
?>
<!DOCTYPE HTML>
<html>
<body>
<img src="session.jpg">
</body>
</html>
So I have a home page where a user can log in. Once they log in I need them to redirect them to index.php that just pulls there information. The Jquery makes a call to index.php where it runs a check against Mysql, if the user doesn't exist it alerts not a valid user. Now if it does I need to send them back to index.php.
Hers is index.php
<?php
include_once 'includes/membersclass.php';
session_start();
$member = new MEMBERS();
if(!isset($_SESSION['id'])) {
if($_POST['action'] == true) {
$result = $member->login($_POST);
if($result) {
$_SESSION['id'] = $result;
echo $_SESSION['id'];
} else {
return false;
}
}
if($_POST['signup'] == 'true') {
$result = $member->signup($_POST);
if($result) {
$_SESSION['id'] = $result;
} else {
header("Location: root.php");
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel='stylesheet' type='text/css' href='css/members.css' />
</head>
<body>
<div id="calendar_container">
<?php $member->drawCalendar(2, 2011); echo $_SESSION['id']; ?>
</div>
</body>
</html>
As you can see Jquery makes the initial call to index.php with a post and get the response back. I set the session to store the user id. On the same page is where the users profile will show. How do I get back here on successful login. Am I even doing it right, should this be separate from the PHP to begin with. Uggghhh, please help.
The question is a bit vague, but if I understand correctly you want to reload the index.php page after a successful login.
if(!isset($_SESSION['id'])) {
if($_POST['action'] == true) {
$result = $member->login($_POST);
if($result) {
$_SESSION['id'] = $result;
echo $_SESSION['id'];
} else {
return false;
}
}
If I'm not mistaken, this piece of code checks if user is already logged in. If not, your checking if the previous Jquery page has given either an 'action' (which I assume is a login call) or a 'signup' (which I assume is to create a new account).
In this case, if 'action' is chosen, you check if the user exists ($result = $member->login($_POST);) and if he does, you create the session ID, and the index-page should show the profile.
Since the $_SESSION['id'] has only been assigned after the page has loaded, it does not check if the $_SESSION['id'] has been assigned again. So you have to reload the page to do this:
if(!isset($_SESSION['id'])) {
if($_POST['action'] == true) {
$result = $member->login($_POST);
if($result) {
$_SESSION['id'] = $result;
echo $_SESSION['id'];
header("Location: index.php");
} else {
return false;
}
}
Now it will call the index.php again, it goes past the if(!isset($_SESSION['id'])) part, since this time the session is created, and to the code (which is not yet present here?) that will take care of the profile.
I have to assume quite a bit here, but tell me how close I am.
PS:
if($_POST['action'] == true)
and:
if($_POST['signup'] == 'true')
Once you have true without quotes, once with. I think you just want to check which one is set? This will suffice:
if(isset($_POST['signup']))
and
if(isset($_POST['action']))
Makes the code more consistent and less prone to errors.
i make the admin panel and have a problem.
need some help to make form for change password in ac-config.php file.
need form for change the adminpassword
$adminpass = "adminpassword";
thankyou
wait for useaful help.
ac-config.php
<?php
//Admin Username and password
$adminuser = "admin";
$adminpass = "adminpassword";
//Error message variables
$not_logged_in_message_error_message = "Error<br><br>You Are not logged in. Go back and try again!<br><br>";
$incorrect_error_message = "Error<br><br>You have entered the incorrect username and/or password, please go back and try again!<br><br>";
$no_pass_or_user_error_message = "Error<br><br>You have either not entered a password or a username, please go back and try again!<br><br>";
//The first page you want the script to go to after creating those cookies (this page must include the validating code as seen in admin1.php)
$first_page = "ac-admin.php";
?>
that is my login verify
ac-login.php
<?php
$formuser = $_POST["formuser"];
$formpass = $_POST["formpass"];
$formpass = md5($formpass);
if($formuser && $formpass) {
setcookie ("cookuser");
setcookie ("cookpass");
setcookie ("cookuser", $formuser);
setcookie ("cookpass", $formpass);
header("Location: ac-admin.php");
}
else {
include("ac-config.php");
echo($no_pass_or_user_error_message);
}
?>
ac-admin.php
<link href="css.css" rel="stylesheet" type="text/css" />
<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Admin</title>
</head>
<body>
<div id="content">
<div id="logo"></div>
<?php include("nav.php"); ?>
<?php
include("ac-config.php");
$cookuser = $_COOKIE["cookuser"];
$cookpass = $_COOKIE["cookpass"];
$adminpass = md5($adminpass);
$moderatorpass = md5($moderatorpass);
if($cookuser && $cookpass) {
if(($cookuser == $adminuser || $cookuser == $moderatoruser) && ($cookpass == $adminpass || $cookpass == $moderatorpass)){
//Any protected stuff you want goes in here!
echo'<green>Successfully logged in!</green><br /><br />';
}
else{
echo($incorrect_error_message);
}
}
else{
echo($not_logged_in_message_error_message);
}
?>
This is Admin Page<br />
Anything want can place here<br />
<div id="footer">CopyRight 2011 - All Rights Reserved</div>
</div>
</body>
</html>
this what you are doing here is what we call "hard coded" passwords into the code, try reading some more on how to use databases or file system, then you can change your password dynamically;
Create another file, which we will use to contain a hashed version of your password. (As this is in another file, you can read/write/edit it as you wish without taking a chance of killing the PHP script which is working with it.)
Create a file "_something_random.txt"
Into that file, paste the following (and only the following - no new lines, or spaces, or anything):
11982574c05624fd4946dda5298cf9db6c679ef4
This is an SHA1 hash of "StackOverflow" - basically a one-way encryption of the word.
Within your existing files:
"ac-config.php"
<?php
//Admin Username and password
$adminuser = "admin";
$adminhashfile = '_something_random.txt';
$adminhash = file_get_contents( $adminhashfile );
.... (rest of the file as-is) ...
"ac-login.php"
<?php
$formuser = $_POST["formuser"];
$formpass = sha1( $_POST["formpass"] );
if( $formuser==$adminuser && $formpass==$adminhash ){
setcookie ("cookuser", $formuser);
setcookie ("cookpass", $formpass);
header( "Location: ac-admin.php" );
} else {
include("ac-config.php");
echo($no_pass_or_user_error_message);
}
?>
If you want to change the password at anytime, you can either manually calculate the SHA-1 hash of your new password and paste it into the "_something_random.txt" file, or you can create a PHP script which (authenticates you as already being logged-in and then) takes the new password and writes it into that file for you.
<?php
include("ac-config.php");
$newPassword = $_POST['newPassword'];
file_put_contents( $adminhashfile , sha1( $newPassword ) );
file_*_contents() & heredoc example...
<?php
//Replacing the values into the config
$config_file="";
if(isset($_POST['update']) && isset($_POST['user']) && isset($_POST['pass'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$config_file = <<<CONFIG
<?php
//Admin Username and password
\$adminuser = "$user";
\$adminpass = "$pass";
//Error message variables
\$not_logged_in_message_error_message = "Error<br><br>You Are not logged in. Go back and try again!<br><br>";
\$incorrect_error_message = "Error<br><br>You have entered the incorrect username and/or password, please go back and try again!<br><br>";
\$no_pass_or_user_error_message = "Error<br><br>You have either not entered a password or a username, please go back and try again!<br><br>";
//The first page you want the script to go to after creating those cookies (this page must include the validating code as seen in admin1.php)
\$first_page = "ac-admin.php";
?>
CONFIG;
file_put_contents('ac-config.php',$config_file);
//Where to send after update
header('Location: ./admin.php?page=changepass');
}
//Getting the values for the form
$config_file = file_get_contents('ac-config.php');
$match = preg_match('%adminuser = \"(.*?)\"%',$config_file,$confuser);
$match = preg_match('%adminpass = \"(.*?)\"%',$config_file,$confpass);
//$confuser[0] & $confpass[0] can be used to insert the values into the form
?>
<form method="POST" action="">
<input type="hidden" name="page" value="changepass">
<input type="hidden" name="update" value="go">
<h1>Change Logins</h1>
<p>Username:<input type="text" name="user" value="<?php echo $confuser[0];?>" size="20"></p>
<p>Password:<input type="password" name="pass" value="<?php echo $confpass[0];?>" size="20"></p>
<p><input type="submit" value="Submit"></p>
</form>