How to prevent form submission on page load/refresh in php? - php

I am working on a html/php code as shown below in which I want to call a particular section of php code on click of a button.
<html>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['go-button'])) {
for each ($mp4_files as $f) {
}
}
?>
<form action ="" method="POST">
<table>
<td style="width:5%; text-align:center;"><button style="width:90px;" type="submit" name="go-button" value="Go" class="btn btn-outline-primary">Go</button> <!-- Line#B -->
</table
</form>
</html>
On click of a button at Line#B, the php code is call above and it goes inside the if block.
The issue which I am having right now is that on refresh of a page, it is also going inside the if block which I don't want to happen. I want if block to be active only on click of Go button.
Problem Statement:
I am wondering what changes I should make in the php code above so that on refresh of a page it doesn't go inside the if block. It should go only on click of a button at Line#B.

I'm not sure where you were having issues as such - in one comment you virtually hit the nail on the head as it were with how to prevent the form being re-submitted if the user reloads the page. You ought to be able to adopt an approach like the following - though if the PHP does generate content and it located within the document body somewhere you'd need to use output buffering to prevent errors regarding headers already sent
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' and !empty( $_POST['go-button'] ) ) {
foreach( $mp4_files as $f ) {
/* do stuff */
}
/* finished processing POST request, redirect to prevent auto re-submission*/
exit( header( sprintf('Location: %s', $_SERVER['SCRIPT_NAME'] ) ) );
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST">
<table>
<tr>
<td style="width:5%; text-align:center;">
<!-- Line#B -->
<button style="width:90px;" type="submit" name="go-button" value="Go" class="btn btn-outline-primary">Go</button>
</td>
</tr>
</table>
</form>
</body>
</html>

Related

How to run a function through my plugin page and print the result on that same page

