location.href and Cannot send session cache limiter - headers already sent - javascript

I understand that there can be no output before setting the headers, and I believed that I am following that rule. I have a php page a.php:
<?php
session_start();
...
echo "<button id=\"searchForTeamsButton\">Search For Teams</button><br>";
...
?>
<script type="text/javascript">
document.getElementById("searchForTeamsButton").onclick = function () {
location.href = "b.php";
};
</script>
and php page b.php:
<?php
session_start();
?>
Upon clicking that button, I am receiving the classic headers already sent error. I am lead to believe that the location.href is not calling a new page "b.php", which allows for new headers. My true question here is what is the proper protocol for redirecting to new pages with links/ buttons? Perhaps location.href is the correct (and perhaps only) way, and perhaps my error is actually on b.php.
I appreciate any information here.
Thanks :)
Brent

Related

Simple Page Redirect Using URL

I want my index.php to redirect to my welcome/index.html. I know there are so many ways to do it but I want to shorten it just like Facebook does. I want a url based redirection. I want to redirect index.php to welcome/index.html by using url.
For example:
example.com to example.com/?url=welcome
//this 'url=welcome' is the index.html of my welcome folder.
Here's the code, according to what I've understood. Place it on the very top of index.php. I'm assuming you're using the domain example.com
<?php
$destination = $_GET["url"];
switch($destination) {
case "welcome": // add your destinations here, one per single "case"
case "about":
case "anotherpage":
header("Location: /" . $destination . "/index.html");
break;
default:
echo "Error";
break;
}
?>
Doing this way you can manage which redirects will work and what not, avoinding "evil" usages of your redirect system.
Something malicious like example.com?url=http://evilsite.com will not redirect them to evilsite.com
This is probably not the best solution, but it's a good starting point to avoid not wanted redirections.
somewhere i read using header for redirection is little bit dangerous as header can b changed easily by hacker and hacker can send victim to another location easily. so i use javascript location.href function for redirection.
<?php
echo "<script>window.location ='http://example.com/welcome/index.html</script>";
?>
if you want to send user to dynamic url from example.com you can set a get variable like.
source address: http//example.com?url=http://example.com/welcome.html
destination address: http://example.com/welcome.html
<?php
if(isset($_GET['url']))
echo "<script>window.location ='$_GET[url]'</script>";
else
echo "<script>window.location='http://somewhereelse.com'";
?>
now u can dynamically set url variable in your source address and redirect user wherever you want to
Not really sure if this would help, but you're welcome to try
<?php
if (isset($_GET["url"])) {
$url = $_GET['url'];
header('Location:'.$url);
}
?>
I haven't tried this, but this is what I thought after seeing your post

Redirect after 5 seconds but only allow the page to be accessed by the referrer

