Hi have checked answer from this page: But it uses action="" is it vulnerable to XSS attacks? If yes then without such solution what are my options?
I tried using header redirect. But as I have 2 forms,(in some pages 4-5 forms) header re direction is not working for me with errors.
Here is my code: (Simplified)
1st form: works ok with a redirect.
<form name="ip_block" method="post" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="submit" class="btn btn-default"
name="ip_block_add">Submit</button>
</div></div>
</form>
<?php
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
header("refresh:5;url=./admin-security.php");// avoiding form
resubmission
echo 'Added successfully';
}
else {
echo 'failed to insert';
}
}
?>
Form 2:
<form name="clear_data" method="post">
<input type="hidden" name="data_clear" value="1"/>
<button type="submit" class="btn btn-warning">Clean Data</button>
</form>
<?php
if(isset($_POST['data_clear'])){
if($mysqli->query("CALL clear_old_data")){
header("refresh:5;url=./admin-security.php");// avoiding form resubmission
echo 'operation successfull';
}
else
{
echo 'database failure';
}
}
//----
?>
For Second form I get error like this
Warning: Cannot modify header information - headers already sent by
For 2nd form I am using header before echo still it doesn't work.
reference, I tried with javascript too but that failed.
echo "<script>setTimeout('window.location.href='./admin-
security.php';',4000);</script>";
Updated with Dainis Abols idea: but form re submit option is still showing on page refresh
<form name="clear_data" method="post">
<input type="hidden" name="data_clear" value="1"/>
<?php
$var=111;
$_SESSION['var']=$var;
?>
<input type="hidden" value="<?php echo $var; ?>" name="varcheck"
/>
<button type="submit" class="btn btn-warning">Clean
Data</button>
</form>
<?php
if(isset($_POST['data_clear']) &&
($_POST['varcheck']==$_SESSION['var'])){
// Some code
}
I'd rather use ajax to send data to the database, without form submiting, and on success I would use js to redirect to /admin-security.php. In this case it's not possible to send the data twice.
Here is the PHP Code:
<?php
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
echo 1;
}
else {
echo 0;
}
exit;
}
?>
HTML:
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="button" onClick="send_form()" class="btn btn-default"
>Submit</button>
</div></div>
</div>
And AJAX written with JQuery
<script>
function send_form() {
$.ajax({
url: "./admin-security.php",
type: "POST",
data: {
ip: $("#ip").val()
},
success: function(response) {
if(response==1) {
alert("Done");
location.href = "./admin-security.php";
}
else alert("Fail!");
}
});
}
Related
I am facing an issue while validating the input fields inside the form using PHP and JavaScript. I am providing my code below.
<form autocomplete="off" action="<?php echo base_url() . $tourModule; ?>/search" method="GET" role="search" onSubmit="return checkform();">
<input type="text" data-module="<?php echo $module; ?>" class="hotelsearch locationlist<?php echo $tourModule; ?>" placeholder="Tourist Destination" value="<?php echo $_GET['txtSearch']; ?>">
<input type="hidden" id="txtsearch" name="txtSearch" value="<?php echo $_GET['txtSearch']; ?>">
<div class="col-md-12 form-group go-right colspecing col-xs-12 submit text-center">
<button type="submit" class="btn btn-lg pfb0 loader">
<?php echo trans( '012'); ?> </button>
</div>
</form>
<script type="text/javascript">
function checkform(){
console.log('validate form');
var textname=document.getElementById('txtsearch');
if (textname.value=='' || textname.value==null) {
alret('Please select Tourist Destination.');
return false;
}else{
return true;
}
}
</script>
Here I need before submit the form the input field will validate but in my case when I am clicking on submit button checkform function is not executing at all. I need to check that validation.
There is a typo in your code. Change alret to alert
I have this form
<form role="form" method='post' action='index.php' id='cme'>
<input type="hidden" name="bonval" value="<?php echo $bonval ?>" />
<fieldset>
<h2 class="blink_me" style="color:green;font-size:40px;"><?php echo $bonval ?></h2>
<div class="form-group">
<center>
<div class="g-recaptcha" data-sitekey="siteky"></div>
</center>
</div>
<div class="row">
<center>
<input type="submit" name="claim" class="btn btn-lg btn-success btn-block" value="Claim Now" id="claim">
</center>
</div>
</fieldset>
</form>
I have this javascript to disable button after click
<script>
$(function(){
$('#claim').on('click',function(){
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#cme').submit();
});
});
</script>
and this is my form validation
if(isset($_POST['claim'])) {
$recaptcha = $_POST['g-recaptcha-response'];
if(!empty($recaptcha)) {
# Use the recaptcha function here
$resp = getGoogleRecaptcha();
if($resp['success']) {
# Capture value from the form submit
$bonval = $_POST['bonval'];
# Insert normally
$db->fetchVal("insert into log (`user_id`,`amount`) values (?,?)", array($id, $bonval));
}
} else { ?>
<div class="overlay"><div class="popup" style="background:red;">
<h2>Error</h2>
<a class="close" href="#">×</a>
<div> <center><span class="blink_me">Seems error</span></center></div>
</div></div>
<?php }
}
My issue is button gets disabled but form is not submitted
if user refresh page form keeps getting submitted into database
Edit: sorry, lack of explanation, I read a little fast:
You can completely remove the var $ _POST after insert bdd with unset($_POST['...']);
if(isset($_POST['claim'])) {
//code
$db->fetchVal("insert into log (`user_id`,`amount`) values (?,?)", array($id, $bonval));
unset($_POST['claim']);
//code
}
You should stop the button from submitting form first by replacing the type="submit" by type="button" :
<input type="button" name="claim" class="btn btn-lg btn-success btn-block" value="Claim Now" id="claim">
Hope this helps.
How to execute Jquery Ajax post data on multiple pages.
For Example, I am using three pages named Page1,Page2,Page3. I need to post data from Page 1 -> Page2 and,from Page2 -> Page 3. User initiates only on Page1, all other function should performed in background. Is that possible?
This is the code used.
Page1.php:
<html>
<head><title>Page1</title></head>
<script src="/path to/jquery.min.js"></script>
<body>
<button type="button" class="btn" id="bt">SEND</button>
<script>
var a1="Hello";
var b1="Testing Ajax";
$(function(){
$('#bt').click(function(){
$.ajax({
url: 'Page2.php',
type: 'POST',
data: {'w1': a1,'w2':b1},
alert("Data Sent...");
},
error: function() {
alert("Unable to send data now.");
}
});}); });
</script>
</body>
</html>
Page2.php:
<html>
<head><title>Page 2 </title></head>
<body>
<?
$r1 = $_POST['w1'];
$r2 = $_POST['w2'];
?>
<div id="dom1" style="display: none;">
<?php
$r1 = $_POST['w1'];
echo htmlspecialchars($r1);
?>
</div>
<div id="dom2" style="display: none;">
<?php
$r2= $_POST['w2'];
echo htmlspecialchars($r2);
?>
</div>
<script>
var div1 = document.getElementById("dom1");
var m1 = div1.textContent;
//alert(m1);
var div2 = document.getElementById("dom2");
var m2 = div2.textContent;
//alert(m2);
$.ajax({
url: 'Page3.php',
type: 'POST',
data: {'x1': m1,'x2':m2},
alert("Data Sent...");
},
error: function() {
alert("Unable to send data now.");
}
});
</script>
</body>
</html>
Page3.php:
<html>
<head>
<title>Page3</title></head>
<body>
<div id="dom3">
<?php
$r1 = $_POST['x1'];
echo htmlspecialchars($r1);
?>
</div>
<div id="dom2">
<?php
$r2 = $_POST['x2'];
echo htmlspecialchars($r2);
?>
</div>
</body>
</html>
There are several ways you can solve your problem.
PHP Sessions
You can easily start a session in every of your pages and post
<?php
// every page needs to start the session
session_start();
// after submission or posting
$_SESSION['data'] = $your_data;
?>
So on your next page you can easily access your data via session.
<div>
<?= $_SESSION['data']['var1'] ?>
</div>
Use Forms and send them via jQuery ajax requests and put the form values on the next page into hidden input elements.
<!-- example for page 2 -->
<form id="your_form" method="post" action="">
<input type="hidden" name="var1" value="<?= $var1 ?>">
<input type="hidden" name="var2" value="<?= $var2 ?>">
<input type="submit" id="submit" name="submit" value="submit">
</form>
<script type="text/javascript">
$('#submit').on('click', function( event ) {
event.preventDefault();
$.ajax({
url : your_url,
type : 'POST',
data : $('#your_form').serialize();
});
});
</script>
Just don 't use ajax. You really don 't need it, wenn you jump from page to page. Look the example below.
<!-- on page1.php just a quick form -->
<form id="form1" method="post" action="page2.php">
<label for="var1">Var 1</label>
<input type="text" name="var1" id="var1" value="">
<input type="submit" name="submit" value="submit">
</form>
<!-- on page2.php just another quick form with hidden elements -->
<form id="form2" method="post" action="page3.php">
<label for="var2">Var 2</label>
<input type="text" name="var2" id="var2" value="">
<input type="hidden" name="var1" value="<?= $_POST['var1'] ?>">
<input type="submit" name="submit" value="submit">
</form>
In every 3 given examples you should consider the securty stuff like escaping post vars, etc.
I have 3 separate forms each with their own submit buttons (removed all other lines of form code as not required):
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicSub" id="postingTopicSub" enctype="multipart/form-data">
<input type="button" name="submittopic" id="submittopic" value="Submit" onclick="topicPostSubmit();"/>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicReply" id="postingTopicReply" enctype="multipart/form-data">
<input type="button" name="submitreply" id="submitreply" value="Submit" onclick="replyPostSubmit();"/>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicEdit" id="postingTopicEdit" enctype="multipart/form-data">
<input type="button" name="submitedit" id="submitedit" value="Submit" onclick="editPostSubmit();"/>
I am using Javascript to verify the form data is filled in before submitting however because using JavaScript the POST data from the button is not being sent.
JavaScript submit for each form:
document.getElementById("postingTopicSub").submit();
document.getElementById("postingTopicReply").submit();
document.getElementById("postingTopicEdit").submit();
On my data page I use isset to make the SQL queries run are for the correct form:
// User meets all conditions and posts a topic
if (isset($_POST['topicID'], $_POST['subject'], $_POST['post_text'], $_SESSION['username'], $_POST['submittopic']) && !isset($_POST['forumID'])) {
// User meets all conditions and posts a reply
if (isset($_POST['topicID'], $_POST['post_text'], $_SESSION['username'], $_POST['submitreply'], $_POST['forumID'], $_POST['subject'])) {
// User meets all conditions and edits a post
if (isset($_POST['topicID'], $_POST['post_text'], $_SESSION['username'], $_POST['submitedit'], $_POST['forumID'], $_POST['postID'], $_POST['subject'])) {
My questions:
Is there a way to keep my method of keeping the 3 SQL queries separate
to the specific forms
Is there a way to sent the POST of the submit even though it is being
submitted through JavaScript?
Is there another way that I just haven't seen.
Thanks in advance.
EDIT:
Full form (without bbcodes)
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicSub" id="postingTopicSub" enctype="multipart/form-data">
<input type="hidden" name="topicID" id="topicID" value="<?php echo $topicID ?>"/>
<div class="post-subject">
Subject:
<input type="text" name="subject" id="subject" />
</div>
<div class="post-textarea">
<textarea name="post_text" id="post_text" cols="100" rows="30"></textarea>
</div>
<div class="post-button">
<input type="button" name="submittopic" id="submittopic" value="Submit" onclick="topicPostSubmit();"/>
</div>
</form>
Full JS for form validation:
function forumssubmit()
{
var subject = document.getElementById("subject").value;
var text = document.getElementById("post_text").value;
if(subject=="" || text=="")
{
alert('Please fill in the subject and text');
return false;
}
return true;
}
function topicPostSubmit()
{
if(forumssubmit())
{
document.getElementById("postingTopicSub").submit();
}
}
EDIT2::
New js:
function forumssubmit()
{
var subject = document.getElementById("subject").value;
var text = document.getElementById("post_text").value;
if(subject=="" || text=="")
{
alert('Please fill in the subject and text');
return false;
}
return true;
}
function topicPostSubmit()
{
if(forumssubmit())
{
//document.getElementById("postingTopicSub").submit();
return true;
}
}
New button:
<input type="button" name="submittopic" id="submittopic" value="Submit" onclick="return topicPostSubmit();"/>
If you're really just "using Javascript to verify the form data is filled" you can add a return to the onclick's of your submit buttons. You'll then be able to use those for submitting the form instead of Javascript.
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicSub" id="postingTopicSub" enctype="multipart/form-data">
<input type="submit" name="submittopic" id="submittopic" value="Submit" onclick="return topicPostSubmit()"/>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicReply" id="postingTopicReply" enctype="multipart/form-data">
<input type="submit" name="submitreply" id="submitreply" value="Submit" onclick="return replyPostSubmit()"/>
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicEdit" id="postingTopicEdit" enctype="multipart/form-data">
<input type="submit" name="submitedit" id="submitedit" value="Submit" onclick="return editPostSubmit()"/>
Then in the javascript if you have a bad state return false.
function editPostSubmit(){
if(data == 'bad')
return false;
return true;
}
I also want to make sure you're doing data validation on the backend. We don't want to allow SQL injection on your page.
Edit:
Updated your modified code.
<form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" method="post" name="postingTopicSub" id="postingTopicSub" enctype="multipart/form-data">
<input type="hidden" name="topicID" id="topicID" value="<?php echo $topicID ?>"/>
<div class="post-subject">
Subject:
<input type="text" name="subject" id="subject" />
</div>
<div class="post-textarea">
<textarea name="post_text" id="post_text" cols="100" rows="30"></textarea>
</div>
<div class="post-button">
<input type="submit" name="submittopic" id="submittopic" value="Submit" onclick="return forumssubmit();"/>
</div>
</form>
I applied the multilingual and i also need to apply in javascript code which part of alerting message.
This is the common.php code.
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
header('Cache-control: private'); // IE 6 FIX
$CUR_LANG = 'en';
if(isset($_COOKIE['lang'])){
$CUR_LANG = $_COOKIE['lang'];
setcookie('lang', $CUR_LANG, time() + (3600 * 24 * 30));
}
switch ($CUR_LANG) {
case 'ko':
$lang_file = 'ko.php';
break;
default:
$lang_file = 'en.php';
break;
}
include_once("multilingual/".$lang_file);
?>
and this is the signin.html page
<?php include_once('top.php'); ?>
<div class="" style="background:#F7F7F7;">
<div id="wrapper">
<div id="login" class="animate form">
<section class="login_content">
<form id="signin" name="signin" class="signinForm" onsubmit="return false;" method="post" action="signin.html";>
<input type="hidden" name="act" value="signin">
<h1>Login Form</h1>
<div>
<input type="email" class="form-control" id="userEmail" name="userEmail" placeholder="<?= $lang['SIGNIN_ENTER_EMAIL'] ?>" required="" />
</div>
<div>
<input type="password" class="form-control" id="userPassword" name="userPassword" placeholder="<?= $lang['SIGNIN_ENTER_PASSWD'] ?>" required="" />
</div>
<div>
<a class="btn btn-default" id="signin_btn" href="signin.html"><?= $lang['SIGNIN'] ?></a>
</div>
<div class="clearfix"></div>
<div class="separator">
<a class="reset_pass" href="user-password-reset.html"><?= $lang['SIGNIN_RESET_PASSWD'] ?></a>
<p class="change_link"><?= $lang['SIGNIN_CREATE'] ?>
<?= $lang['SIGNIN_ACCOUNT'] ?>
</p>
<div class="clearfix"></div>
<br />
<!--<div>
<h1><i class="fa fa-gamepad" style="font-size: 26px;"></i> GAMEPARTY </h1>
</div>-->
</div>
</form>
<!-- form -->
</section>
<!-- content -->
</div>
</div><!-- #wrapper -->
</div>
<script type="text/javascript">
function checkFormValid() {
var isFormValid = true;
$(".signinForm input").each(function(){
if ($.trim($(this).val()).length == 0){
console.log("(no value)input id : " + this.id);
isFormValid = false;
}
});
if(isFormValid) {
checkEmail();
}else {
alert("<?= $lang['SIGNUP_ALERT_0'] ?>"); //here is the msg!
}
}
This page includes the top.php and top.php also includes the common.php.
The attached bottom of javascript code is needed to validate and alert the message.
The message show well depends on applied multilingual. However, the custom js files also have these kind of multilingual messages to alert but they just shows php code.
function email_form_validation(element) {
var email = element.val();
console.log("email_from_validation : " + email);
var regex = /[0-9a-zA-Z][_0-9a-zA-Z-]*#[_0-9a-zA-Z-]+(\.[_0-9a-zA-Z-]+){1,2}$/;
if(regex.test(email)){
return true;
}else {
alert("<?= $lang['E_FROM_VAL'] ?>");//This msg isn't applied the mulitilingual.
element.focus();
return false;
}
}
The above is the sample of common.js file and this common.js file is included in top.php file because this is the group of validation that must be needed from all files. How can i figure out this? The msg in common.js appears just like this -> "<?= $lang['E_FROM_VAL'] ?>"
How can i bring the php file and show it? Please let me know.
I figured out how to do. I simply renamed the common.js to val.php and also modified the top.php like below.
<script type="text/javascript" src="../val.php"></script>
I also added the <?php include_once('./common/common.php'); ?> to the val.php
That's all. It works great.