Variable changes after reloading the page - php

So I am having a problem. I (probably) know what the problem is, but I dont know how to fix it.
I have a forum, with questions and comments. Now the username of the person who posted the question/ comment is a link to his/her profile. When I get to that link, I check wether the persons username is my username. If it is I can edit the profile with a button. Now when I click the button, I get errors and I'll explain why I think so. First i'll show you my code. This is on top of my profile page:
if(!empty($_GET['thread_username'])){
//If thread username link was clicked
$profileusername = $_GET['thread_username'];
}
else if(!empty($_GET['comment_username'])){
//If comment username was clicked
$profileusername = $_GET['comment_username'];
}
else{
}
$profileusername=$mysqli2->real_escape_string($profileusername);
The button on the profilepage reloads the page(and more) so that it goes through this code again, BUT the $_GET['thread_username']and the $_GET['comment_username'] are from the previous page. So when I reload it, these doesn't exist(So they are empty) and the page goes through the else. I have tested if it goes through the else by just giving the $profileusername a variable and it does. So when it goes through the else, the $profileusername isn't declared so I get all sort of errors. My problem is that when the page reloads, it shouldn't go through the else. It should just check the $_GET, but the page says it doesn't exist which I understand but how can I fix this?
My form now:
echo
<<<EOT
<form action="profile.php" method="post">
<input name="edit" type="submit" value="edit"></td>
<input type="hidden" name="thread_username" value="{$_REQUEST["thread_username"]}"/>
<input type="hidden" name="comment_username" value="{$_REQUEST["comment_username"]}" />
</form>
EOT;

Use $_REQUEST instead of $_GET, see the comments to the question.

Related

How to run a php code, only if the "submit" button redirect you.

This is my admin panel code:
<form action="connectdb.php" method="post">
<input type="text" name="name">
<input type="submit">
</form>
So, It so, the code in connectdb.php will only run, if the "submit" button redirects a user to it. It will not run, if a user directly open /connectdb.php page.
Do I need to start some session, something like that?
Note: I am a newbie, so please explain in detail.
Since your form is using method="post"you can place the following code at the very beginning of your connectdb.php file:
<?php
if (empty($_POST)){
exit;
}
//The rest of your code goes here
This checks to see if the $_POST variable either does not exist or does exist but is empty. If this returns true that means your form was not submitted and a user went to the page directly. The script will then exit and a blank screen will be displayed.
Instead of displaying a blank screen, you may instead want to redirect to a different page such as this:
<?php
if (empty($_POST)){
header("Location: index.html");
exit;
}
//The rest of your code goes here
Whenever you do a redirect like this, it is important to place an exit; statement directly after it, otherwise your script could still process some of the other statements and send data to the browser that shouldn't be sent. This of course could be a security risk in some cases. An exit statement prevents this kind of security risk.
Not sure if you really need it, but you can add a name attribute like the following:
<input name="submit_button" type="submit">
So when you click this button a $_POST['submit_button'] variable will be created on the PHP side, and then you can use it to check if the button was clicked:
if(isset($_POST['submit_button'])){
// your code
}
<input type="submit" name="submit_btn">
Now in your connectdb.php check,
<?php
if(isset($_POST['submit_btn']))
{
//do your code
}
else
{
//redirect to your home page
}
?>

How can I detect the last visited page with php?