I am trying to have page1.php redirect to page2.php after 5 seconds. However page2.php needs to be a restricted page that can only be viewed if you are being sent from --> mydomain.com/page1.php and can not be accessible if you type the address manually into the address bar.
I have tried methods that use shared keys, htaccess and php HTTP_REFERRER.
I believe the issue is coming from the redirection, and I believe it is because the redirect script is not sending the HTTP_REFERRER and therefore page2.php is looking at the url sent from the redirection script as being manually entered. I have tried with a simple php redirect and javascript. Below are the two different redirect scripts I have used.
php version.
header( "refresh:5;url=page2.php" );
Javascript version.
<script type="text/javascript">
function Redirect()
{
window.location="page2.php";
}
setTimeout('Redirect()', 5000);
</script>
I have tried these with the full url and with/without http:// for example mydomain.com/page2.php.
Page2.php needs to only accept traffic from page1.php. I have no objection as to how to go about achieving this. Using shared keys or any other aspect just as long as the user can not enter the address manually and visit the page. I am also fully aware the Referrer can be spoofed however I do not have the expertise to get to advanced.
You can use session data to make sure users of page2 have passed through page 1
With the way sessions work,The encrypted string is quite secure even if it is not encrypted at all.
on page1:
session_start();
$_SESSION['secret_key'] = 'encrypted_string';
on page2:
session_start();
if($_SESSION['secret_key'] == 'encrypted_string'){
// user is authorized
echo 'You are authorized to see this page';
}
else{
echo 'Please visit page1 before accessing this page';
}
// Logic for authorized user
Or, shorter version for page2 :
if(empty($_SESSION['secret_key']) || $_SESSION['secret_key'] != 'encrypted_string'){
die('You are not authorized to view this page.');
}
echo 'only authorized user will see from here forward';
BTW, when testing, remember that once your session is set, you will have to delete sessions in browser, or use incognito to test again.
To delete cache on chrome ctrl+shift+delete and choose cookies and other
Here's how I would do it, using 3 pages.
On the landing page, include your JavaScript, this will redirect you to an intermediate page that sets a session variable before redirecting to the final page.
On the final page, check the session variable, determine whether or not to display the page, then unset the session variable (so if they try again without returning to the first page, it will no longer work).
p1.php
<?php session_start(); ?>
<script type="text/javascript">
function Redirect()
{
window.location="p12.php";
}
setTimeout('Redirect()', 5000);
</script>
p12.php
<?php session_start();
$_SESSION['secret'] = 'todays_password';
$newURL = 'p2.php';
header('Location: '.$newURL);
?>
<script type="text/javascript">
function Redirect()
{
window.location="p2.php";
}
Redirect();
</script>
p2.php
<?php session_start();
if (isset($_SESSION['secret']))
{
if ($_SESSION['secret'] == 'todays_password')
{
//The user provided the correct secret session variable
echo 'welcome. you can view this page.';
//Put all of your page content here
?>
<!-- HTML content should be in between php delimiters, like this-->
<?php
}
else
{
//The user supplied a secret code, but it was not the correct one
echo 'invalid secret.';
//You can also add code for redirecting the user back to p1 here
//Or just display an error message
}
}
else
{
//The user did not provide a secret session variable -- they most likely did not pass through p12.
echo 'error, you are unable to view this page';
//You can also add code for redirecting the user back to p1 here
//Or just display an error message
}
unset($_SESSION['secret']); //This line makes the user return to p1 every time they visit p2 -- delete this line if you only want them to visit p1 once.
?>
To make this method secure, you'd need to give each user a unique value for their secret session variable. Store this variable, along with it's timestamp when the user visits p1 both as a session variable for the client and in a server-side database. When p2 is loaded, check to see if the session value they provide is at least 5 seconds old in the database. If it is, let them see the page. Then delete the value in the database.

How can I convert this PHP code in a way that will allow me to add it in .JS using Ajax?

