trying to set session variable - php

if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?

Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.

Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.

Related

i am try to create session but always session empty

I want to try to make a session but always session Empty.Use this code rate this product this link send an email open email and click link Active than code working session empty please help me...
<?php
session_start();
include("myhomeportal/setting/config.php");
$conform = $_GET['conform'];
$query = mysqli_query($conn, "SELECT * FROM item_users where com_code='$conform'");
$row = mysqli_fetch_array($query);
if ($row) {
// now update `com_code`
$sql = "UPDATE item_users SET com_code='active', user_type='user' WHERE com_code='$conform'";
$result = mysqli_query($conn, $sql) or die(mysqli_error());
$inventory_id = $row['inventory_id'];
$active = $row['com_code'];
$_SESSION['sess_active'] = $active;
header("Location: category.php?inventory_id=$inventory_id");
} else {
// confirm code not found, show error
}
?>
Try to debug first.
Echo this $row['com_code']; then $_SESSION['sess_active'].
If they print something then go ahead.
There ir an error in your test page.
"sir other page is not working session just simple test code – Pankaj"
Instead you are only testing, you must start the session always with session_start() in every .php you want to use session.
Solving testing page.
"<h1>welcome <?php session_start(); echo $_SESSION['sess_active'];?> </h1> – Panka"
Note from w3schools:
The session_start() function must be the very first thing in your document. Before any HTML tags.
you are writting some html code before start the session, you should do that way:
<? php session_start(); ?>
<h1>welcome <?= $_SESSION['sess_active']; ?> </h1>
You can read more about this https://www.w3schools.com/php/php_sessions.asp

What's going on with my code?