I am on my page index.php. From here I go with a link to myform.php.
myform.php:
<?php
echo "My last visited page is:".$_SERVER['HTTP_REFERER'];
?>
<form action="success.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
The result I see on my page is:
My last visited page is http://www.mypage.com/index.php
Now I submit my form and come to success.php. Here I click my "back" button and come again to myform.php.
The result I see is now:
My last visited page is http://www.mypage.com/index.php
But what I expect here is:
My last visited page is http://www.mypage.com/success.php
You can use sessions..
Bottom of the success.php you can assign page name to sessions
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
When click on back button you can get that value using sessions(index.php),
echo $_SESSION['page'];
On that page at the bottom, you can assign current page name to session, then it can track on next page
The back button does strange things with variables and page refreshing. Try typing the http://www.mypage.com/myform.php address into the browser and seeing what happens.
N.B. I know this only deserves to be a comment, but reputation is a pain.
As you need to carry the previous info to forwarded page. Then it will be better if you use session. When you are visiting a page, store this current page in a session variable. Add this line at bottom on each page.
$_SESSION['page'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
And to echo
<?php
echo "My last visited page is:".$_SESSION['page'];
?>
So whole text will look like:
<?php
echo "My last visited page is:".$_SESSION['page'];
?>
<form action="success.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
<?php
$_SESSION['page'] ="http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>
edit: Be careful when you are using multiple tab. Only latest info will be stored.
One way is, you can handle this by using PHP's _SERVER global, If the user first time visits your site, there will be no previous page, except that, the previous page will be last visited page identified by _SERVER, check out this script,
isset($_SESSION['current']) || $_SESSION['current'] = '';
// check for first visit to any page, initialize
if($_SERVER['SCRIPT_NAME'] != $_SESSION['current']){
// check if current page != previously recorded page
// order is important here in two lines, check it yourself
$_SESSION['previous'] = isset($_SESSION['current']) ? $_SESSION['current'] : '';
$_SESSION['current'] = $_SERVER['SCRIPT_NAME'];
}
You can make something like this, which ignores same page if user refreshes the page, disregarding the method being GET or POST.
You can include this script in common file to record the activity.
Array
(
[current] => /session/index.php
[previous] => /session/submit.php
)

trying to unset my session['where'] not only clicking on my submit input... but also with page refresh

I have a list of posts in my page, and I also have a form to search for posts.
This is my form:
<form action="" method="post">
<input type="text" name="search" onclick="if(this.value=='Search:')this.value=''" onblur="if(this.value=='')this.value='Search:'" value="Search:" />
<input type="submit" value="Search" name="sendForm" />
</form>
And then, when my form is submited with some values I store a session with my sql condition statment and I get only my list of news that have title like the value I wrote in my input.
And then, If I submit my form without any value I unset my session and I get my list of all news again.
if(isset($_POST['sendForm'])){
$search = $_POST['search'];
if(!empty($search) && $search != 'Search:'){
$_SESSION['where'] = "WHERE title LIKE '%$search%'";
header('Location: dashboard.php?exe=posts/index');
}
else{
unset($_SESSION['where']);
}
}
And this is working fine, but I need to click on my input search to unset my session and get all news again.
Even if I refresh my page Im getting only my news with title that I wrote in my input, and only if I click on my submit button I get again my list with all news.
Do you see how I can solve this, how I can unset my session not only clicking on my submit again but also with page refresh, becausee I want to show all news when I click in my link dashboard.php?exe=posts/index
Im trying with this code below on top of my page, but like this my search form is not working, is not returning any results.
if(!empty($_SESSION['where'])){
unset($_SESSION['where']);
}
Another quick alternative is instead of unset, you can set $_SESSION['where'] == "" then your query will not be affected as it does only contains nothing. Also please take note that your code is vulnerable to SQL injection attack.
You could store the user last visited page in session, and if it's the same than your current page and there is no submit, you know that it's a refresh.
Alternatively you could use the referer ($_SERVER['HTTP_REFERER']) although it's less reliable because it's client data and can be tampered.

Object Oriented PHP to pass message to user upon success of function

I am new to OO php so this may seem basic..
Basically I have a list of courses a user can book. I have got it so the user can remove the course from their list, but I want a message to be displayed to them after they delete. I have done something similar to what I want here:
<form name="removecourse" action="<?php bloginfo('url');?>/user/<?php echo $current_user->first_name ; ?>" method="post">
<input type="hidden" value="<?php the_id();?>" name="courseid" />
<input id="removebutton" type="submit" name="removecourse" value="Remove">
</form>
The form sends the required data to the same page, and at the top of that page is a check to see if the forms post name is present in $_POST[] like so:
if(isset($_POST['removecourse']) && !empty($_POST['removecourse'])){
$courseManager->delete_post($_POST['courseid'], $_POST['cancel-reason']);
echo $courseManager->delete_response;
};
This is where the Class and object part comes in...
public $delete_response;
function delete_post($postid, $reason){
//stuff to actually delete the post
$this->delete_response = 'Thanks, your course has been removed.';
}
So here I am adding a value to the delete_response variable and calling it above at the top of the page. This works, but when I refresh the page the message is still there as I am resubmitting the POST. I am just wondering if what I am doing is along the right track, and how to implement a Post/Redirect/Get type functionallity to stop the messaage from appearing on page refresh?
You have to check, either your course has been already deleted, is it simple as that :).
Yours displaying it again because:
if(isset($_POST['removecourse']) && !empty($_POST['removecourse'])){
//is always true when posted again.
}
You have to check the existiance

