Passing $_SESSION through an iframe - PHP - php

For the record, I DID see this entry - Passing sessions variables through an iframe, php which is asking the exact same question, but the answer (even when I followed it to a T) still isn't working for me.
I have two pages - one is the landing page, the other is the page pulled in to the landing page via iframe. I start the session on the landing page and assigned $_SESSION a value, and I want that value pulled in to the iframe.
Here's my code for the landing page:
<?php
session_start();
$_SESSION['vendorname'] = $this->getVendorId(); // store session vendor name data
echo "Vendor = ". $_SESSION['vendorname']; // test to see if the vendor name was properly set
session_write_close();
?>
<html>
<body>
....blah blah...
<iframe width="100%" src="http://www.somewhere.com/iframe.php"></iframe>
<body>
</html>
Here's the code from the page within the iframe:
<?php
session_start();
?>
<html>
<head>
<link href="css/something.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
if(isset($_SESSION['vendorname']) && is_array($_SESSION['vendorname'])) {
echo "vendor = ". $_SESSION['vendorname']; }
else {
echo "Meh, back to the drawing board"; }?>
</body>
</html>
On the landing page, the $_SESSION displays correctly. It retrieves the vendor's name via our database and spits it out on the screen. In the iframe however, it only displays my failure message ("Meh, back to the drawing board"). I am missing something. :(
EDIT:
Per Marc B's suggestion, I'm now checking the session_id(). So for this code (on landing page):
<?php
session_start();
echo session_id();
echo "<br>";
$_SESSION['vendorname'] = $this->getVendorId(); // store session vendor name data
echo "Vendor = ". $_SESSION['vendorname']; //test to see if the vendorname was properly set
echo "<br>";
echo session_id();
session_write_close();
?>
I'm getting the following output:
0lq5gb79p52plgd9mcknpife60
Vendor = SUPERVEND
0lq5gb79p52plgd9mcknpife60
On the iframe page, for this code:
<?php
session_start();
echo session_id();
?>
<html>
<head>
<link href="css/something.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
echo session_id();
if(isset($_SESSION['vendorname'])) {
echo "vendor = ". $_SESSION['vendorname']; }
else {
echo "vendor = ". $_SESSION['vendorname']; }
?>
I'm getting the following output:
0lq5gb79p52plgd9mcknpife60
0lq5gb79p52plgd9mcknpife60
vendor =

Start the iframe with the following:
header('P3P: CP="CAO PSA OUR"');
session_start();
you should then be able to access the session variables in the normal fashion.

Related

Google Login PHP is not redirecting after authentication