I have a .js file hosted on domain1.com, but for this to work correctly I need to add a PHP code at the beginning. The reason for this is to bypass some restriction on Safari for my script and it requires me to create a session. The PHP code creates a session through a url to domain2.com. There is no browser redirection or anything, the user stays in the domain1.com. I want to have a single .js file in domain1.com so maybe an AJAX solution is what I need. Here it is:
<?php
session_start();
if (!isset($_SESSION['isIFrameSessionStarted']))
{
$_SESSION['isIFrameSessionStarted'] = 1;
$redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
header('Location: domain2.com/start-session.php?redirect=' . $redirect);
exit;
}
?>
The start-session.php file is hosted on domain2.com does not need any changes, it contains this:
<?php
session_start(); // create the session cookie
$redirect = rawurldecode($_GET['redirect']);
header('Location: ' . $redirect); // redirect back to domain
exit;
?>
Let me combine what you requested in comments:
I have a .js file hosted on domain1 ... I want to have a single js file and I can't put PHP into that ... the whole purpose of this is for domain1 to not have any php code or php file. ... The reason is because I want it cross-domain and the session to be created from domain2.
It sounds like your issue might be related to the Safari iFrame session cookie problem, especially because you have if (!isset($_SESSION['isIFrameSessionStarted'])) in one of your code blocks. I will continue with this assumption.
Summary of the problem for other readers:
Upon embeding an IFrame from one domain into a website of a different domain, you will quickly realise that Internet Explorer and Safari are blocking the cookies (and thus the session variables) of the website inside the IFrame (ref).
Attempted solutions that didn't pan out:
Safari 3rd party cookie iframe trick no longer working?
Internet Explorer & Safari: IFrame Session Cookie Problem
IFrame must die
Safari: Setting third party iframe cookies
PHP Session in iFrame in Safari and other browsers
My solution:
Essentially, PHP session "hijacking". It works surprisingly well where the above solutions failed. This is the essential solution. Please do any security enhancements* and URL-prettifying you like. Basically, we retrieve the PHP session ID through redirects and pass this to the iframe. Instructions are in the comments.
In your domainA.com head place this:
<script src="session.js"></script>
session.js (on domainA.com):
// Location of the domain B session starter
var sessionScriptURL = "http://domainB.com/start-session.php";
var refQSparam = "phpsessionid";
// Check if we have the phpsessionid in the query string
var phpsessionid = getParameterByName(refQSparam);
if(phpsessionid === null) {
// Not in the query string, so check if we have it in session storage
var sessionStore = sessionStorage.getItem(refQSparam);
if(sessionStore === null) {
// We have no session storage of the PHP session ID either, redirect to get it
top.location = sessionScriptURL + "?redirect=" + encodeURIComponent(self.location.href);
} else {
// phpsessionid was found in session storage. Retrive it
phpsessionid = sessionStore;
}
} else {
// Save the phpsessionid to session storage for browser refresh
sessionStorage.setItem(refQSparam, phpsessionid);
// Optional: Redirect again to remove the extra query string data
}
// Helper to get QS values
function getParameterByName(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
session-starter.php (on domainB.com):
<?php
session_start(); // create the session cookie
$redirect = rawurldecode($_GET['redirect']);
// redirect back with the php session ID
// Optional: encode this information
$href = $redirect . '?phpsessionid=' . session_id();
header('Location: ' . $href);
exit;
HTML (in the body, on domainA.com):
Append PHP session information to the iframe src.
<script>
document.write('<iframe src="http://domainB.com/embedded-script.php?phpsessionid='+phpsessionid+'"></iframe>');
</script>
embedded-script.php (on domainB.com, in an iframe):
<?php
// Use the phpsessionid passed in
$phpsessionid = rawurldecode($_GET['phpsessionid']);
// REF: http://php.net/manual/en/function.session-id.php
function session_valid_id($session_id) {
return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}
// Check that this is potentially a valid session ID
if(session_valid_id($phpsessionid)) {
// Set the session to the one obtained in session-start.php
session_id($phpsessionid);
}
session_start(); // Only call this after session_id()!
// Rest of your code
*Considerations:
Don't actually use document.write, use jQuery or document selectors.
Encode the PHP session ID
Perform another redirect back to the base URL of domainA.com to remove the ?phpsessionid= in the URL for a cleaner look.
If you decide to call session-starter.php with AJAX instead, you will get a new PHP session ID every time for the same reason. The iframe will successfully use this session ID, but if you open a new page to domainB.com, the session will yet again be different.
If you want to run PHP within a file extended with .js, you can do this by telling your apache web server. Add the following directive to the .htaccess or directly to the apache config:
AddType application/x-httpd-php .js
After this is done, your server will run the included PHP code as soon as the file is requested from the server.
Update:
If you want to use sessions with JavaScript, you can do this with an AJAX solution. For this implement a web service on the server which should store the session values. Programming language for implementation can be PHP or another one which can be run by the web server. Request the web service with JavaScript. Here is an answer with an example.
If you want to redirect in Javascript, you can't use a PHP redirect which you have called from AJAX. You can pass the URL you create in PHP and send it back to JavaScript and do the redirect from there. You can do something like:
PHP:
session_start();
if (!isset($_SESSION['isIFrameSessionStarted'])) {
$_SESSION['isIFrameSessionStarted'] = 1;
$redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
echo json_encode(array('url' => $redirect));
}
JavaScript:
$.get('phpfile', function(result) {
if (!result) return;
var data = JSON.parse(result);
window.location.href = decodeURIComponent(data.url);
});
Don't know what you're trying to achieve exactly but let's say you want to go from php to js and back to php you could trying something like this:
Solution 1: Using XMLHttpRequest
In PHP (domain1.com):
<?php
$parameter = ""; //If you'll like to add a parameter here
echo "<script type='text/javascript'>window.addEventListener('DOMContentLoaded',". "function () { goToJS('$paramter');});</script>";
?>
In JS:
window.goToJS = function (parameter) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
//You can redirect back to a php file here
document.location.href = "domain1.com";
//You can view feedback from that php file you sent the stuff to here - just for testing
alert("feedback" + xmlhttp.responseText);
}
}
xmlhttp.open('GET', 'http://domain2.com/start-session.php?q=' + parameter, true);
xmlhttp.send();
}
Not sure about your redirect links and stuff but yeah this should pretty much work. Did something similar a while back
Solution 2: Using ajax
Using ajax you could have a JS script as follows. (type could be POST or GET, Used an example where you sent some json to the php file. Can change the data sent if you properly describe to me what you wish to send. Alternatively could be null also
In JS:
function init_() {
$.ajax({
type: 'POST',
url: 'http://domain2.com/start-session.php',
data: {json: JSON.stringify(selectedEvent)},
dataType: 'json'
}).done(function (data) {
console.log('done');
console.log(data);
}).fail(function (data) {
console.log('fail');
console.log(data);
});
}
In PHP:
Let's say you sent a javascript json to PHP. You could use it in PHP as follows:
<?php
$status_header = 'HTTP/1.1 ' . 200 . ' ' . 'OK';
header($status_header);
header('Content-type: text/javascript');
$json = json_decode($_POST['json']); //Do whatever you want with the json or data sent
echo "This is the returned data"; //Echo returned data back to JS or wherever
?>
why don't just use script directly (if you put this script on top of file it will wait the script to finish creating session in domain2 anyway. (I guess you have iframe in domain1 that call to domain2?)
<script src="http://domain2.com/start-session.php"></script>
USe jquery and jqxhr object for this request, no need send browser to second server, from domain1 you can request to browser load page to init session, and your client never see that.
//include jquery min library and do next code
$(document).ready(function (){
var jqxhr = $.get( "http://domain2.com/start-session.php", function() {
alert( "success" ); //some action for success
})
.done(function() {
alert( "second success" ); //when all is done (success done)
})
.fail(function() {
alert( "error" ); //some action for error
})
.always(function() {
alert( "finished" ); //some end action for anycase
});
});
you can delete .done function, .fail function, and always function as you wish.
NOTE: ready function is to make sure, that domain1 page completely load, and then run script.
reference https://api.jquery.com/jquery.get/

How to read a session variable from a php file in JavaScript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
There have been far too many questions on this subject but I still fail to understand.
Case:
Hyperlinked image
OnClick of image: Check if session exists
If session exist, open link
If session does not exist, show login form
onclick is calling a JavaScript function:
var my_global_link = '';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
// .. then show login modal that uses 'js/whitepaper-login.js'
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
Global variable is being saved in another php file as :
$_SESSION['logged_in'] = 1;
I am unable to capture the session value in the var check. Can you advise?
Using jQuery here is a simple example of how to get a PHP $_SESSION into your JavaScript:
session.php
<?php
session_start();
$_SESSION['foo'] = 'foo';
echo $_SESSION['foo']; // this will be echoed when the AJAX request comes in
?>
get_session.html (assumes jQuery has been included)
<script>
$(function() {
$('a').click(function(event){ // use instead of onclick()
event.preventDefault(); // prevents the default click action
// we don't need complex AJAX because we're just getting some data
$.get('session.php', function(sessionData) {
console.log( sessionData ); // session data will be 'foo'
});
});
});
</script>
click
If this is successful you'll see the data and can use it in other JavaScript functions by passing the data appropriately. I often find it handy to json_encode() session data, returning JSON to be used by JavaScript, but there is no need to in a simple example such as this one.
Make the request to someone file.php
$( document ).ready(function(){//run when DOM is loaded
$.post("file.php", //make request method POST to file.php
function(data){ //callback of request is data
var arr = jQuery.parseJSON(data); //make json decoding
if(arr.logged == 1) //arr.logged is value needs
#do
})
})
file.php
<?php
session_start(); //start session for my dear friend Jay Blanchard
$_SESSION['logged_id'] = 1; //init value for example
$array = array('logged' => $_SESSION['logged_id']);//creat array for encoding
echo json_encode($array); //make json encoding for call back
?>
your javascript is not a very good solution, as it can be hacked easily. One can simply change the value of check to whatever one likes, and even without a login one would be able to access the link of the picture.
A better implementation would probably be something like:
<img src="img.png" alt="" />
checklogin.php would then verify the $_SESSION variable. If validated, you can use header("Location: something.html"); to redirect to where you want to bring the user. If not logged in, you can instead redirect to the login page: header("Location: login.php");
#Sarah
You have to first call the php file via ajax and set the javascript variable as the result. Since the javascript is a client side scripting language hence it can't read server side PHP script.
Hence on click call javascript function
function someFunc(){
//Fire Ajax request
//Set check variable
//and perform the function you want to ...
}
<?php include "sess.php"; ?>
<script type="text/javascript">
var my_global_link = 'testr.com';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
</script>
<a href="#" onclick="show_login('test')" >test</a>
file1.php
<?php
session_start();
$_SESSION["logged_in"] = 1;
?>
sess.php
I have done this using two files. You may have not included session file I guess. Its working fine for me.

Pass parameters to location.href in javascript instead if HEADER()

I am new to wordpress.
I have tried the following code
header("Location: $location", true, $status);
I want to redirect the page to particular page and i am getting this kind of error
"Cannot modify header information - headers already sent by (output started at /home/content/c/l/a/clareb23/html/client4/wp-content/plugins/featured-articles-lite/main.php:773) in /home/content/c/l/a/clareb23/html/client4/wp-includes/pluggable.php on line 870"
Any suggestions would be appreciated.
Based on comment
You can do it like this:
<script>
window.location = '<?php echo $location?>?myvar=true&status=<?php echo $status?>';
</script>
Make sure that you do not echo/print anything on screen before header(...) statement and that there is no whitespace before opening php tag eg <?php. It is also good practice to put exit() after header() function.

Categories

Resources