php $_SESSION TWIG + Mini2 - php

I'm currently working on a new project based on Mini2 PHP framework
(here is the GitHub of the framework).
As you can see this framework use Twig, but when I want to log in people with a form, I send a request to the Model.php where I start a Session and set $_SESSION['user'] = 'John' for exemple.
The issue is that I have no idea how to check on other page is the Session has been created or even how to show the user name on a page.
Could you please help me ?
Thank you :)

try something like this:
session_start(); // start the session to have access to the session variables
if(isset($_SESSION['user'])) { // check the existance of a variable with isset()
echo "User ".$_SESSION['user']." is logged on";
}

Related

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

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

how developer hack his own website by creating new session manually? (with out login)

I read many question and post about my question but all were not helpful.
I develop website, and in login page i use session.
As i know session is end when browser close,, but my session is not end on browser close..
I want to access my web with out login
here is code that create session
$_SESSION['session_name'] = 'session value';
$_SESSION['is_admin'] = '1';
$general->redirect('home.php');
by this code session is created and i access website definitely,
i try to add session manually , and set these session name in manually session, and then i want to access website,..
you Not give me full detail, but please give me initialize suggestion and helpful source where i read about this.
Thank you.
Simply create a separate page on your website’s root (preferably protected by a HTACCESS password). Call it something like *hack_login.php* (or something more cryptic).
<?php
session_start();
$_SESSION['session_name'] = 'session value';
$_SESSION['is_admin'] = '1';
?>
Now when you access that page, and provided your session cookie is written correctly, you should be authorized when you access your website through the front page.
Don't forget to remove that page once your tests are done ;)

PHP Sessions - Login Form - Unable to login