I am running an issue where after I authenticate the user, that it's redirecting me to the log in page again and not the home-page.php where it should display the user's google login information. I tried adding an exit(); after authentication like what this thread (Why is my web not redirecting after Google Login) suggested but I still run into the same issue.
Config.php
<?php
// Google API configuration
define('GOOGLE_CLIENT_ID', '659848906740-qvoftv2sg9urfh5kt5a2hh3mcel57hsa.apps.googleusercontent.com');
define('GOOGLE_CLIENT_SECRET', 'Te3sltN31StU3zgmUQm0SBwR');
define('GOOGLE_REDIRECT_URL', 'https://cgi.sice.indiana.edu/~team03/team-03/Server/profile_log.php');
// Start session
if(!session_id()){
session_start();
}
// Include Google API client library
require_once 'google-api-php-client/Google_Client.php';
require_once 'google-api-php-client/contrib/Google_Oauth2Service.php';
// Call Google API
$gClient = new Google_Client();
$gClient->setApplicationName('Login to Hair Identity');
$gClient->setClientId(GOOGLE_CLIENT_ID);
$gClient->setClientSecret(GOOGLE_CLIENT_SECRET);
$gClient->setRedirectUri(GOOGLE_REDIRECT_URL);
$google_oauthV2 = new Google_Oauth2Service($gClient);
?>
index.php
<?php
// Include configuration file
require_once 'config.php';
session_start();
if(isset($_GET['code'])){
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var(GOOGLE_REDIRECT_URL, FILTER_SANITIZE_URL));
}
if(isset($_SESSION['token'])){
$gClient->setAccessToken($_SESSION['token']);
}
if($gClient->getAccessToken()){
// Get user profile data from google
$gProfile = $google_oauthV2->userinfo->get();
// Getting user profile info
$gData = array();
$gData['oauth_uid'] = !empty($gProfile['id'])?$gProfile['id']:'';
$gData['first_name'] = !empty($gProfile['given_name'])?$gProfile['given_name']:'';
$gData['last_name'] = !empty($gProfile['family_name'])?$gProfile['family_name']:'';
$gData['email'] = !empty($gProfile['email'])?$gProfile['email']:'';
$gData['gender'] = !empty($gProfile['gender'])?$gProfile['gender']:'';
$gData['locale'] = !empty($gProfile['locale'])?$gProfile['locale']:'';
$gData['picture'] = !empty($gProfile['picture'])?$gProfile['picture']:'';
$userData = $gData;
// Storing user data in the session
$_SESSION['userData'] = $userData;
// storing user profile data in session
if(!empty($userData)){
$_SESSION["upic"]= '<img width="100" src="'.$userData['picture'].'">';
$_SESSION["uid"]= '<p><b>Google ID:</b> '.$userData['oauth_uid'].'</p>';
$_SESSION["uname"]= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>';
$_SESSION["uemail"]= '<p><b>Email:</b> '.$userData['email'].'</p>';
$_SESSION["logout"]= '<p><b>Logout</b></p>';
header("Location: home-page.php");
}else{
$out_error = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
echo $out_error;
}
}else{
// Get login url
$authUrl = $gClient->createAuthUrl();
echo "<center>";
echo "<h1>Continue logging in with Google </h1>";
// google login button
$login_image = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'">
<img src="images/google-sign-in-btn.png" alt=""/></a>';
echo $login_image;
echo "</center>";
}
?>
<html>
<head>
<link rel="stylesheet" href="login.css">
</head>
<body>
</body>
</html>
home-page.php
<!DOCTYPE html>
<html>
<head>
<title>Google Account</title>
</head>
<body>
<center>
<?php
session_start();
if(isset($_SESSION["uname"])){
echo "<h1>Your Google Details </h1>";
echo $_SESSION["upic"];
echo $_SESSION["uid"];
echo $_SESSION["uname"];
echo $_SESSION["uemail"];
echo $_SESSION["logout"];
}else{
header("index.php");
}
?>
</center>
</body>
logout.php
<?php
// Include configuration file
require_once 'config.php';
// Remove token and user data from the session
unset($_SESSION['token']);
unset($_SESSION['userData']);
// Reset OAuth access token
$gClient->revokeToken();
// Destroy entire session data
session_destroy();
// Redirect to homepage
header("Location:index.php");
?>
From the documentation:
Note:
Most contemporary clients accept relative URIs as argument to ยป
Location:, but some older clients require an absolute URI including
the scheme, hostname and absolute path. You can usually use
$_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an
absolute URI from a relative one yourself:
<?php
/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>
Try this.
The header("Location: home-page.php"); code in index.php is correct and should be the page you want your redirect to, in this case mine is the page that displays the google information of the user. The issue was in the config.php where your Google_redirect_URL should be the file that your google button is connected to, in my case being index.php. You also need to add that URL to your Google console so you don't get a mismatch error.

On link click redirect after cookie is set with PHP