redirect to current page if user clicks back or refreshes the page

Sorry I have posted this question and I googled it alot still Im unable to solve this
I have a php page that has a form and when user clicks refresh or F5 it creates duplicate values in the database and also a message is alerted to the user, indicating resubmitting may insert duplicate values in database.My boss dont want that alert box of the browser to user and also insertion of duplicate values into the database
I know its header(). I read lot of header() in php manual and also server_name functions but still I tried in many ways putting in the top but cant solve it. its very important. can anyone please help me with a sample of code explaining the way to do.any help is greatly appreciated.
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
demo.php
<?php
$firstname = $_POST['fname'];
?>
Tell me what should i add in the demo.php page to stop it from submitting the form again and again and also if user clicks back button on the browser it should not direct to the previous page , it should still redirect to current page.
So if user clicks refresh or back button it should redirect to current page only and should not insert any duplicate values and also alert box should be disabled.Please explain me what to do here, im in deep help.Thanks
There's lots of things wrong with your code, and lots of ways to mitigate the impact.
First, why are you creating duplicate entries?
In addition to the problem of bad data is also implies that your site is vulnerable to CSRF. Go read up on how to prevent CSRF with single-use tokens.
If you've got performance problems with your site, then users will often click on the submit button multiple times. While addressing the duplicate submission problem on the database, use javascript to disable the submit links on the page and provide visual feedback that the page is doing something.
Redirects are not the way to solve the problem.
My boss dont want that alert box of the browser
Are you talking about the duplicate post alert? While you can get around this using PRG, that creates other problems.
You must post a unique id (session_id) and save it in the database.
When your registration, test if the session_id is already present. If so, send a message to THE USER. "You have already post out this form"
The code:
<?php session_start; ?>
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
<input type="hidden" name="session_id" value="<?php echo session_id();?>">
</form>
demo.php
<?php
//test session_id in database
$session_id = session_id();
mysql_connect('localhost','xxx','xxx');
mysql_select_db('xxx');
$return = mysql_query("SELECT COUNT(*) AS nb_data FROM TABLENAME WHERE session_id='".session_id()."'");
$data = mysql_fetch_assoc($return);
if ($data['nb_data'] == 0){
echo 'Your message';
}
else{
$firstname = $_POST['fname'];
//.....
header('location:xxx.php')?
}
?>
I would use php header function to replace the current location so if the user clicks refresh, it won't repost the information and a session to store the posted value and check for resubmissions.
demo.php
<?php
session_start();
if($_POST)
{
if(!isset($_SESSION[fname]))
{
//database queries here
}
$_SESSION[fname] = $_POST['fname'];
header('location:demo.php', true); //true replaces the current location
}elseif(!issset($_SESSION[fname])){
header('location:form.php');
}
$firstname = $_SESSION[fname];
?>
form.php
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
You need ON DUPLICATE KEY , this will update the record instead of creating a copy of it :
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
so it wouldn't matter if they hit refresh or resubmit, if the record existed already it would just get updated.
The solution will be to redirect the page after database operations like insert, update and delete
pageName: test.php
if(isset($_REQUEST['deleteBtn']))
{
$emp_id=$_REQUEST['emp_id'];
$count=mysql_query("delete from employees where emp_id=$emp_id");
header("location:test.php");
}
This way if you click F5 or back button the form data will not get posted again.
What you want is to embed a session id in your form when you create it, and to track that session id on the server. Then, when the form is submitted and you are processing the form on the server, if the form was submitted more than once, you can overwrite the first submission in your database, or respond with an error message, or whatever. (Show the popup only on the first submission, whatever.)
An easy way to do this is to generate a session id, send it as a hidden field in the form, and when the form is submitted store the session id in your database with the constraint that the session id be unique.

Categories