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"]);">
Related
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
why my echo doesn't work here in this code?It goes directly to the function header().
if($result){
echo("<script> alert('User Successfull Added')</script>");
header('location:home.php');
}
In order to make your code example work, you need to put it inside an if/else condition like so, if you want it to work, but since I only see what you posted as code, am putting this in as an example:
<?php
if($result){
echo("<script>alert('User Successfully Added')</script>");
echo("<script>window.location = 'home.php';</script>");
}
else {
header('Location: elsewhere.php');
}
Actually thy echo is working. but we cant see the message because at the same time the page redirects to the home.php page.
If you want to alert to display the alert message use jquery post. or php session variable
Assuming you want to both display the alert & redirect to home.php, why don't you just try setting a SESSION (or other global variable) and then check if it's set at the start of the redirected page?
Such as:
<?php
session_start();
$_SESSION['usercreated']="Y";
header('Location: elsewhere.php');
?>
and then on home.php at the start of your php code:
<?php
session_start();
if(isset($_SESSION['usercreated'])){
echo("<script> alert('User Successfully Added')</script>");
}
//....
?>
Sorry, I can't add comment here. But I think what you want to do needs Java and replace alert() with confirm()
var r=confirm("User Successfull Added")
if (r==true) // if user click OK
{
window.location.assign("home.php")
}
else // user click Cancel
{
}
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.
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
I have a simple input form on my site for people to enter in information for submission. The code looks like this in the case they do not enter anything:
this is form.php
if ($_POST['q']) == NULL ){
echo "Please enter your information"
The code works great, but it sends the user to form.php with the echo, where I want this to be echoed on my main page index.html right below the input box - basically so it doesn't navigate away from the page. Is this doable in php or will I need some javascript. I would have searched for ways to do this but I don't know what this method is called.
Thanks!
dont set a action in the url and it will submit to its self, if that still wont work you will need rewrite rules.
If you don't want to navigate away from the page you will need to use Javascript. Add a onSubmit to the form, and then let the function you call there return false, if the input is not complete and the form should not be submitted.
you can make it postback to itsself and then redirect the page to post.php?q=value if there is a value else echo below the input field.
<?php
$qisempty = false;
if(!empty($_POST['q']))
{
header("Location:http://../post.php?q=".$_POST['q']);
}
else
$qisempty = true;
?>
<input name="q" type="text">
<?php if($qisempty) echo "Please enter your information";?>
You can use AJAX for this thing. AJAX is great for this type of problems when you don't want to reload pages to do task in specific place or Div of HTMLpages.
For your problem, You need to create a HTML file with your form in it, and submit it via AJAX. and get your response via same AJAX.
<script type="text/javascript">
function submit_ajax(val1,val2,param1,param2,subfile){
var http = new XMLHttpRequest();
var url = subfile;
var params = val1+"="+param1+"&"+val2+"="+param2;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
//Remove the alert and use whatever you want to do with http.responsetext like
// document.getElementById("YourDiv").innerHTML=document.getElementById("YourDiv").innerHTML +http.responsetext
}
}
http.send(params);
}
</script>
</head>
<body>
<form>
<input type="text" id="user" value="user" name="user" />
<input type="password" id="password" value="pass" name="pass" />
<button onclick="submit_ajax(user.name,password.name,user.value,password.value, "submit_file.php");">Submit</button>
</form>
<div id="YourDiv">
<!--Something appears here after callback-->
</div>
This was the first page. Now Use your script in your PHP file(probably, submit_file.php) as you want and then echo the text you want in your div by validation or something.. a sample would be
<?php
$username=$_POST['user'];
$password=$_POST['pass'];
if(validateuser($username,$password)){
if(checkuserpass($username,$password){
echo "You were successfully logged in!";
}
echo "Sorry Username/Password Mismatch";
}
else {
echo "There was an error in your input!Please Correct";
}
?>
Hope you got what you wanted...
The simplest way would be assigning the error message to a variable called (e.g $errorMsg)
the printing it on page using a echo or print function.
<?php
if ($_POST['q']) == NULL ){
$errorMsg =' Please enter your information';
}
?>
Place this code where you want the error to appear
<? print $errorMsg; ?>