How to correctly use sessions [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have seen a lot of articles on this, but nothing so far has worked. What I want to do is simple.
I have a login page.. verifies who you are through mysql/php, etc. This page has the session_start() in it. From there, it takes you to the menu page.
I want to make it to where if the session hasn't been started from the login page, you're not able to view the menu page and it will direct you back to the login page. If this isn't possible, what I ultimately want to do is make it to where you have to use the login page to view the menu page.
Code from comments:
login.php
session_start();
session_id ("username");
menu.php
if(!session_id() == "") {
header("location:login.html");
}

Instead of just starting the session, you should put something inside so that you know it went past login.php:
$_SESSION['logged_in'] = true;
Then, inside the menu page, you also need session_start():
session_start();
if (!isset($_SESSION['logged_in'])) {
header('Location: /login.php');
}

Use a framework such as Laravel as these features are already built in and handled properly. Theres no use reinventing the wheel and a framework such as the one I mentioned is easy to learn.
EDIT: Sorry, i'm relatively new to answering questions so i'll try again.
In libraries such as Usercake, what happens is when the user logs in you set a session variable
$_SESSION["stack_user"] = "user#stackoverflow.com"; // This could be their name, an object etc
After this on each page that requires the user to be logged in you can check by going
if (!isset($_SESSION["stack_user"])){
header("Location: /login.php");
}
// The rest of your page logic here
Aaaaaand I just realised this has already said... boy i'm off to a bad start

Related

Prevent direct access to php file jquery load() [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to protect my PHP files from direct access, but my problem is that i do not include them in my index. I use jquery load() or iframe, so basicly the php files in include folder don't have access or code from index.php. So i tried with define CONST, but of course didn't work... So basicly i have URL site.com/file witch i load in my index with jquery load as a pop up, but i don\t want if someone try to access it directly from browser to have access... Any idea how should i protect them?
Mike's answer works for regular users, but if you need to be sure that the user first loads the index page, you could do something like:
generate a token when user loads index.php
add token to session data
add token to jquery load as a query parameter (e.g. site.com/file?token=xxxx)
on file load, compare token passed as parameter to the one stored in session and clear the session, so it cannot reuse the token
This way, the user is required to load index.php before loading file.
It wouldn't prevent an advanced user from acessing the file page directly after having the token.
try this, first block limits access to ajax requests, second one checks referring url is mywebsite
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
echo "<span class='error_msgh'>Error 1. Process Aborted.</span>";
die();
}elseif(!preg_match('/(www.mywebsite.com)/', $_SERVER['HTTP_REFERER'])){
echo "<span class='error_msgh'>Error 2. Process Aborted.</span>";
die();
}

How to dynamic generate pages in php? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm doing a web app with PHP in which users have different number of tabs in the menu depending on a certain number of things, one user can have one tab in the menu where another user has ten.
I've managed to dynamically generate the menu items but now I don't know how to create files (pages) where the user gets redirected once he presses on any of the menu tabs.
All these files look the same the only thing that changes are the text, just some strings.
Summing up, what I want to do is:
Generate and destroy files automatically when the user has to consult something
How to link the menu tabs (href) to them automatically
The best would be to use a PHP page as template you could call it.
Lets say for example a user is logged in and clicks the view data page (data.php)
on your link you could have something like this:
and in data.php:
<?php
$USER_ID = htmlspecialchars($_GET["id"])
//SQL Request to get user priviledge and authentificate
//OR
//Check the cookie session for information
if (user_priviledge == 0)
{
//
//Show only data for 0 users
//
}elseif (user_priviledge == 1) {
//
//Show only data for 1 users
//
}
?>
This may not be the solution you wanted but your question wasn't very clear either so if you need any other information make sure to bring more precision.
The condition which are using for tab use same condition to show page. But add that condition in your text.Because your text is changing not page I think.
I this this might help you.
since all files will look the same and only variables will change, you can create one php file and just send the necessary data when a user clicks on the tab to assign to the variables in that page. You do not need to keep on creating custom pages for each and every tab.
Provide some code which you have written for this so that we can help you further

php - different design of webpage for logged in users [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I just have one question. I looked through one book and the Internet and unfortunately didn't find an concrete answer. So... I have a webpage where user can log in. If the user is logged in then the bar at the top of webpage is different(user sees his own photo, name etc.). I know how to use sessions&databases in this case, but I don't know how to make this two different websites. I mean.... in the home site of my whole webpage i can write sth like (in php):
if(isset($_SESSION["User"])) ..... .
But what then? I should somehow hide the html for unlogged user in "else" and part for logged user in "if" or should i create a whole new site for logged in users and redirect to this site if user is logged...? Please, help me.
It seems that you need to spend a little time looking into PHP deeper. My advice would be to learn about including PHP files in order to create a template system (so you would have a base PHP file with the HTML/PHP that is on every page (like a master page) that would include the code:
if(isset($_SESSION["User"]))
{
// Do code for logged in user...
}
else
{
// Do code for generic user...
}
Although that is a really rudimentary example, you could have a global variable if you need things on specific pages too. If you have a more specific question about implementing it, feel free to ask.
one cool thing that you can do in PHP is include html "inline". eg:
if(isset($_SESSION["User"]))
{
?>
<p>Welcome User! <?php echo $_SESSION["User"]; ?></p>
<?php
}
else
{
?>
<p>Please login to see all features...</p>
<?php
} ?>
You should first set the session variable's value(eg. $_SESSION['logged_user_id']) to some value as per your website. Then assuming that you have only one page, you will have to include many php codes at the place you wanted to display user image, Hello xyzuser etc content. You will have to use "if/else" statements to check if the session variable for some user is set or not. If the session variable is set then it will be using the if block statements where you can write code to display image of the user corresponding to e.g. that logged_user_id using your db. Otherwise it will use the else part that will display your default content.
You will have to perform "if/else" checks at each place where your content has a chance to change based on the user status i.e. use the "if" statement to check if the user is logged in or not if no user is logged in then it won't go to the "if" block statements and execute the "else" part for default display. Ok.

php - How to track pages visited by users after they leave my website? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have a website where people can search for cheapest prices of products gathered from 25 websites. It is not an e-commerce site, it's just a site trying to increase the traffic of those 25 sites.
Therefore I want to track my users after they click the products and directed to those e-commerce sites....
I have read a lot about PHP cookies but those did not solve my problem.
Thanks
If you use Google Analytics you can also track clicks as follows:
function trackOutboundLink(link, category, action, opt_label) { // google analytics tracking
try {
_gaq.push(['_trackEvent', category , action, opt_label]);
} catch(err){}
if (link.target == '_blank')
window.open(link.href);
else {
setTimeout(function() {
document.location.href = link.href;
}, 100);
}
}
then use in the <a></a>
<a onclick="trackOutboundLink(this, 'CategoryName', 'ActionName', 'LabelName'); return false;" href="whatever.html" target="_blank">External Website Name</a>
where CategoryName, ActionName and LabelName can be anything you want and will show in Analytics
you need to add a redirection php to save where they are going and redirect them manually. use
something like:
when a link to partner site is clicked which looks like: redirect.php?url=<?php echo urlencode("www.partnersite.com/products.php?productid=34"); ?>
redirect.php:
<?php
$urltoRedirect = $_GET['url'];
//save $urltoRedirect to database / increment redirection count
header("Location: " . $urltoRedirect);
?>
you can't save that data neither to cookie nor session, since cookies are kept locally and sessions expire as soon as user close the browser / or after a limited time.
The links redirecting to the sites themselves should not be writtent directly, instead they should be something like:
The lowest price website
Redirect.php will grad the id the user wants to visite, check it, secure it, write in your DB that this id was hit, means an update on one of your tables like
UPDATE site_hits SET hits = hits + 1 WHERE id = $id;
And then directly redirect the user using a header or meta

CodeIgniter error handling [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm wondering which way is right to handle the errors in CodeIgniter and specifically the MVC pattern. I'm not talking about only sql errors, but lets say that you have user level-access control system and every level can access specific parts of the site.
What if somebody try to enter in a forbidden place for his level?
Or if you execute a controller based on some conditions and these conditions are not met?
Which is the best way to control the errors without confusing the end user which is browsing and using the application?
I'm wondering how you do it.
Do you use different views and controllers when an error occurs or something else?
You are asking 2 different things.
First one:
but what if you have a form which edits something, but according to user-level you cant edit.
You can achieve this but not showing the fields in the form nor updating the database if the user doesn't have permissions.
if ($user_has_permissions)
{
echo form_input('field_name');
echo form_input('field_name');
}
and when updating the row
if ($user_has_permissions)
{
$this->db->set('db_field_name', $field_name);
}
If you want to show an error message in form validation, use callbacks (callbaks in CodeIgniter).
Check if the user has permissions and show the message if hasn't.
Second one
Using die() is not an option, I just dont wanna crash my whole app
If you wan't to stop the execution without using die(), you have some other "friendlier" forms to do it:
show_404();
show_error();
show_error('Description of your error');
This will stop the execution and will show a fancy screen with the error description.
You could specify the user's access level in your database. If a user tries to access a forbidden place you could store some error in the userdata and display them in the view if its set.
The codeigniter session class documentation: http://ellislab.com/codeigniter/user-guide/libraries/sessions.html

Categories