I'm currently trying to add a debug page to my website. This page is simply dedicated to running some of the tasks done by my plugin and outputting some results on the same page.
I currently have a separate page in my Wordpress admin, this page contains a form and button that should be linked to a function that will do various steps and then return a value that must be printed on that page.
Here's the current code for the page and button :
function actu_admin_menu_option()
{
add_menu_page('Scripts', 'Sahar actus plugin', 'manage_options', 'actu-admin-menu', 'actu_scripts_page', '', 200);
}
add_action('admin_menu', 'actu_admin_menu_option');
// HTML page of the plugin
function actu_scripts_page()
{
?>
<div class="wrap">
<h2>Sahar actus plugin</h2>
<form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
</div>
<?php
}
function start_test()
{
return ("test started!");
}
add_action( 'admin_post_start_test', 'start_test' );
What I would like is for example to run the following function when clicking on the button and then outputting the returned value on the page.
function start_test()
{
return("test started!");
}
So when I press the button I want "test started!" to be printed on the page, currently clicking on the button redirects me to /wp-admin/admin-post.php which is a blank page.
I have no idea what is the best course of action to do it, should I make an ajax request on my button to run the function and then get the return value from that ajax call ? Or is there a better way to go about this ?
Thanks for helping me, have a great day
EDIT : Updated code, no errors but output is still not printed to page or console.
function actu_scripts_page()
{
?>
<div class="wrap">
<h2>Sahar actu plugin</h2>
<form action="" method="post">
<?php wp_nonce_field('do_test', '_test_nonce') ?>
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
</div>
<?php
if (isset($_POST['start_test'])) {
if (isset($_POST['start_test'])) {
if (!wp_verify_nonce($_POST['_test_nonce'], 'do_test')) {
// error in nonce
} else {
start_test();
}
}
}
?>
<?php
}
function start_test()
{
echo("hhhhh");
die(); // tried with and without, no difference
}
add_action('admin_post_start_test', 'start_test');
There are two ways to acheive this, both are fine, it just depends on the user experience you desire. Use the normal http form submission (what you have already), or use ajax. The normal form submission is the easiest method.
Submit the form using the standard method (what you have there), which will reload the page. Important Note it would be better to leave the action attribute blank like action="" if you are submitting the page to itself.
You will also want to add a nonce to the form using wp_nonce_field() and check its value in the submission block with wp_verify_nonce().
So your form would like something like this:
<form action="" method="post">
<?php wp_nonce_field('do_test', '_test_nonce') ?>
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
Add a php block to check if the form has been submitted and do your script in there, printing any output with php.
function start_test() {
// do things. If successful, return true. Otherwise return false
return true;
}
if( isset($_POST['start_test']) ) {
if( ! wp_verify_nonce( $_POST['_test_nonce'], 'do_test' ) {
// error in nonce
} else {
if( start_test() )
echo '<p>Success!</p>';
else
echo '<p>Failure!</p>';
}
}
There is a redirection happening through /wp-admin/admin-post.php that will return you back to the previous screen.
Your results are being printed on this page, and since it's redirecting, you don't get to see anything.
All you need to do to solve this issue, is add this after your debugging code:
die();
Or
exit();
This will stop the PHP from executing anything after your code. Thus, stopping the page from redirecting. Also, any functions that will run after you function, will not run normally, so if you're expecting saving for example, it won't happen after this piece of code.

PHP form pop-up for confirmation request

I would like to implement a pop-up request for the user , e.g. if the user press "yes" for confirm data on MySQL DB are modified otherwise no. This should be done without creating another php confirmation page. I looked through forum discussions , I founded some possible solutions based on Ajax or Javascript but unfortunately I don't know how to programme with these tools.
Can anyone helps?
many thanks
//$sql_select= "SELECT .... FROM DB
}
//------------------Button save data pressed--------------------
if (isset($_POST['bottone_update'])) {
// If te user click confirm button I have to modify the database
/*$sql_upd = "UPDATE db_sale.prenotazioni_alpha SET VALUES.....*/
}
?>
<html>
<head>
</head>
<style type='text/css'>
<meta charset="utf-8">
</style>
<body>
<form method="post" action="">
<!--Table data -->
<table class='table1' id="pos_table1">
<tr>
<td><textarea name="alpha_9_10"></textarea>
<td>
<td><textarea name="meda_9_10"></textarea>
<td>
</tr>
<tr>
<td><textarea name="alpha_10_11"></textarea>
<td>
<td><textarea name="meda_10_11"></textarea>
<td>
</tr>
</table>
<button type="submit">look for data</button>
<button type="submit">Save data</button>
You can simply add an onSubmit attribute to the form, with the JavaScript function confirm in it. It will open a pop-up in the browser, asking whatever you define within the first parameter, with two buttons: "OK" and "Cancel". This has the feature of returning true or false (a boolean), when clicking "OK" or "Cancel" respectively.
This means that if you do onSubmit="return confirm('Are you sure?');" in the form, you'll be able to send the form only if you press "OK" to this check. Then, in PHP, you just check weather or not the form has been submitted; and if it has - you perform your update-query, like you already started doing - no need for additional checks!
if (isset($_POST['bottone_update'])) {
// Perform your query
}
Your opening <form>-tag should then contain this:
<form method="POST" onSubmit="return confirm('Are you sure?');">
<!--- Rest of form goes here -->
</form>
If you have action="", you can just remove it altogether.
Try This:
$('#button').click(function () {
if (confirm('Are You Sure?')) {
$.post('http://localhost/ajax.php', function () {
alert('Data Added Successfully!');
});
}
});

Using forms from a tabbed index page