I am using similar syntax in my blog. However, On my forum, nothing happens! This has been such an infuriating thing to tackle, as everything seems to be working exactly as my blog did. Here's my code I pass through and call the delete_post page
CHUNK FROM VIEWPOST.PHP
while($row = mysqli_fetch_array($result)){
echo '<tr>';
echo '<td class="postleft">';
echo date('F j, Y, g:i a', strtotime($row['forumpost_Date'])) . "<br>" .$row['user_Name']. "<br>" .$row['forumpost_ID'];
echo '</td>';
echo '<td class="postright">';
echo $row['forumpost_Text'];
echo '</td>';
if(isset ($_SESSION['loggedin']) && ($_SESSION['user_AuthLvl']) == 1){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
else if(isset ($_SESSION['loggedin']) && ($_SESSION['user_ID']) == $row['forumpost_Author']){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
echo '</tr>';
}echo '</table>';
DELETE POST FUNCTION
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID']);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
Now it is showing the ID's as intended, it just simply does not delete the post. It's such a simple Query, I don't know where my syntax is not matching up!
EDIT FOR DBCONNECT.PHP
<?php
/*---------------------------------------
DATABASE CONNECT PAGE
A simple connection to my database to utilize
for all of my pages!
----------------------------------------*/
$host = 'localhost';
$user = 'ad60';
$password = '4166346';
$dbname = 'ad60';
$connectDB = mysqli_connect($host, $user, $password, $dbname);
if (!$connectDB){
die('ERROR: CAN NOT CONNECT TO THE DATABASE!!!: '. mysqli_error($connectDB));
}
mysqli_select_db($connectDB,"ad60") or die("Unable to select database: ".mysqli_error($connectDB));
?>
Ok, I saw this and I would like to suggest the following:
In general
When you reuse code and copy paste it like you have done there is always the danger that you forget to edit parts that should be changed to make the code work within the new context. You should actually not use code like this.
Also you have hard coded configuration in your code. You should move up all the configuration to one central place. Never have hard coded values inside your functional code.
Learn more about this in general by reading up about code smell, programming patterns and mvc.
To find the problem
Now to fix your problem lets analyse your code starting with delete_post.php
First check if we actually end up inside delete_post.php. Just place an echo "hello world bladiebla" in top of the file and then exit. This looks stupid but since I can't see in your code if the paths match up check this please.
Now we have to make sure the required references are included properly. You start with the include functionality of php. This works of course, but when inside dbconnect.php something goes wrong while parsing your script it will continue to run. Using require would fix this. And to prevent files from loading twice you can use require_once. Check if you actually have included the dbconnect.php. You can do this by checking if the variables inside dbconnect.php exist.
Now we know we have access to the database confirm that delete_post.php received the forumpost_ID parameter. Just do print_r($_GET) and exit. Check if the field is set and if the value is set. Also check if the value is actually the correct value.
When above is all good we can go on. In your code you check if the forumpost_ID is set, but you do not check if the forumpost_ID has an actual value. In the above step we've validated this but still. Validate if your if
statement actually functions by echoing yes and no. Then test your url with different inputs.
Now we know if the code actually gets executed with all the resources that are required. You have a dedicated file that is meant to delete something. There is no need to use a function because this creates a new context and makes it necessary to make a call and check if the function context has access to all the variables you use in the upper context. In your case I would drop the function and just put the code directly within the else statement.
Then check the following:
Did you connect to the right database
Is the query correct (echo it)
Checkout the result of mysqli_query
Note! It was a while ago since I programmed with php so I assume noting from the codes behavior. This is always handy. You could check the php versions on your server for this could also be the problem. In the long run try to learn and use MVC. You can also use frameworks like codeigniter which already implemented the MVC design pattern.
You have to declare $connectDB as global in function.
function delete($table, $forumpost_ID){
global $connectDB;
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
See the reference about variable scope here:
http://php.net/manual/en/language.variables.scope.php
please try to use below solution.
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID'], $connectDB);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID, $connectDB){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
I wish this solution work for you best of luck!

empty session value when moving one page to other

Im having a problem of accessing the session variable value.
im creating a login page and this were i set the values of my session variables.
index.php
<?php
session_start();
$result=mysql_query("select * from myuser where id='".$id ."' and password='".$password."'");
if(mysql_num_rows($result) > 0){
$user = mysql_fetch_assoc($result);
$_SESSION['SESS_ID'] = $user['id'];
$_SESSION['SESS_UNAME'] = $user['username'];
$_SESSION['SESS_PASS'] = $user['password'];
header("location:home.php");
exit();
}
?>
home.php
<?php
session_start();
if(!isset($_SESSION['SESS_ID']) || (trim($_SESSION['SESS_ID'])) == ''){
header("location:index.php");
exit();
}
?>
<html>
<body>
<p>Login Successful</p>
<?php echo $_SESSION['SESS_ID'] ; ?>
</body>
</html>
the problem here is i have no value in $_SESSION['SESS_ID']..so how do i get or access the value of this session variable in my home.php?
Edit: my query for the SQL is
select * from myuser where id='".$id ."' and password='".$password."'
Some points about why you have this issue:
the values you populate the $_SESSION array with come directly from the database, but you have no database SQL query - instead you have
"!--query written here --"
If you can replace this placeholder with a query that returns your id, username and password values then your code should execute as expected.
I'm not certain if your syntax is wrong as such, but it is not the shape I would ever lay it out, my own shape would be:
$result = mysqli_query($connection, $sql);
while ($outputrow = mysqli_fetch_array($result)){
// In here $outputrow is an array of ONE row of your database, so
// $outputRow['id'] = the id from one row. ordered by the ORDER BY in your SQL query.
}
Add a mysqli_error($connection) clause to your SQL query to detect errors. such as :
Here:
$result=mysqli_query($connection, "<!--query written here -->") or die("error :".mysqli_error($connection));
As I have used across these examples, please, please STOP using MySQL and use at least MySQLi or even PDO. There are a host of improvements and bug fixes and lots of info on this transition on SO.
Also, never, ever compare passwords as strings, passwords saved to a database should as a minimum be saved as hashes with PHP function password_hash(). Never have the line if($_POST['pwd'] == $row['pwd']){.
Finally, as rightly mentioned by Fred-ii- in comments, add error logging and checking into your script so that you know what's going on:
Such as:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Add these to the very top of your PHP page and they will display your errors and warnings to you so you can see what is and is not working.
EDIT:
From your edit there are two biq questions, your statement is that:
"select * from myuser where id='".$id ."' and password='".$password."'
so where does the value $id and $password come from? is the <?php at the top of the page, if so, these variables will always be empty, you need to apply a value to these variables.

Can you use $_POST in a WHERE clause

There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.

PHP code allows logging in without correct password

I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php

Categories