cookie expire on click of button - php

Can we add events to php.
Just as i want to log out ie. destroy my current session and delete the existing cookie on click of a button.
The button form action corresponds to same page drum.php
<?php
$h=0;
if(isset($_COOKIE["name"])) {
if($h==0) {
session_start();
if(isset($_SESSION['views'])) {
$_SESSION['views']=$_SESSION['views']+1;
} else {
$_SESSION['views']=1;
}
echo "You have been logged in as: ".$_COOKIE["name"].".Your session will expire in "."5min."."You have viewed this page ".$_SESSION['views'];
} else {
session_destroy();
setcookie("name",$name,time()-25);
}
} else {
echo "<form action='drum.php' method='post'><input type='text' name='name'></input> ` </input><input type='submit' value='Log in'></input></form>";
$name=$_POST["name"];
$expire=time()+2*60;
setcookie("name",$name,$expire);
}
?>

Yes, you can do that. At the start of the PHP page, write if(isset($_POST['buttonName'])) and then nest all your actions for that button within that. And make sure your form posts to that page itself.
Every time the page's requested, it checks whether the button has been clicked and logs out if true. If false, it shows the regular content.

Related

PHP cookie not working right after setting it

I am new to cookies, and tried to search for my problem, but couldn't find it.
My code:
index.php
<?php
if (isset($_GET["submit"])) {
setcookie("time",date('Y/m/d H:i:s'),time()+3600);
echo $_COOKIE["time"];
}
//Look if cookie isset, if not open overlay.
if (isset($_COOKIE["time"])) {
echo "<body>";
} else {
echo "<body onload='toggleOverlay(0)'>";
}
?>
When you open the page in the browser, the bottom part of the php code is executed, there shouldn't be a cookie 'time' so the body will be echoed with the onload="toggleoverlay()". This all works fine.
then when i click on the submit button to accepts the cookies, the page is reload, and the upper part of my php code is executed, a cookie named 'time' is created with the current time.
then the bottom part should be executed, but it still echos the body with the onload, even though i just created the cookie.
i also get the error when i'm trying to echo the cookie (saying the cookie does not exist). when i reload the page again manually then it works. But this is very frustrating since you need to accepts the cookie. then the page gets reloaded, and the overlay opens again.
I think this is because it takes some time creating the cookie and by then the other code has already been executed, but does anyone know how to fix this?
Thanks in advance.
The cookie is not set until the response is sent back to the client (browser). It is not available in your PHP until the next request from the client after that.
You could do next.
<?php
$cookie_set = isset($_COOKIE['time']);
if (!$cookie_set && isset($_GET['submit']) {
setcookie('time', date('Y/m/d H:i:s'), time() + 3600);
$cookie_set = true;
}
if ($cookie_set) {
echo '<body>';
} else {
echo '<body onload="toggleOverlay(0)">';
}
I have found a semi-solution, if the page is submitted, the page is reloaded, then after the cookie is created, i reload the page again en change the index.php?submit to index.php
like this
<?php
if (isset($_GET["submit"])) {
setcookie("time",date('Y/m/d H:i:s'),time()+3600);
echo $_COOKIE["time"];
header("Refresh:0; url=index.php");
}
//Look if cookie isset, if not open overlay.
if (isset($_COOKIE["time"])) {
echo "<body>";
} else {
echo "<body onload='toggleOverlay(0)'>";
}
?>
Like this it works, but it is not the best solution.

submit form only on button click not on page refresh

Below is my code, and is working fine.. The only problem is that when I refresh the page , It execute the success query.
<form action="" method="post">
<input type="submit" value="Purchase" id="btn" name="link_credits">
</form>
if(isset($_REQUEST['link_credits']))
{
echo "success";
//some codes here with sql statements
}
Else
{
echo " Please try Again tomorrow";
}
?>
Problem:
I don't want to run the query with page refresh, it should run the code only at button click.
Just add the line unset($_REQUEST['link_credits']); in success loop
if(isset($_REQUEST['link_credits']))
{
echo "success";
//some codes here with sql statements
if($success){
$_SESSION['msg']="Data Added successfully";
}
else{
$_SESSION['msg']="Data Not Added successfully.Please Check";
}
unset($_REQUEST['link_credits']);
header("Location:--somepage.php--");
}
else
{
echo " Please try Again tomorrow";
}
Then you can show the $_SESSION['msg'] value in --somepage.php-- and after showing use unset($_SESSION['msg']);
Your browser should be warning you that a page refresh will re-submit the form. So, you are clicking a button even when you refresh the page, or you are using a broken browser.
All that being said, here are some possible solutions:
Cookie the browser during the "success" phrase, and only allow the success condition to run if the cookie is not set/present.
Learn about "Redirect after POST", which is what you should be doing here. Essentially, you perform the success action, set flags as apropos, and forward the browser (via PHP's header()) to a page that says, "OK, it worked!".
Change your if condition to.
if(isset($_POST['link_credits'])){
echo "success";
//some codes here with sql statements
}
else
{
echo " Please try Again tomorrow";
}
This is because you are submitting the form to the same page with the method post, so when you refresh the page it novamento sent another request post.
Solution:
if(isset($_REQUEST['link_credits'])) {
echo "success";
$_REQUEST['link_credits'] = null;
} else {
echo " Please try Again tomorrow";
}
This happen because of simply on refresh it will submit your request again.
So the idea to solve this issue by cure its root of cause.
I mean we can set up one session variable inside the form and check it when update.
if($_SESSION["csrf_token"] == $_POST['csrf_token'] )
{
// submit data
}
//inside from
$_SESSION["csrf_token"] = md5(rand(0,10000000)).time();
<input type="hidden" name="csrf_token" value="
htmlspecialchars($_SESSION["csrf_token"]);">

Open Page Only After Redirecting

My question is may be foolish. But I want to know, if there is any code that prevent the page opening if tried with link but opens only after . if it's link is from another page.
for example, if i have a form on page contact.php and user gets redirected to page contact_success.php.
Now I want, if anybody tried to open contact_success.php page directly from browser address bar, it should not be get opened. It should be get opened only after form submission from contact.php page..
A simple way is just to use an if check on the contact_success.php page like
if($_SERVER['REQUEST_METHOD'] = "POST"){
//display page
} else {
echo 'You cannot view this page.';
//add redirect, if you like
}
Set a session or a cookie for the user in the contact.php, and then in the contact_sucess.php you can check if it exists.
for exmaple:
contact.php:
<?php
$_SESSION['visited_login'] = 'yes';
?>
contact_sucess.php:
<?php
if (isset($_SESSION['visited_login']) && $_SESSION['visited_login']=="yes") {
// output tanks
} else {
echo "go away";
die;
}
?>
You can use session for that example:
let say when you submit the contact form there is a page where in you will process the user input and i will use(refer to the #1)
contact_process.php
$_SESSION['success'] = 'success';
(this code will create a session)
then once success in processing the user input there is another page like(refer to # 2)
contact_success.php
if(isset($_SESSION['success'])
{
//Output if it is success
}
else{
header('location:contact.php');
}
(this code will check if session is existing if yes the desired output will show and if not it should turn back to contact.php)
you can easily learn session here http://www.w3schools.com/php/php_sessions.asp

Run a Jquery Login Form if php Login Check Fails

I do not want to redirect to a new page if the login check fails, rather I want to stay on the page and simulate a click on the login button which would bring up a login form popup. Any ideas?
Lame attempt using php redirect which doesnt do anything desired:
function logincheck($redirect='')
{
if(!isset($_SESSION['duser']['id']))
{
if($redirect)
{
header("Location: ".$config['site_url']."index.php? redirect=".urlencode($redirect));
}
else
{
header("Location: ".$config['site_url']."index.php#login-box");
}
exit;
}
}
HTML button:
<li><a class="log" href="#login-box"></a></li>
In your <head></head> define a javascript variable if the user is logged in or not such as
<script type="text/javascript" />
var logged_in = <? if(!isset($_SESSION['duser']['id'])){
echo "FALSE";
}else{
echo "TRUE";
}
?>
</script>
Now when you load the page check using javascript that if logged_in is TRUE or FALSE and base on that run the javascript to pop up for login panel
Hope it helps :)

Reload page in php

While designing sign up page I wish to reload page if user has submitted anything wrong in the fill up boxes. How can I reload page after the user presses submit button with a wrong entry ? (while verifying expected content through php)
You can use header() plus some _GET variables for telling the original page there were errors.
Form submit page:
<?php
//.... lots of code validation
if ($failed) {
header('Location: http://path.com/to/your/site/original_form.php?error=1');
}
?>
Form page:
<?php
if (isset($_GET['error']) {
echo "there was an error! Please fix it!";
}
?>
Try the following -
if (validation_failed) {
header("Location: http://yourserver.com/signup.php");
} else {
header("Location: http://yourserver.com/welcome.php");
}
PHP Header function

Categories