Unable to echo PHP coded cookie value? - php

I have the following code that builds a cookie:
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$firstName = $_COOKIE['firstName'];
$lastName = $_COOKIE['lastName'];
$active = $_COOKIE['active'];
$email = $_COOKIE['emailAddress'];
then when using:
echo "<b>Username:</b> <? " . $username . "?>";
echo "<a href=logout.php>Logout</a>";
The value is not printed as expected.
Can the community explain why and provide me with the correct method for echoing the value to the relevant output device?

I suspect that you never set $_COOKIE['ID_my_site']. You could do a print_r($_COOKIE); to see what it contains. I don't recommend using cookie like this, its against RFC. If you need to keep this information throughout the session then you should use $_SESSION. This also keeps malicious people from changing their cookie.

If you're using that syntax exactly, then you haven't echoed the variable at all. Try:
echo "Username: $username";
echo "Logout";
I see you've edited your question. If $username is not getting populated, try outputting all of $_COOKIE to see what's in there first.
var_dump($_COOKIE);

Related

how to pass values from one page to another in php, not by passing through URL?

How to post values to loginchk_coustomer.php given in below code, not through Url by any other way.
Is there any other way to post these value to loginchk_coustomer.php becoz it is not secure.
<?php
include "include/connect.php";
$user_name = $_REQUEST['user_name'];
$password = $_REQUEST['password'];
//echo "select * from school_info where school_id='$user_name' and school_password='$password'";
$sql_query = mysql_fetch_assoc(mysql_query("select * from school_info where school_id='$user_name' and school_password='$password'"));
$db_username = $sql_query['db_username'];
$db_password = $sql_query['db_password'];
$db_databasename = $sql_query['db_databasename'];
echo "<script>";
echo "self.location='member/loginchk_customer.php?db_username=$db_username&db_password=$db_password&db_databasename=$db_databasename&user_name=$user_name&password=$password'"; // Comment this line if you don't want to redirect
echo "</script>";
?>
You need to create a session to store all that information.
Here's what they are - from http://php.net/manual/en/features.sessions.php:
Session support in PHP consists of a way to preserve certain data across subsequent accesses.
To start a session write at the beginning of your code:
session_start(); // needed in all pages that will use the variables below
and then after your assign the information this way:
$_SESSION['username'] = $sql_query['db_username'];
$_SESSION['password'] = $sql_query['db_password'];
$_SESSION['databasename'] = $sql_query['db_databasename'];
All the information will persist on those variables along the site until you do:
session_destroy();
I also recommend you not to redirect with javascript, but this way in PHP:
header('Location: member/loginchk_customer.php');
Possibly after checking this answer you will think about to change the way you check the login information. But that's okay. It's the way of learning.
More information about sessions: http://php.net/manual/en/book.session.php
I hope this helps.

PHP header if num_rows greater than zero