So I'm new to PHP and I'm having trouble getting some of my forms to function. I think it may be the way my site is set up that's causing me problems.
I have index.php which is set up as such:
<div class="pageContent">
<div id="main" style="width:1000px; margin:0 auto;">
<!-- Create the tabs -->
<div id="tabs" >
<ul>
<li>Overview</li>
<li>Ranked</li>
<li>Arena</li>
<li>Decks</li>
<li>New Game</li>
<li>Admin</li>
</ul>
<div id="tabs-0"></div>
<div id="tabs-1"></div>
<div id="tabs-2"></div>
<div id="tabs-3"></div>
<div id="tabs-4"></div>
<div id="tabs-5"></div>
</div>
<!-- Load the pages into tabs -->
<script>
$("#tabs").tabs();
$("#tabs-0").load("tab0.php");
$("#tabs-1").load("tab1.php");
$("#tabs-2").load("tab2.php");
$("#tabs-3").load("tab3.php");
$("#tabs-4").load("newGame.php");
$("#tabs-5").load("admin.php");
</script>
</div><!-- / main -->
</div><!-- / pageContent -->
This gives me a nice static page and 6 tabs of .php files to do cool stuff on.
There are a couple of forms, log in and such, in index.php which all function fine. But when I create a form on a page in a tab, it will not.
Here's an example from admin.php (#tabs-5)
<?php
if(isset($_POST['delLog'])){
unlink('log.txt');
echo 'Success';
}
if(isset($_POST['delLog'])){
unlink('error_log');
echo 'Success';
}
?>
<html>
<head>
</head>
<body>
<table width="100%" border="1">
<tr>
<td width="40%" valign="top">
</td>
<td width="30%" valign="top">
<h1>error_log</h1>
<form action="" method="post">
<input type="submit" name="delErr" id="delErr" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('error_log'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
<td width="3'0%" valign="top">
<h1>log.txt</h1>
<form action="" method="post">
<input type="submit" name="delLog" id="delLog" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('log.txt'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
</tr>
</table>
</body>
</html>
This is another, better example. A stripped down test I did yesterday for this question
Problems with $_POST
<?php
define('INCLUDE_CHECK',true);
include 'php/functions.php';
error_reporting(E_ALL);
ini_set('display_errors',1);
logThis('ready!');
if (isset($_POST['submit'])) {
logThis('success');
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Neither of these examples work. When the submit button is pressed the site refreshes but no PHP actions are taking place. There is no error message in error_log. I don't think it's getting the call at all.
Neither of the forms return an output, one adds to the database. The other deletes log files.
Hope I've provided enough details.
What ever you are trying to do is not possible at all. You can not load PHP code to frontend, it can only be processed by the server.
The statement $("#tabs-5").load("admin.php"); is fetching only the html code (processed by the server) not the PHP script
<form action="" method="post"> will post to the current page (ie. whatever is in your address bar).
When you load the pages into index.php using ajax, that means the forms will post to index.php... I'm guessing you are expecting to fetch the form submissions in each individual php-file
So to fix it either you have to also post using ajax (and refresh the tabs with the response), or you need to change the action attribute on the forms to each individual php-file... in which case you lose your tabbed layout when a form is submitted. You can work around that as follows:
In each of the php-files you do something like this (using newGame.php as example):
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
// ...and then redirect back to index.php
header("Location: index.php");
die();
} else {
//Print your form
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
}
Note that there should be no <html>, <head>, <body> or other html in the "sub-pages" at all - just the bare content you want inside the tabs...
Now for the ajax-submit method you should also remove all "wrapping html", you should still set a target="[...]" on each form, and you should still do form handling inside each individual file. But you should not do a redirect after form handling, but just output the form again:
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
//Maybe print a little message to let the user know something happened
echo 'Form completed at ' . date('H:i:s');
}
//...then print your form no matter what
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
Then add this script to index.php - it will post all forms inside the tabs using ajax instead of refreshing the page:
<script>
my_cool_ajax_post = function(form_elm, tab_elm) {
//Actual ajax post
$.post(form_elm.target, $(form_elm).serialize(), function(data){
//Results are in, replace tab content
tab_elm.html(data);
});
};
$(document).on("submit", "#tabs form", function(){
//Store the form element
var form_elm = this;
//Find the parent tab element
var tab_elm = $(this).closest('#tabs > div');
//Really simple "loader"
tab_elm.html('<p>loading...</p>');
//Submit by ajax
my_cool_ajax_post(form_elm, tab_elm);
return false;
});
</script>
Disclaimer: Completely untested, so let me know...

xss attack on a php page

In my security course teacher gave us a challenge to do so that we can practice with xss on a dummy website.
This website is composed by 2 php pages.
The first is called xss.php, and this is the code
<html>
<head>
<title>Equations</title>
</head>
<body>
<center>
<?php
if (isset($_POST['result'])){
$result = $_POST['result'];
if (intval($result) == 1){
echo "<h1>Ok, you are able to solve simple equations </h1><br>";
}
if (intval($result) == 0) {
header("Location: error.php?error=Type numbers!");
}
if (intval($result) != 1){
echo "<h1>Wrong result! Try again.</h1>";
}
}
else { ?>
<h1>Can you solve equations?</h1>
<h2>x^2 - 2*x + 1</h2>
<form method=POST action="xss.php">
<table>
<tr> <td>x:</td> <td><input type=text name=result></td> </tr>
</table>
<input type=submit value=Submit />
</form>
</center>
</body>
</html>
<?php }
?>
the second is error.php, and it's this:
<html>
<head>
<title>Error</title>
</head>
<body>
<center>
<h1>Error: <?php echo $_GET["error"]; ?></h1>
<center>
</body>
</html>
the request is to redirect someone to another website (I'll call it "http://whatever.com/" ). When I start the challenge I'm in xss.php and the only thing I can do is writing something in the input form (the one with name=result). What can I write?? Thank you
An XSS attack is one in which the page allows allows users to inject script blocks into the rendered HTML. So, first you must figure out how to do that. For instance, if the input from the user gets displayed on the page and it isn't html escaped then a user could do the following:
User enters :
<script>alert('testing');</script>
Following that, if when when viewing the page an alert is shown then the page is vulnerable to XSS.
Therefore if the user enters JavaScript as follows:
<script>window.location.href = "http://www.whatever.com";</script>
The user would be redirected.
You can pass by "error" GET variable a javascript code to redirect the page for whatever you want.
To do it,you'll access
error.php?error=<script>window.location.href="http://youpageurl.com";</script>
Then you have to be redirected to "yourpageurl.com" website

Submit button clicking changing the value of it to another thing

maybe very easy!
I'm php coder and I don't have experience in js but I must do this for one of my codes
suppose I have sub1 in page after clicking it must be that sub1 but value now is sub2
<html>
<head>
<title>pharmacy</title>
</head>
<body>
<form method="post" action="pharmacy.php">
<?php
//some code
if(array_key_exists('update',$_POST)){
//somecode
}
?>
<input type="submit" name="update" value="<?php echo if(isset($_GET['update'])) ? 'Show' : 'Update' ?> ">
</form>
</body>
</html>
show as function name does not really make sense here (imo), but you could do:
<input type="submit" name="sub" value="sub1" onclick="show(this)">
and
function show(element) {
element.value = 'sub2';
}
Important:
But that will actually not solve your problem. As soon as you click the button, the form is submitted, meaning the browser initiates a new request and will load a new page. So every change you made the current page is lost anyway.
The question is: What are you trying to do?
It seems to me that you should change the value of the button on the server side. You have to keep track which form was submitted (or how often, I don't know what you are trying to do) and set the value of the button accordingly.
Update:
I see several possibilities to solve this:
You could keep using JavaScript and send and get the data via Ajax. As you have no experience with JavaScript, I would say you have to learn more about JavaScript and Ajax first before you can use it.
You could add a GET parameter in your URL with which you can know which label to show for the button. Example:
<form method="post" action="?update=1">
and
<input type="submit" name="sub" value="<?php echo isset($_GET['update']) ? 'Show' : 'Update' ?> ">
Similar to 2, but use a session variable (and not a GET parameter) to keep track of the state.
Update2:
As you are already having $_POST['update'] you don't need the URL parameter. It could just be:
<html>
<head>
<title>pharmacy</title>
</head>
<body>
<form method="post" action="pharmacy.php">
<input type="submit" name="update" value="<?php echo isset($_POST['update']) ? 'Update' : 'Show'; ?> ">
</form>
</body>
</html>
This should do it
function show(){
document.getElementsByName('sub')[0].value = 'sub2';
return false;
}
Edit: if you don't want it to submit the form, just add a return false, but then you'd need to change your onclick from your submit button to your forms onsubmit;
<html>
<head>
<title>test</title>
<script>
function show()
{
document.getElementById("sub").value= "sub2";
return true;
}
</script>
</head>
<body>
<form method="post">
<input type='submit' id="sub" name='sub' value="sub1" onclick="return show()">
</form>
</body>
</html>

Categories