How to do restricted URL in Array and Checkout Page - php

I want to restrict page of Check_out.php and my_account.php. I have added these restriction on top.php like this!
$current = $_SERVER['PHP_SELF'];
$url = "http://" . $_SERVER['HTTP_HOST'] . $current;
$restricted = array("<a href='" . BASE_URL . "products/check_out.php'>Check Out</a>,
<a href='" . BASE_URL . "users/my_account.php'>My Account</a>");
$public_pages = array("login.php","signup.php");
It is not working fine! without login. Check out page is still opening!
Link below, when user clicked on it.
It need to check the condition like If user login then it goes to check_out page. Otherwise it goes to singup.page
<li> Check Out </li>
Here is the code of condition, what i have done right now!
if ($obj_user->login && in_array($current, $public_pages)) {
$_SESSION['ref_url'] = $url;
$_SESSION['msg'] = "You must <a href='" . BASE_URL . "/process/process_logout.php'>LOGOUT</a> to view this page";
header("Location:" . BASE_URL . "msg.php");
}
if (!$obj_user->login && in_array($current, $restricted)) {
$_SESSION['ref_url'] = $url;
$_SESSION['msg'] = "You must <a href='" . BASE_URL . "/login.php'>LOGIN</a> to view this page";
header("Location:" . BASE_URL . "/msg.php");
}
?>
In Check_out.php , I have already set the table which displayed quantity, product name and total price
thanks!

change your first line to this
$current = basename($_SERVER['PHP_SELF']);
change $restricted array to this
$restricted = array('check_out.php','my_account.php');

In any of your none public php file add a check if your user is login if not then redirect to signup page.
Add your check in the top most of any none public php file.
//Make sure your session has started
//Check the user if he/she is not logged in, assuming this will return true or false if the users session is set.
if(!$obj_user->login){
//redirect to the sign up page e.g
header("Location: signup.php");
}

Related

Strategy to pass data from included PHP file

The following code presents a way that I am currently rendering my pages through index.php. The problem is that I'm not sure how to re-think this so I can pass a page title before the template has been included.
How other way I could do this? This is just my index page, please ask if more code needed.
include($cms->GetTheme() . "/head.php"); This should get the Title information before being included, but I'm not sure how to pass data there from later included page.
include('config/config.inc.php');
$cms = new cms();
if(($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_GET['page'])) {
include($cms->GetTheme() . "/head.php");
$cms->IncludeModule($_GET['page']); <- actual page being included
include($cms->GetTheme() . "/foot.php");
} // end (GET || POST) && GET
else { // just index.php
include($cms->GetTheme() . "/head.php");
foreach($cms->GetModuleList() as $module) {
echo " $module <br />";
}
include($cms->GetTheme() . "/foot.php");
} // end ELSE
Example page being included. The $this->SetTitle($module_name); I would use to set the page title.
<?php
$module_name = 'Log out user';
$module_directory = 'admin';
$this->SetTitle($module_name); // setting page title
if(count(get_required_files()) < 2) {
header('Location: index.php');
}
else {
if(isset($_SESSION['user'])) {
$this->DestroyUser();
echo "You have been logged out! Please navigate to the Login Page.";
}
else {
header('Location: index.php?page=login');
}
}
?>
There are echos all over the place. Try and limit the places where you do that by storing the output, rather than printing it all out straight away.
In your module for example, you could do $this->content = "You have been logged out..."
Then you can change the order of execution:
$cms->IncludeModule($_GET['page']);
include($cms->GetTheme() . "/head.php");
echo $cms->content;
include($cms->GetTheme() . "/foot.php");

How to add Steam OpenID login and remember user login with cookie to my site?

Im trying to build a website where users will be able to login via Steam OpenID and do some stuff on the website.
But i would also like to implement some features that steam doesn't offer so:
If user come first time to the website and try to login he use steam OpenID feature to retrieve his user informations (the id is only passed on openID and the rest of informations i can take via API) but now i need to verify user first before i enable other site features, to verify user i need to check if he have more than 20 games on his account. If he have more than 20 games he is ok to continue to use website, if he don't have enough games post a notice that once he have enough game he can continue with login.
When the user is logedin and verified i need to insert his data into database to be able to connect him with features on my website, like counting comments, points,and other activity.
And finally once he is loged in remember him via cookie (there are sessions but as i know they are only valid until browser is closed) so cookie would be solution next time he come to website he don't need to login again.
I know how to do some stuff but in messy way i would be very grateful if someone could point me out and help me a bit how to achieve at least half of this.
So far the code i have is this one.
function login() {
$openid = new LightOpenID(SITEURL);
if(!$openid->mode) {
if(isset($_GET['go']) && $_GET['go'] == 'login' ) {
$openid->identity = 'http://steamcommunity.com/openid';
header('Location: ' . $openid->authUrl());
}
if(!isset($_SESSION['RaffleSteamAuth'])) {
echo '<li><img border="0" src="http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_small.png" /></li>';
}
}
elseif($openid->mode == 'cancel') {
echo 'User has canceled Authentication.';
}
elseif(!isset($_SESSION['RaffleSteamAuth'])) {
$_SESSION['RaffleSteamAuth'] = $openid->validate() ? $openid->identity : null;
$_SESSION['RaffleSteamID64'] = str_replace('http://steamcommunity.com/openid/id/', '',$_SESSION['RaffleSteamAuth']);
if($_SESSION['RaffleSteamAuth'] != null) {
$steam64 = str_replace('http://steamcommunity.com/openid/id/', '', $_SESSION['RaffleSteamAuth']);
$profile = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . APIKEY . '&steamids=' . $steam64);
$buffer = fopen('cache/' . $steam64 . '.json', 'w+');
fwrite($buffer, $profile);
fclose($buffer);
}
header('Location: ' . SITEURL);
}
if(isset($_SESSION['RaffleSteamAuth'])) {
$steam = json_decode(file_get_contents('cache/' . $_SESSION['RaffleSteamID64'] . '.json'));
echo '<li class="dropdown">';
echo '<img src="' . $steam->response->players[0]->avatar . '"/> ' . $steam->response->players[0]->personaname .'<b class="caret"></b>';
echo '<ul class="dropdown-menu">';
echo '<li>Logout</li>';
echo '</ul>';
echo '</li>';
}
if(isset($_GET['go']) && $_GET['go'] == 'logout' ){
unset($_SESSION['RaffleSteamAuth']);
unset($_SESSION['RaffleSteamID64']);
header('Location: ' . SITEURL);
}
}