Something weird is happening with the following code. Instead of completely redirecting. It loads the page of the redirect into the login page and mixes things up.
Q1: How do i make a complete redirect.
- session start is the first line
- There's nothing being output before header.
- As for spaces, I'm not sure what will count as a space in the below script.
Q2: How do i preg_replace a string to only allow both lower cases and uppercases and 0 - 9 numbers and again how do i preg replace emaail to allow the '#' charecter and alphanumerics.
Q3: What's the best way to check if the user trying to login matches exactly the registered user?
Q4: What danger can a hacker do with my session variables?
PHP CODE
<?php
session_start();
require_once 'db_conx.php';
$email = preg_replace ('#[^A-Z, 0-9 ]#i', '', $_POST['email']);
$pwd = preg_replace ('#[^A-Z, 0-9 ]#i', '', $_POST['pwd']);
if ($uname == '' || $pwd == ''){
echo '<span style="color:#F00">Please fill in all login details.</span>';
} else {
$Result = mysql_query("SELECT * FROM users WHERE uemail = '$uname' && pwd = '$pwd'")
or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$_SESSION['Sname'] = $row['firstname'];
$_SESSION['Slname'] = $row['lastname'];
$_SESSION['SUid'] = $row['uid'];
$_SESSION['Semail'] = $row['uemail'];
$_SESSION['Suid'] = $row['uid'];
$_SESSION['Szip'] = $row['zip'];
}
if (mysql_num_rows($Result) > 0){
header ('Location: ../user.php');
} else {
echo '<span style="color:#F00">Your account details do not match, please check your details and try again or try to recover your account if you forgot your password</span>';
}
}
?>
Thanks.
Q1
instead of using header( 'Location...)
you can use
echo '<meta http-equiv="refresh" content="0; URL= http://something.com">';
EDIT
i believe you can also use the following. the die should allow for the redirect, but in my experience it doesn't always get along with jquery.
header('Location: http://something.com');
die();
This is especially useful if you are using event.preventDefault(); in jquery on the same page, which will almost always cause header location redirects to be ignored. this method is also appropriate when you are using get requests to include a php page in your index file, causing a url like http://somesite.com/index.php?page=home
EDIT the above information was wrong it wasn't working for me because php had already sent the headers. i'm an idiot.
instead of this meta refresh, you could do this which should produce the desired result.
echo '<script type="text/javascript">window.location = "yoururlhere"</script>';die;
Q2
$step1 = preg_replace('#[^A-Z, 0-9 ]#i', $_POST["variable"]);
$step2 = strtolower($step1);
echo $step2;
Q3
This is a tough question to answer, but basically you want to hash there password, then check if it matches the password in the db. heres a brief pseudocode.
$username = $db->real_escape_string(strip_tags($_POST["username"]));
$password = hash('sha512', $salt.$_POST["Password"});
$db->query("SELECT * FROM `usertable` WHERE `Username`='$username' AND `Password`='$password' AND Username IS NOT NULL AND Username != '' LIMIT 1");
$result = $db->get();
if(!$result){
//the query returned a null result, so the username or password was incorrect.
}else{
//set user session and log them in.
}
Q4
I'm no expert, but it all depends on the architecture of your application and how you are setting sessions and cookies.in my opinion look into using formkeys and preventing xss, rfi, sql injection and lfi, then worry about session variables. the experience gained tackling the aforementioned problems will give you confidence and a broader understanding when attempting to secure your user sessions.
further information can be obtained from php.net/manual/en/session.security.php and stackoverflow.com/questions/328/php-session-security
thanks to the suggestions of DanFromGermany who improved on this answer.

Session does not work between pages

I have this problem. Session does not work when I use with $_POST. If I add 63 manualy it will works across pages. I can see the output 63.
$_SESSION['name'] = 63;
echo $_SESSION['name'] ;
but this below won't work when I switch between pages. The $row['id'] output is also 63.
$cari = "SELECT id FROM dns_soa WHERE `origin` = '".$_POST['origin']."'";
$keputusan = mysql_query($cari);
$row = mysql_fetch_array($keputusan);
$_SESSION['name'] = $row['id'];
echo $_SESSION['name'] ;
When I go to 2nd pages I can see the output but when I went back to 1st pages the output is gone. Any idea?
Because when you are coming back it will again set the session variable, as this time you don't have the $_POST[origin] variable that leads to $row['id']="" and the session variable also NULL...
What you should do is..
$cari = "SELECT id FROM dns_soa WHERE `origin` = '".$_POST['origin']."'";
$keputusan = mysql_query($cari);
$row = mysql_fetch_array($keputusan);
if(!isset($_SESSION['name']))
$_SESSION['name'] = $row['id'];
echo $_SESSION['name'] ;
When you go back to the page where you have used $_POST, $_POST becomes empty, unless your browser posts it again. So the SQL query returns no result. Hence, $_SESSION['name'] becomes empty.
Also make sure you have invoked session_start on every page before using $_SESSION

Move mysql Information from one page to another in PHP

I have the following code in view.php, I would like to take the information to edit.php without compromising on security or show what is contained in the variables. edit.php has a form to edit the information from the database.
while ($row = mysql_fetch_assoc($result))
{
echo "" . $row['first_name'] ." " . $row['surname'] . "";
echo "<br />";
}
You are already compromising in security - see SQL injection and escaping strings.
Also, it is common practice to include other modules of the application by requiring (see require_once() and require() functions) files. It itself is not a security vulnerability, but indeed encloses all the global variables, functions and classes to that script.
If you really need that, you can unset (see unset()) all the variables you have set, but leave only data you want to be passed.
Learn how to write clean and secure code and it will be secure. Including one PHP file into another is not an insecure practice.
EDIT:
Some start may be creating classes with private or protected properties and public methods, then using them to store sensitive information and execute some actions. By using encapsulation you may achieve what you need.
You should allow only logged in users to see or edit that information, also you might get an SQL injection with:
$first_name = $_POST['first_name'];
$sql_query = "SELECT * FROM employee_master WHERE first_name = '$first_name'";
$result = mysql_query($sql_query, $connection);
You should have instead:
$first_name = mysql_real_escape_string( $_POST['first_name']);
$sql_query = "SELECT * FROM employee_master WHERE first_name = '$first_name'";
$result = mysql_query($sql_query, $connection);
The best way to do this would be(assuming you cant do anything else other than to use a standard anchor link to pass the variable) have an md5 of id of each of your record in the table. So that you can do
while($row = mysql_fetch_assoc($res))
{
echo "" . $row['first_name'] ." $row['surname'] . "";
}
now in edit.php retrieve this and compare it with the hash.
An even more secured way would be to concatenate the id of the record with another unique data such as join date or dob and hash the entire string. It would be highly secure that way.
Option 1: Just past the id from the database via your link. If user knows the id, but doesn't know any other information, than it's useless to it. Using something else will just bring few more code lines.
Option 2: Set user's id in SESSION
$first_name = mysql_real_escape_string( $_POST['first_name']);
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['first_name'] = $first_name;
Then to set other values from the database as session variables, e.g. the user's surname:
$_SESSION['surname'] = $row['surname'];
Then from any other page you can do
if ($_SESSION['loggedin'] == true) {
echo "Welcome $_SESSION['first_name'] $_SESSION['surname']!";
}

$_SESSION['user'] not working

SO this is the code for logging and and where I set things
<?php
session_start();
$_SESSION['user'] = "kjkj";
$_SESSION['pass'] = "";
$error = $user = $pass = "";
if (isset($_POST['user'])) {
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "") {
$error = "Not all fields were entered<br />";
} else {
$query = "SELECT store,c_pass FROM store
WHERE store='$user' AND c_pass='$pass'";
if (mysql_num_rows(queryMysql($query)) == 0) {
$error = "Username/Password invalid<br />";
} else {
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
$str = $_SESSION['user'] . ", You are now logged in. Please
<a href='scheduler.php'>click here</a>.";
die($str);
}
}
} ?>
It'll print the correct store name after the query and all that. But when I try to use it in another php file like this
if (!isset($_SESSION['user']) ) {
die("<p><h1>Please Login</h1></p>");
} else {
echo "<p><form id ='addemp' method=\"post\" action=\"addUser.php\">
Name<input type=\"text\" name=\"emp\" />
\"". $_SESSION['user'] . "\">
<input type=\"submit\" value=\"AddUser\" />
</form></p>";
}
It is an empty string. Not null just empty string. I tried all the solutions I can find on the internet, none of them worked. I'm out ideas as to why this isn't working.
Any help will be greatly appreciated, thank you.
It could be a number of things. First of all do sessions work any other time?
I don't think you have provided enough information for us to help you. It could be a problem with set-up of apache/php not just your code. Has happened to me before when I was developing on Windows with WAMP and temp folder didn't have correct permissions. As I said there could be many issues that cause your session to misbehave.
When you do a counter and refresh
page does it keep a number?
At the
beginning of every time that uses sessions you need to have
session_start() method called.
Important: There can't be any echo's or prints etc before
session_start().
Put var_dump($user) before $_SESSION['user'] = $user; and check the content of $user before it gets saved. It could be that your sanitizing function is not working properly. Do it also at the end of the first script to see the content of $_SESSION to make sure variables are saved properly.
You need to call session_start() before using $_SESSION. Also note that keeping the password in the session is a very BAD practice and a BIG security hole.
If you claim to have inserted session_start() in that page too, do 2 things:
1) correct your html, this line.
echo "<p><form id ='addemp' method=\"post\" action=\"addUser.php\">
Name<input type=\"text\" name=\"emp\" />
\"". $_SESSION['user'] . "\">
Has something not really clear. Where do you echo your $_SESSION to? is it maybe that your browser fails at rendering it? What did you want to accomplish? It can be that the browser is interpreting wrong that closing tag >. Try tidying html first.
If that was meant to be the input field value, write
Name <input type=\"text\" name=\"emp\" value=\"".$_SESSION['user']."\"/>
2) var_dump the $_SESSION['user'] to see if it's really an empty string.
if (!isset($_SESSION['user']) ) {
die("<p><h1>Please Login</h1></p>");
} else {
var_dump($_SESSION['user']);
}
It sounds like the OP had an issue with register_globals.
In php.ini set register_globals = Off, then try the code again.
I had the exact same problem - I had a user variable in the session, and then set $user = array(); and found that the $user variable was overwriting the $_SESSION['user'] variable. Disabling register_globals fixed it.
Or you can change your $user variable to something like $myUser, but it's better to disable register_globals anyway.
Based on #kpaulsen answer,
I got same situation on him, $variable overwrites $_SESSION['variable'] so I followed his suggestion but it isn't works fine on me then I found out another way of setting the register_globals = Off
Add this line on .htaccess
php_flag register_globals off
Maybe its a issue I had some time ago, made all the code perfectly, but forgot to insert the session_start(); at the connection script, witch receives the log-in $_POST['somevariable'] to validate with the DB.
On resume, don’t forget to start a session at your connection.

Categories