Putting variable in header = PHP - php

So I'm trying to make the posts.php page look like this >> 'posts.php?user='.$username << for each individual user.
Here is the code on my index.php page (which after a user logs in/signs up turns into >> 'index.php?user='.$username :
<?php
include('header.php');
session_start();
if(!isset($_SESSION['username'])) {
//do nothing
} else {
$_SESSION['username'] = $_GET['user'];
$username = $_GET['user'];
$_SESSION['username'] = $username;
}
Here is the code so far on my posts.php page :
<?php
include('header.php');
session_start();
if(!isset($_SESSION['username'])) {
header('location: must_login.php');
} else {
//idk what to put here
}
?>
I'm trying to get my posts.php page header to look like this >> 'posts.php?user='.$username

I understand you are on day 1 of PHP learning. You are getting a lot of negative responses because your question isn't very specific. You aren't very clear about what is "not working." You should say what you expect to happen, and what is happening.
Here's my answer based on what I think you're asking.
Since the username would usually be gotten from a sign-in form, and sign-in forms usually use POST, you should probably do that. Use POST instead of GET.
included files have access to all the global variables in the file from which they are included.
File#1:
// index.php
$username = $_POST['user'];
include('header.php');
File#2:
// header.php
<div id="header">
<p>You are logged in as user "<?= $username ?>"</p>
</div>
The variable you set in index.php $username is available for use in header.php.

Ok so there's a fair few things you need to consider here, but we all had to learn once so I'll try and cover most of them.
Firstly (as #TrentonMaki has said): DO NOT USE USERNAMES IN URLs. If this site is going live, it is probably the most dangerous thing you can do, aside from printing out your passwords onto the screen.
You must read about authorisation and authentication before you continue.
Secondly, in the interests of learning: the $_SESSION super-global is not the right one to use for URL variables. We call URL variables "GET" variables and therefore they are accessible like this:
$user = mb_convert_encoding($_GET['myVar'], ‘UTF-8′, ‘UTF-8′);
$user = htmlentities($user, ENT_QUOTES, ‘UTF-8′);
These functions 'escape' the data in the variables to make them safe from XSS and SQL Injection attacks (there are alot of other precautions you need to take as well - but they are outside of the scope of this question).
In terms of Sessions, these are variables that are stored in the server memory and persist between pages. there are several considerations when using Sessions (security vulnerabilties like "Session Hijacking") and things you can do to make Sessions safer, but here is how they basically work.
//start the session to retrieve or set variables
session_start();
//you should regenerate session_id here - you need to look up how to do this and other Session santisation.
//set a session var
$_SESSION['myVar'] = "myString";
Now when a new page is loaded you can get the value of a $_SESSION var:
//start the session to retrieve or set variables
session_start();
//you should regenerate session_id here - you need to look up how to do this and other Session santisation.
//get a session var
$myVar = $_SESSION['myVar'];
Some other topics you should definitely learn before you go any further:
mysqli extension - do not use the mysql functions - this is by far the most common mistake new PHP developers make
Prepared statements - these are a MUST for live data security. You should learn them so you never use anything else.

Note :
1.Passing Variable above included file will passing variable to all included script
2.session_start(); must ONLY ONTOP of script and call only session_start(); to avoid session already started error.
<?php
session_start();
$username = $_POST['user'];
include('header.php');
?>

Related

POST variables not persisting from page to page

I'm trying to pass variables between consecutive pages of an automated php process. Because this is automated, I tried setting the variables like this in the prior page:
$_POST['index1'] = $variable1;
$_POST['index2'] = $variable2;
$_POST['index3'] = $variable3
$_POST['index4'] = "hard coded string";
I also have alert statements printing out these values on the prior page just to make sure they're getting set, which they are. But when I move to the following page and try to access those variables, I get undefined index errors for all of these variables. What's happening to the variables from one page to the next that they're not getting passed as expected?
Let's try the following since the information is sensitive.
At the very, very, very, very top of each of the PHP pages connected to this function add:
<?
session_start();
?>
Make sure nothing else is above it, no html, no nothing! Otherwise it will mess up whatever you are trying to do.
On the page you were originally setting your $_POST variables do the following:
$_SESSION["variable1"] = "You";
$_SESSION["variable2"] = "Shall";
$_SESSION["variable3"] = "Not";
$_SESSION["variable4"] = "Pass";
You can ofcourse change the "variable1","variable2" and all of its values into whatever you like.
On whichever page you have included
<?
session_start();
?>
You can now call echo/print/assign each of the $_SESSION variables you set before by echoing:
echo $_SESSION['variable1'];
This would produce the following: "You"
This is a more secure way of transferring data (however sessions can still be hijacked unless you're using HTTPS).
Whenever you are done using the data you can simply unset each $_SESSION variable by using either session_unset(); or session_destroy();
I hope this helps!

Understanding PHP files and AJAX calls

I'm slowly learning PHP ;-) I'm having difficulties understanding how separate PHP-files work together.
I make AJAX calls to different php files that all need to be connected to the backend (Parse). Such as:
sign_up.php
login.php
verify_email.php
get_something_out_of_the_database.php
What is the standard way to stay logged in over the different php files? (or what is the google search term for it..?)
Update:
Thanks for all your answers about 'sessions'. I doesn't work very well yet, so i made a new question.
Thanks!
Remzo
You should use PHP sessions. These are a way to store information on visitor browser between multiple pages...
To start a session, you first need to add session_start(); in every PHP file you intend to use it. Usually it's added in a header.php
Then, you can use sessions already.
To store a result:
$_SESSION['some_data'] = $var;
To retrieve a result in another page, for example:
echo $_SESSION['some_data']; // will echo $var
More info can be found here:
http://www.w3schools.com/php/php_sessions.asp
You can do this for example by storing the login-data in a session-variable and checking it at the start of every new page.
Example:
You check if login-data is valid. Then
session_start();
$_SESSION["login"] = $loginname;
At the start of another page:
session_start();
if(!isset($_SESSION["login"]) || $_SESSION["login"] != "check_somehow")
{
header("Location: logout.php");
exit;
}
For logging out you can use
session_start();
session_destroy();
On the start of your user logged in, you can do something like
session_start();
$_SESSION['USER'] = <some user info>;
In your other pages you can see if
if(isset($_SESSION['USER'])){
// do something
}
at last on logout
session_destroy();
will kill the session

PHP Sessions: Explanation please?

I have been learning PHP for a little bit now, and it has been going really easy for the most part. The only thing I'm hung up on is getting sessions to work. Google has been unforgiving in this endeavor.
It could be one of two reasons; syntax or my software. I'm currently building a local website using EasyPHP 5.3.5.0 on a machine that isn't connected to the internet. Connecting it to the internet is not an option.
What I currently know of sessions is that a lot of syntax related to it has be deprecated, replaced by the superglobal $_SESSION array, which is a lot easier to use. start_session(); must be before any syntax relating to sessions. However, my login script isn't establishing a session, as a quick !isset ($_SESSION['username']) always returns true.
My script is set up like this:
PHP include to login.php, which is a form. check_login.php is what validates it, and if a query returns one row, it'll redirect to login_success.php which establishes the session, gives a welcome message then redirects (Using JavaScript) to the homepage.
Any ideas?
EDIT to include more information:
Here is a synopsis of my code:
index.php:
include 'main_login.php';
main_login.php:
if(!isset ($_SESSION['username'])){
...
Login form, action="cehcklogin.php" method="post"
...
}else{
var_dump ($_SESSION): // Just to see if it works
}
checklogin.php:
Connect to SQL
$username = $_POST['username'];
$password = $_POST['password'];
$username / $password stripslashes / mysql_real_escape_string
Query to find the username & password
$count = mysql_num_rows($result);
if($count = 1){
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header("location:login_success.php");
}else{
echo "Wrong Username or Password."
}
login_success.php:
The login process goes to all of the way here, redirects home and that's where the problem is.
session_start();
var_dump($_SESSION); //This works
if(!isset ($_SESSION['username'])){
header("location:index.php");
}
Javascript redirect, and a welcome message appears.
It all works until you get to the homepage, which $_SESSION['username'] should be set, and it should not display the form, but it does.
It looks like you're not using session_start() in your main_login.php like etranger alluded to. You need to call that function at the start of each new request to begin using sessions.
Otherwise, if you are calling session_start() and you just neglected to show it in the code sample, then maybe the session ID is being lost during the redirect. Are you using cookie-based sessions or passing session ID as a URL parameter? Try printing session_id() or SID at the top of each page. This will let you know when the session is lost (the session ID will change or be "").
If you're using cookie-based sessions, then maybe the cookie is getting lost for some reason. If you're using URL parameter to pass session ID, then maybe transparent session ID support isn't working right.
You have to call session_start() as early as possible, and definitely before using $_SESSION, which would otherwise be empty.

To set up a login system by Sessions in PHP

I found the source of the problem #2. It is the use of session_register(foo).
I put the following to my handle_registration.php.
session_register("foo");
session_register("foo2");
$foo2 = $_POST['email'];
$foo['email'] = $_POST['email']
The problem still persists, since no variables are stored to my session cookie.
This is the logic of my login script.
Solved by Pascal Martin and The Disintegrator: Which is the right place to put the function session_write_close in generating sessions for login?
How can you get a permanent session for user "session" such that a new session is not started each time index.php is loaded?
I have the session_start() at the beginning of my index.php.
The very Beginning of my index.php
session_start();
if($_SESSION['logged_in'] == false) {
$random_number = rand(1,100000);
session_id($random_number);
session_id['email'] = '';
}
while the very end of my index.php
<?php
session_write_close(); // Session code ends here!
?>
I have right after the very beginning of the session code the validation process of user's password by
$dbconn = pg_connect("host=localhost port=5432 dbname=masi user=masi password=123");
$result = pg_prepare($dbconn, "query22", "SELECT passhash_md5 FROM users
WHERE email=$1;");
$passhash_md5 = pg_execute($dbconn, "query22", array($_REQUEST['email']));
// users from registration/login form
if ($passhash_md5 == md5($_REQUEST['password'])) {
$_SESSION['logged_in'] = true;
$_SESSION['email'] = $_REQUEST['email'];
$_SESSION['passhash_md5'] = md5($_REQUEST['password']);
}
// this may be unnecessary if the passhash_md5 cannot be changed by the user
$passhash_md5_2 = pg_execute($dbconn, "query22", array($_SESSION['email']));
// users staying in the site
if ($passhash_md5_2 == $_SESSION['passhash_md5'])) {
$_SESSION['logged_in'] = true;
}
The code generates me continuously random sessions such that no user's data is being saved for the user.
I replaced each $_REQUEST after the login/registration handlers by $_SESSION in my code, since $_REQUEST does not include $_SESSION - still the same problem and I cannot see the username in the homepage after registration/login.
You should use output buffering to prevent this
<?php
ob_start();
everything here
ob_end_flush();
?>
You can't send headers once the normal output takes place.
Your code looks like this :
-- content cut --
</html>
<?php
session_regenerate_id(true); // Session code ends here!
session_write_close();
?>
You definitly have some output (the whole content of your page, actually) before session_regenerate_id is called ; hence the error.
The problem is not with "empty lines" or spaces : it is with output ; and HTML is output ;-)
Like the call to session_start, the call to session_regenerate_id should be done at the beginning of the script, before anything is sent to the browser.
So, here, in the block at the "top" of your index.php.
EDIT : more thoughts.
BTW? I'm not sure you actually need to call session_write_close ; I've probably never used that function, I believe... And, quoting the doc :
Session data is usually stored after
your script terminated without the
need to call session_write_close()
The only case you might need to call this function yourself is if you are doing long calculations :
session data is locked to prevent
concurrent writes only one script may
operate on a session at any time. When
using framesets together with sessions
you will experience the frames loading
one by one due to this locking. You
can reduce the time needed to load all
the frames by ending the session as
soon as all changes to session
variables are done.
But this doesn't seem to be your case, as you are calling this at the end of your script.
So, you could try removing the (useless ?) call to that function...
And, about session_regenerate_id : do you really need to call this function on each page ?
I suppose never calling it would be enough for your site to work... Even if you might want to call it when the user logs in, for security precautions (If I remember correctly, it's nice to call this function whenever the privileges level of a user changes)
Same about session_id, btw : do you really need to call this function on each page ?
http://www.php.net/manual/en/function.session-regenerate-id.php#53480
http://www.php.net/manual/en/function.session-regenerate-id.php#85433
session_regenerate_id — Update the current session id with a newly generated one
If you use it the way you are, you will be generating new sessions over and over.
session_id — Get and/or set the current session id
You are setting a new session every time with a random number.
Actually, the only thing you NEED to use sessions is to put a session_start() statement at the beginning of the script.

Transfer variables between PHP pages

I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.
Try changing your session code as this is the best way to do this.
For example:
index.php
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo 'Click to continue.';
} else {
// form
}
?>
nextpage.php
<?php
session_start();
if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
header('Location: index.php');
}
?>
However I'd probably store something safer like a userid in a session rather than the user's login credentials.
I Agree with carson, sessions should work for this. Make sure you are calling session_start() before anything else on any page you want to use the session variables.
Also, I would not store password info directly, rather use some kind of authentication token mechanism. IMHO, it is not intrinsically unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.
There are several ways:
use sessions (but don't forget to call session_start() on every page you'll use the session data store ($_SESSION))
append your data to the query string of the "next" page ($_GET)
post your data to the "next" page ($_POST)
The session-way is the only way on which the data does not "leave" the server as it's stored on the server itself. For all other ways mentioned above you have to take care of sanitizing and validating the data on the receiving page.
The most simple way would be
//page1.php
session_start();
$_SESSION['user']='user';
$_SESSION['password']='password';
//page2.php
session_start();
echo $_SESSION['user'] . ' ' . $_SESSION['password'];
You can try using POST and GET methods for transferring user inputs within PHP scripts.
PHP GET
PHP POST
I agree too, sessions are the best solution. See this chapter from Web Database Applications with PHP & MySQL for some examples.

Categories