PHP UPDATE with if and else statement

I need a little help with my script, I am making a library sign in/out and page and I have it working so that it posts the form when they sign in and out, but i want to make it to where if they are trying to sign out and they actually never signed in it would pop-up a js alert tell them that and I can't quite get it.
Here's the code:
<?php
session_start();
include_once("connect.php");
date_default_timezone_set("America/Winnipeg");
$date = ("m-d-Y");
$timeout = date("g:i:s a");
//search for existing entries
if ("SELECT EXISTS(SELECT * FROM signin_out WHERE
lname='".$_POST['lastname']."' AND fname='".$_POST['firstname']."'
AND date='".$date."')") {
//if they exist run this
mysql_query("UPDATE signin_out SET timeout='" . $timeout . "'
WHERE lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "' AND timeout='' ");
header("Location: ../index.html");
//if they don't exist run this
} else {
header("Location: ../index.html");
echo "<script type='text/javascipt'>\n";
echo "alert('You did not sign in!');\n";
echo "</script>";
}
?>
The HTTP Location header already sends them to ../index.html long before the JavaScript gets echoed out. You need to have a logout.php page with that JavaScript or a $_GET variable for the page you redirect them to, and trigger the alert box there.
For instance:
...
} else {
header('Location: ../index.php?notloggedin');
}
And somewhere in your index.php:
<?php
if(isset($_GET['notloggedin'])) {
echo '<script>alert("You did not sign in!");</script>';
}
?>
Although I find that an alert box is rather intrusive, I'd rather do:
<?php
if(isset($_GET['notloggedin'])) {
echo '<p><strong>You did not sign in!</strong></p>';
}
?>

PHP Redirect to Selected Page After Login

