I'm trying to execute some PHP that removes a cookie from your browser (it's used for removing your login data cookie) and when you click on the button called 'Log Out'I tried using an action to do this, but it does not seem to work this way?
<?php
if(isset($_COOKIE['LoggedIn']) && !empty($_COOKIE['LoggedIn'])) {
echo "<li>Log Out</li>";
} else {
echo "<li>Log in</li>";
}
?>
I am using the '\' to change make the quotes into regular text quotes that can be placed inside the main quotes.
So my question is mainly, how will i achieve executing it correctly? I've tried it this way but it does not do a thing.
Better still link your a href tag to a php file that runs the function you need and use
header("Location: Your URL")
To redirect back to the login page or anywhere you want
You could use something like this;
<a href='/?logout'>Logout</a>
if(isset($_GET['logout'])){ Logout(); }
function Logout() {
unset( $_SESSION[''] ); // unset and session data
session_unset(); // remove all session variables
session_destroy(); // destroy the session
setcookie("LoggedIn", "", time() - 36000, "/"); //unset the remember me cookie
header( "Location: /?loggedOut=1" );
exit;
}
As far as I'm aware anchor tags ("a" tag) have no concept of an "action" attribute. I think what you want here is "onclick" instead of "action".
Occurs to me you are also trying to execute a php function in the "action" attribute, this clearly will not work - you need to create a simple javascript function that clears out the cookie. For example:
var deleteCookie = function(name,path) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;' + (path ? ' path=' + path : '');
};
Which you can then invoke in an "onclick" on your link.
I reccomend just having a logout.php button which redirects to the login page after logout button has been clicked like so:
echo "<li>Log Out</li>";
Logout.php
//Expire Cookie
setcookie('LoggedIn', '', time() - 60*100000, '/');
//Redirect to page
header( 'Location: https://www.foo.com/login.php' ) ;
Related
I submit all forms of my website to a specific page page form_submition.php, after processing the form data I redirect to another page index.php?page=some page using header function
but in one of my forms that named main_form I get a wrong redirection
if(isset($_POST['form1']))
{
// process form data
header('Location: ../index.php?page=some page')
}
if(isset($_POST['form2']))
{
// process form data
header('Location: ../index.php?page=some page')
}
$to=$_GET['to']
if (isset($_POST['main_form']) ) {
// process form data
}
header("Location: ../index.php?page={$to}&error_loc_{$error_loc}=1&err_msj=" . $err_msj, true, 302);
exit();
but it redirects me to mywebsite.com/folders/form_submitions.php?to=all_p
instead of mywebsite.com/index.php?page=all_p
any ideas?
UPDATE 1
I checked my code a lot, it seems that the header is not redirecting the page at all. the strange thing is that the page at mywebsite.com/index.php?page=all_p gets loaded but the url won't change and the css+js files not loaded because the relative path becomes invalid.
UPDATE 2
Further Checking my code, before submitting the main_form to form_submission.php I open a new window with javascript to print some data. the following is the form:
<form enctype='multipart/form-data' action='./forms/form_submitions.php?to=all_p' onsubmit="return checkfiles('attachfiles')">
.
.
.
<button id="main_form" name="main_form" class="btn btn-primary">Save Changes</button>
</form>
I call the following function when #main_form is clicked:
$("#main_form").on('click', function(event) {
newWin = window.open('printingpage.php?data='+ data);
setTimeout(function () { newWin.print(); }, 500);
});
Here the printing function won't return unless the print preview is closed. I think this creates the problem, because when I remove the newWin.print() function, everything works just fine.
is there any ways to make this printing asynchronous?
remove .. parts in your paths & try.
So the code will be :
if(isset($_POST['form1']))
{
// process form data
header('Location: /index.php?page=some page')
}
if(isset($_POST['form2']))
{
// process form data
header('Location: /index.php?page=some page')
}
$to=$_GET['to']
if (isset($_POST['main_form']) ) {
// process form data
}
header("Location: /index.php?page={$to}&error_loc_{$error_loc}=1&err_msj=" . $err_msj, true, 302);
exit();
Try this. Put your web link in your redirection link.
$data = array(
'page' => $to,
'error_loc_'.$error_loc => 1,
'err_msj' => $err_msj
);
header("Location: http://www.mywebsite.com/index.php?".http_build_query($data), true, 302);
Hope this helps.
I'm trying to do some protective stuff to prevent pages from accessing databases when a php page has been idle and the session has expired because of inactivity. I'm basing some of it on session_status() and am having issues with that.
Using alerts and console.log, I find the php and js code seems to be ok. When I artificially inject session_status() values, I get the results I expect.
The problem seems to be that session_start() always returns 2 (available) even after the session has timed out.
Should I not expect system_status to be updated automatically after inactivity timeouts? Is there a better way than session_status() to check for session status?
Here is the 'onclick' function that returns '2' for system_status() on an expired page when the button is clicked:
$("#save-to-database").click(function () {
var active = <?php echo session_status(); ?>;
if(active == 2) { //the session is active, do the sort & save
saveStuff();
} else { // the login has expired, abandon this and reload index.php
window.location.replace("index.php?artist=" + <?php echo $artist ?>);
}
});
This a long way to go about this but this works fine.
function isSessionActive() {
session_start();
$lastActivity=$_SESSION['lastActivity'];
if ($lastActivity!=null && ($lastActivity+(10*60) > time())) {
$_SESSION['lastActivity']=time();
return true;
} else {
deleteSession();
return false;
}
}
function deleteSession() {
session_start();
setcookie("PHPSESSID", "", time() - 3600, '/');
session_unset();
session_destroy();
}
I have a logout function that looks like this.
if ($_GET["argument"]=='logOut'){
if(session_id() == '') {
session_start();
}
session_unset();
session_destroy();
$host = $_SERVER['HTTP_HOST'];
$extra = 'index.php';
header("Location: http://$host/$extra");
exit;
}
My problem is that, If I inspect the page and look at the Network preview and response, it looks 'fine'.
There are two php files listed that was processed.
http://localhost:5000/inc/mainScripts.php?argument=logOut
which is where the function is located.
and http://localhost:5000/index.php
Which is where i would like to be redirected.
The Response tab in the Network of the inspect page area in chrome
contains the full login html page login.php but in the browser it remains in the same place. Like the header command has never been called.
What Am I doing wrong?
HTML AJAX call to this function:
$("#logout_btn").click(function() {
$.ajax({
url: './inc/mainScripts.php?argument=logOut'
})
});
SOLUTION
AJAX
$("#logout_btn").click(function() {
$.ajax({
url: './inc/mainScripts.php?argument=logOut',
success: function(data){
window.location.href = data;
}
});
});
PHP
if ($_GET["argument"]=='logOut'){
if(session_id() == '') {
session_start();
}
session_unset();
session_destroy();
$host = $_SERVER['HTTP_HOST'];
$link = "http://$host/index.php";
echo $link;
}
Try this instead.
if( isset($_GET['argument']) && $_GET['argument'] == 'logOut' && !empty( session_id() ) ) {
session_destroy();
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/index.php");
exit;
}
Edit: If you're using AJAX, it'd be easier to send the url from your php script back to your javascript and redirect from there.
You are probably running into the same common problem that many people run into when people first start to program in PHP.
Calls to header() only works when there are NO previous HTML output generated. If there are any HTML output generated, even just a single space, calls to header() will fail. To get around this problem, use functions such as ob_start() and ob_end_flush().
I have a simple registration form and the new comers will be registered with an ajax function. There I create a $_SESSION['is_logged'] when the registration is finished.
On var_dumb I get that the var is set. But when redirect on another page it is empty (I have included already the session_start() on the both pages...
I have read somewhere in the net that:
"Sessions are ONLY written on a page load/refresh".
Is this the case, or I have to look for some other issues within my code.
the ajax:
$.ajax({
url:"../controllers/register.php",
type:"POST",
data:res,
success: function(responce){
if (responce==1) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>It seems that you have already submited the form. Click to "+
" <a href='login.php'>log-in</a> or to <a href='register.php'>register</a>.</p>");
}
else if (responce==2) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>You have successfully created account. Click to "+
" <a href='start.php'>welcome</a> to start your .</p>");
$('.menu').append("<li><a href='logout.php'>Log out</a></li>")
}
else{
$('#msg').text(responce);
}
},
error: function(){
$('#msg').text("Opss, try again");
}
});
the register.php file:
if (isset($_SESSION['submited'])) {
echo 1;
exit;
}
include_once('../models/functions.php');
// Give the post parametters to another var
$arr=$_POST;
// function for uploading
$reg = registerMe($arr);
if ($reg === true) {
$_SESSION['submited']=1;
$_SESSION['is_logged']=1
echo(2);
}
else{
echo($reg);
}
exit;
The session_start(); is included in the header of the first page where from the ajax is started.And the second page - where the $_SESSION['is_logged'] is lost, again the session_start(); is part of dc_header(); function. start.php:
<?php
dc_header("Речник|Регистрация");
if (!isset($_SESSION['is_logged'])) {
#header("location: ../views/login.php");
var_dump($_SESSION);
}
?>
add
session_start();
to the top of register.php
You need to specify session_start, so your server who was commanded to execute "register.php" (either from ajax, direct call, browser scripts, cron job or whatever possible you-name-it) will handle the execution and the setting of $_SESSION variables in reference to the connected clients session. Server won't guess by itself that this is an "ajax call from an already session_start page". You need to specify that whatever is done in register.php is done in the current client's session.
I have a logout.php page. This gets called by clicking logout that has this javascript attached to it:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
button.onclick = function() {
FB.logout(function(response) {
window.location = 'logout.php';
});
}
}
});
On the logout page i have this php code running:
if (isset($_COOKIE['fbsr_' . $app_id])) {
setcookie('fbsr_' . $app_id, $_COOKIE['fbsr_' . $app_id], time() - 3600, "/");
setcookie('PHPSESSID', $_COOKIE['PHPSESSID'], time() - 3600, "/");
unset($_COOKIE['fbsr_' . $app_id]);
unset($_COOKIE['PHPSESSID']);
}
The problem is that the javascript does log someone out. The php script will not remove the fbsr and the phpsessid cookies. How can I get around this issue?
For some of the applications, FB sets the fbsr cookie under ".your-domain.tld" domain (notice the preceding point). The cookie won't be deleted unless you specify the correct domain. Try this and you'll have logout working:
setcookie('fbsr_' . $appID, '', time()-3600, '/', '.'.$_SERVER['SERVER_NAME']);
It's a FB bug that makes the cookie not be deleted at logout, so your $fb->getUser() API call returns the former user ID instead of NULL or 0. This is FB world ;)
Greetings!
I had the same problem, even though all cookie pars were right (doublechecked)
What seems to work for me, is
setcookie($cookie_name, '', null, '/', '.'.$base_domain);
note the null value instead of: time()-3600
I honestly dont know why that works and the time()-3600 does not, but I cross checked and it works... HTH