I have a page which has two links. When you click one of the link than the PHP should redirect you to the clicked page and when you visit back the cookie should remember your previous choice and it should load the specific page and not the page with the two links.
I was able to set the cookie but I don't know how to use it when I click on the links.
Here is the full code:
<?php
$cookie_name = 'redirect';
if(!isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name , 'redirect-link', time()+(60*60*24*365), "/");
}
else {
print 'Cookie with name ' . $cookie_name. ' value is: ' . $_COOKIE[$cookie_name];
}
?>
<html>
<head></head>
<body>
<br/>
link1
link2
</body>
</html>
main page
if(isset($_COOKIE['thechoosenone'])
{
$url='<baseusl>/'.($_COOKIE['thechoosenone'];
header('Location: '.$url);
}
on the linked page eg:
if(!isset($_COOKIE['thechoosenone'])) {
//create cockie $_COOKIE['thechoosenone'] and asight the url
}else{
$url='<baseusl>/'.($_COOKIE['thechoosenone'];
header('Location: '.$url);
//stop choosing via manual url browsing
}

Using URL With Variables to Effect Code

I was wondering how you use ? (question marks) in your website to make it do different stuff based on the variable in the url.
like:
http://example.com/php/learn/kinder.php?level=$level
like what's that called, and how do you use it?
I assume with a switch statement
This is my code at the momment:
<php
$con=mysqli_connect("host","username","pass","db");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$level = mysqli_query($con,"SELECT gradek FROM profiles");
?>
<html>
<head>
<title> Redirecting </title>
<meta http-equiv="refresh" content="1; url=http://teachertechtutor.com/php/learn/kinder.php?level=$level>
</head>
<body>
</body>
</html>
Then i'd have a switch... I know it's pointless. I just want to know for future reference.
So my question is:
how to redirect using php variable in html
How to use the ? to change the code.
I used bolli's code and this is what appears in the web page:
`<meta http-equiv="refresh" content="1; url=http://teachertechtutor.com/php/learn/kinder.php?level2=> </head> <body> </body> </html>
And it still doesn't redirect correctly
In kinder.php place:
$level = $_REQUEST['level'];
echo $level;
And read about POST and GET request.
http://www.tizag.com/phpT/postget.php
Or do you mean how to place the variable in the URL?
Either do
<meta http-equiv="refresh" content="1; url=http://teachertechtutor.com/php/learn/kinder.php?level=<?php echo $level;?>>
or
echo "<meta http-equiv="refresh" content="1; url=http://teachertechtutor.com/php/learn/kinder.php?level=".$level;
EDIT / UPDATE
Are you trying to get the variable and based on it, switch the page content?
You could do something like this?
<?php
//you could load header here
//include 'header.php';
/*
*Load content based on $_get parameter
*/
// Get the $variable from the url after the level=
$page = (isset($_GET['level'])) ? $_GET['level'] : 'index';
//Check to see if the file exist
if (!file_exists($page . '.php'))
{
//echo "File does not exist" . $page;
}
switch ($page)
{
case 'test':
include('test.php');
break;
case 'test2':
include('test2.php');
break;
case 'test3':
include('test3.php');
break;
//Defualt start page
default:
include('index.php');
}
// You could load footer here
//include 'footer.php';
?>

Having Issue with PHP Session

Can you please let me know why my session setting is not working correctly? I have a simple Form in index.php file as:
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<body>
<form method="POST" action="validate.php">
Password: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I also have a validate.php file which is like this:
<?php
session_start();
$err="You Have to Insert The Password to Get into Page";
if(($_POST['name']) == $_SESSION['uid']){
header ("Location: target.php");}
else{ echo $err; }
?>
and finally the target.php page is like this
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<body>
<img src="session.jpg">
</body>
</html>
Now my problem is when ever I run the validate.php or target.php URLs directly from the browser address bar like (..localhost/PHP/Session_3/validate.php) I still get access to the target page!
Can you please let me know why this is happening? and how I can set a better isset() function to prevent this?
Thanks for you time and comments
You have to check for session on every page you load,
Adding
if(!isset($_SESSION['uid'])){
header ("Location: index.php");
}
may help on each page. And dont forget to delete the session on every logout.
//Four Steps to close a session
//i.e. logging out
//1. Find the Session
session_start();
//2. Unset all the session variables
$_SESSION=array();
//3. Destroy the session cookie
if(isset($_COOKIE[session_name()])){
setcookie(session_name(),'',time()-42000,'/');
}
//4. Destroy the session
session_destroy();
//redirect_to("index.php?logout=1");
You have code to validate a password but that's all you've written so far. You are neither storing the result of the validation, nor preventing access to protected pages.
To store validation result:
if ($_POST['name']==$_SESSION['uid']) {
$_SESSION['validated'] = true;
}
To protect a page:
if (!isset($_SESSION['validated'])) {
header('Location: http://example.com/');
exit;
}
($_POST['name']) will return a Boolean value, its an if statement on his self ( because of the ( and ) you put around it. It will give you a true value when the $_POST is available.
So what you get is if ((True) == $_SESSION['uid']). Because the code sees the True value it will not run the code after it, its allready true in it.
Thats why it always comes the the header line
So this should do the trick in your case ( there are better ways to do it btw )
if($_POST['name'] == $_SESSION['uid']){
header ("Location: target.php");
}
else
{
echo $err;
}
You have almost done it. There is no need of validate.php. just copy below code in index.php,
<?php
session_start();
if(!empty($_POST['name']) and ($_POST['name']=='test') ){
$_SESSION['uid']='test';
header ("Location: target.php");
}
?>
and update form action to
<form method="POST" action="**index.php**">
and in index.php form, use below code.
<?php
session_start();
if(empty($_SESSION['uid'])){
header ("Location: index.php");
}
?>
You can access target.php if you close and reopen browser. Because at the start there is no value in session and post
So this line,
if(($_POST['name']) == $_SESSION['uid'])
equals
if ( "" == "" ) //true
You should use isset(),
validate.php
<?php
session_start();
$err="You Have to Insert The Password to Get into Page";
if (isset($_POST['name']) && isset($_SESSION['uid'])) {
if ($_POST['name'] == $_SESSION['uid']) {
$_SESSION["logged"] = "logged";
header ("Location: target.php");
} else {
echo $err;
}
} else {
header ("Location: index.php");
}
?>
And If you want to make target.php inaccessible directly if not logged, That would be like this,
target.php
<?php
session_start();
if (!isset($_SESSION["logged"])) {
//No access directly if not logged
header ("Location: index.php");
}
?>
<!DOCTYPE HTML>
<html>
<body>
<img src="session.jpg">
</body>
</html>

User profile data does not appear after logging in

I am creating a social network website where each user has his own profile, but there is a problem when I log in, the profile page does not appear. I used cookies and sessions I did lot of research about the problem but without any success, so I think that the problem is in the cookies. I do not know how to fix it; if anyone can help me, I will appreciate that.
profile.php
<?php
ob_start();
require_once('for members/scripts/global.php');
if($logged == 1){
echo("you need to be loged in to view profiles");
exit();
}
if(isset($_GET['id'])){
$id=$_GET['id'];
$id= preg_replace("#[^0-9]#","",$id);
}else{
$id=$_SESSION['id'];
}
//collect member information
$query = mysql_query("SELECT * FROM members WHERE id='$id'LIMIT 1") or die("could not collect user information ");
$count_mem = mysql_num_rows($query);
if($count_mem == 0){
echo("the user does not exit");
exit();
}
while($row = mysql_fetch_array($query)){
$username = $row['username'];
$fname = $row['firstname'];
$lname = $row['lastname'];
$profile_id= $row['id'];
if($session_id == $profile_id){
$owner = true;
}else{
$owner = false;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php print("$fname"); ?> <?php print("$lname"); ?>'s profile</title>
<link href="style/stylesheet.css" type="text/css"/>
</head>
<body>
<div class="container center">
<h1><?php print("$username"); ?></h1>
<?php
if($owner == true ){
header("Location: profile.php");
?>
<!--
edit profile<br />
account settings<br />
-->
<?php
}else{
header("Location: index.php");
?>
<!--
private message<br />
add as friend<br />
-->
<?php
}
?>
</div>
</body>
</html>
<?php flush(); ?>
If you need other related code, let me know. Thank you.
There are quite a few things wrong with the code that you have displayed. For starters, Do not use mysql_ functions. From the PHP manual
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
Secondly, your header redirects are imbedded in your HTML, which is bad practice and you've only been saved by ob_start(). With that though, you have a conditional that will either redirect to 'profile.php' or 'index.php', be lucky you get redirected to 'index.php', otherwise you'd have a forever self-redirecting page.
I can't see if/where you ever set the variable $session_id, but from what can be seen, it's null and will never == $profile_id, so $owner will always be false.
With that, you have a while loop while fetching one row...remove it, no need for it.
Now for some of the logic in your code. If you have to be the profile owner in order to view it, check that immediately after your query, and if not the owner, header("Location: index.php"); die; and don't have an else, anything following it means that it's the profile owner viewing the page.
Also, you need to make sure session_start(); is at the top of the page if you plan on using the session variables. You have ob_start(); up there, but at the end you call flush(). Read up on ob_start() and call the proper flush function for the buffer you started.

Categories