I'm trying to find a way to redirect a user to the page they selected if they have been forced to log in again after a session timeout.
Right now, after the user logs in, they are redirected to index.php. But, if a user received a link in an email to a different section of my site and they have not logged in all day, they are obviously asked to log in but end up on the index.php instead of the page the link was for.
Here is a snippet of my code in the login page:
if (mysql_num_rows($result_set) == 1) {
// username/password authenticated
// and only 1 match
$found_user = mysql_fetch_array($result_set);
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['username'] = $found_user['username'];
$_SESSION['last_activity'] = time();
$_SESSION['time_out'] = 7200; // 2 hours
redirect_to("index.php");
Any ideas would be helpful.
I want to thank everyone who answered my question. The solution was a combination of a few suggestions I received here. I'd like to share with you how I solved this:
Part of the reason why I was having trouble saving the url the user tried to go to before being forced to log in again was that my sessions are handled by an external php file which takes care of confirming login and expiring current session. This file is required by all pages on my website. HTTP_REFERER would not work because it would always be set to the login.php. Here's what I did on my session.php file:
session_start();
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https')
=== FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
$currentUrl = $protocol . '://' . $host . $script . '?' . $params;
if ($currentUrl != "http://domain.com/login.php?") {
$expiryTime = time()+(60*5); // 5 mins
setcookie('referer',$currentUrl,$expiryTime,'/');
}
Essentially, I saved the referring url in a cookie that is set to expire in 5 minutes, giving the user enough time to login. Then, on login.php I did this:
if(isset($_COOKIE['referer'])) {
redirect_to($_COOKIE['referer']);
} else {
redirect_to('index.php');
}
And, BINGO! Works every time.
Try this:
$actual_link = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
if($actual_link == 'the email link'){
header('Location: '. $actual_link);
}else{
header('Location: index.php');
}
Try to save the URL in session whenever a user hit any url like http://www.abc.com/profile.php
once the user has successfully logged in redirect the user to saved URL(which is in session)
it the previous page is in the same directory and then you can try header('Location : .') or else if you if you need to redirect somewhere else.save the path before that situation occurs and in $url then u can redirect using header('Location: $url') or header('Location $url?values')

Form redirection with multiple variables

I found a wonderful example on form redirection when there is an error with the form elements. In validation.php the system checks if there is an error and if it's true it redirects the user to the form page.
My question is what if I have more than one form element?
As you see I renamed user_name to app_name and I added a new variable (adtext) so now I get two error messages when both form elements have some error (right now they not equal to a certain word), but I don't know what to do with the $query_string variable so the url would contain the second variable and its value as well.
This is how the url of the form page (adparameters.php) looks like when I click the submit button and there is an error with $appname:
/adparameters.php?appname=aa&error=App%20name%20is%20requiredAd%20text%20is%20required
<?php
# validate.php
$appname = trim($_POST['appname']);
$adtext = trim($_POST['adtext']);
$error = '';
if ($appname != 'myapp') $error = 'App name is required<br />';
if ($adtext != 'mytext') $error = $error . 'Ad text is required<br />';
$query_string = '?appname=' . $appname;
$server_dir = $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . '/';
header('HTTP/1.1 303 See Other');
if ($error != '') {
// Back to register page
$next_page = 'adparameters.php';
// Add error message to the query string
$query_string .= '&error=' . $error;
// This message asks the server to redirect to another page
header('Location: http://' . $server_dir . $next_page . $query_string);
}
// If Ok then go to confirmation
else $next_page = 'confirmation.php';
/*
Here is where the PHP sql data insertion code will be
*/
// Redirect to confirmation page
header('Location: http://' . $server_dir . $next_page . $query_string);
?>
The greatness of this code is that if I type something in the first input type object and it doesn't equal 'myapp' it is still filled with the text after redirection. That's what I want with the second object as well.
Best practice would be to send them in a $_SESSION.
session_start();
$_SESSION['form'] = array();
$_SESSION['form']['myapp'] = 'App Error Code';
$_SESSION['form']['adtext'] = 'AdText Error Code';
Then on the new page you would get the values as an array;
session_start();
$form_error = $_SESSION['form']['myapp'];
$form_error = $_SESSION['attext']['myapp'];
If you insist on using GET parameters why not append them on with the & character.
?field1=one&field2=two
I woldn't do it the way you do it but if you want it like that just change few things
if ($appname != 'myapp') $error = 'App name is required<br />';
if ($adtext != 'mytext') $error .= 'Ad text is required<br />';//note contatenation
$query_string = '?appname=' . $appname .'&addtext='.$adtext;

Categories