I have a simple script where a user logs in. I am trying to use sessions, so that a user remains logged in on whatever page he browses through the website.
I have these scripts:
index.php - http://pastebin.com/yqLtqPRC
login.php - http://pastebin.com/KcQWjfw1
dbConfig.php - http://pastebin.com/GKyfaJJV
upload.php - http://pastebin.com/iMrz3WB8
functions.php - http://pastebin.com/x44KrmxK
If the user logs in or is logged in, 'You are now logged in, $user' is supposed to be shown, but the default 'You are not logged in.' displays throughout the pages.
No error messages are shown whenever I change page or try to log in.
Latest version of the code can be found here: http://www.mediafire.com/?7n6qo3p4gpkaao4
Can anyone help please?
thanks.
Put the session_start() on the top of the page in each file where you need sessions just after<?php and you should be fine. You need to call this function before any actual html is echo'd on the page.
Read the php session documentation here
Further looking into your code, if you want to limit the user to see other pages only if he's logged in then make a new file called logincheck.php with contents below and include it on the top of each file by require_once("logincheck.php");. In this case don't put the session_start() code again as mentioned above.
<?php
session_start();
if(isset($_SESSION["username"])){
$welcomeMsg = "<p align='right'>Welcome, </p>" .$_SESSION["username"];
}else{
if(basename($_SERVER["PHP_SELF"])=="index.php")
$welcomeMsg = "You are not logged in";
else
header("Location:index.php");//will redirect the user to index page if he has not logged in
}
?>
Now u can use $welcomeMsg and echo it anywhere on page where u want to display the error msg.
Hope that helps answer your query.
form action="?op=login" method="POST" action="login.php"
why are using action twice in form?
action="login.php" is only required.
I didn't see exactly where your problem was, too much code to read, but by looking through 2 files (the first 2) I noticed some stuff that could become a problem:
A Session_id is supposed to identify a user. if you simply put in a boolean (true) I could easily break in your user reserved part of the site by just modifying my HTTP header.
second thing is that you put a redirect on the login.php before you echo something.... guess you wont see anything.... the redirect happens before the echo.
The third thing is that you should definetly hash the passwords you get and store. It is so sad when people get access to databases and have without any work all passwords of all people.
And a last advice: try to put the Session_Start as the first statement in every file... could be that.
I stopped at this point:
redirect('../TASK2PHP/upload.php');
what's that function and what does it do?
Maybe you meant to use http_redirect or header or HttpResponse::redirect ...
Here you go. There were a ton of errors.
http://www.2shared.com/file/A2V_Ztw8/login.html
That should at least get you started. It is also commented along the way. I did not use the functions.php file there was nothing important in there. Also when you use this change your dbConfig file accordingly.
I have edited index.php, login.php and setup working flow of sessions. Follow the code structure for setting up sessions in others file accordingly.
Download following login-form rar file;
https://www.box.com/s/1ie9ilp9jgluvokf6say
you code structure of login methods seems confusing and its always a good idea to echo everything before you redirect otherwise httpresponse complains about it. Moreover my advise is you first turn on error reporting its always a good idea to do development with error reporting enabled. You can do this inside your login.php just place at the beginning of the file.
error_reporting(E_ALL); or set E_ALL to 1
ini_set('display_errors','On');
TL,DR. But here is an article that teaches the general design pattern for this sort of thing. All web sites that use PHP client authentication follow this design.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html
You can copy and paste the code snippets from the article. If you have any questions about what the code is doing, please post a comment here and I'll try to help explain. ~Ray
Hope this may help :
you can debug if session is empty or not.
session_id() returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.
if(session_id() == '')
{
// session has NOT been started
session_start();
}
else
{
// session has been started
}
and
check session in php if empty
Make it on index.php file and include your pages if user logged in. and check inside each and every page you including. if user not set then redirect to login page.
example :
index.php
if(isset($_SESSION['UserId'])){
//make simple function to get the username from user ID
$dUserName = getUserName($_SESSION['UserId']);
echo "wellcome".$dUserName;
echo "<href='logout.php'>Logout</a>";
}
else{
echo "<href='login.php'>Logout</a>";
}
if(isset($_GET['page'])){
$includePage = "includes/".$_GET['page'].".php";
}
else{
$includePage = "includes/login.php";
}
if(isset($includePage)){
include($includePage);
}
sample page loading from index
sample.php
if(isset($_SESSION['user']) && $_SESSION['user'] != ''){
//show your page
}
else{
//redirect to login page
echo '<SCRIPT language="JavaScript">window.location="index.php?page=login";</SCRIPT>';
}
I have fixed the files...
The main problem is in login.php in the loginUser function.
Change this line:
$sql = "SELECT * FROM users WHERE Username = '$username' AND Password = '$password'";
To this:
$sql = "SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'";
The problem with the first line is that it is looking for the text '$username' (and '$password' and not the variable $username and $password
As you can see the solution is to close the string before and after the variables reference'
P.S. You would gain tremendously from using a framework such as CodeIgniter to build your site, besides for saving you a lot of time fixing errors like this, it is also much more secure.
Let me know if you need me to upload the fixed files.

Capturing Session ID from URL in Joomla

I am trying to capture a session ID from a URL so that the ID will follow a user throughout the site and then get captured when they fill in a form.
The URL will look something like this.
http://www.mysite.co.za/?campaign=the_campaign_name
Then I inserted this code into the top of my Joomla template file:
session_start();
$_SESSION['campaign']=$_GET['campaign'];
Will this capture the session (the_campaign_name) and will this work with Joomla as I know Joomla uses its own session ID's?
When I check the sessions I just get a PHPSESSID showing its session.
Thanks in advance.
This seems to have worked for me, if this helps anyone:
<?php
if (isset($_GET['campaign'])) {
$campaign = $_GET['campaign'];
}
setcookie('CampaignName', $campaign);
?>
Not sure if it's even the correct way but it worked for me on Joomla.
yes it should work, joomla is PHP. and what you are trying to do is PHP, if you want to check all the created session variable then try
session_start();
var_dump($_SESSION);
Update:
it seems joomla stores the session variables in database, according to the documentation you need to set and access session variable in joomla like this.
to set session variable
$session =& JFactory::getSession();
$session->set('campaign', $_GET['campaign']);
to get session variable
$session =& JFactory::getSession();
echo $session->get('campaign');
it seems joomla upon initialization destroys the regular session variable for some security reason they say, here is the link from joomla documentation to help you http://docs.joomla.org/How_to_access_session_variables_set_by_an_external_script
hope this helps. and always remember to sanitize user input with proper validation. before using it.
Since you are using Joomla, why not make use of the Joomla framework?
To set:
JFactory::getSession()->set('campaign', JRequest::getVar('campaign'), $optional_namespace);
To get:
JFactory::getSession()->get('campaign', $optional_default_value, $optional_namespace);

Categories