POST doesn't work fine - php

Well I have a problem with my code:
if ($_POST) {
//send confirmation email (or insert into database, etc...)
if(isset($_POST['del'])) {
$Link = $_POST['del_link'];
$query = "UPDATE comentarios SET del = '1' WHERE id = '".$Link."'";
mysql_query($query) or die ('Error: ' . mysql_error());
//header('Location: http://google.es'); //For debug
}
}
echo '<form name="del" method="post">
<input type="hidden" name="del_link" value="'.$rowComen['id'].'" />
Delete
</form>';
But when I press the link the web refreshes and that's all...
I had tried with: header('Location: http://google.es'); But I don't redirect to google...
And I don't know if the problem is in the post or in the query...

if(isset($_POST['del'])) {
You dont seem to have del form field. so the code inside this if statement is never executed. i think you are trying to check for del_link. so make it as if(isset($_POST['del_link'])) {

Have you checked in your browser if it contains the right value? The form as it is will contain the exact value '.$rowComen['id'].', unless a part of the PHP code is missing and the form is actually inside a string..
[edit]
I see. The form's name is 'del', but that name is never sent. Make the name of your submit button 'del', or add another hidden element. Easier still: Just check for the existence of del_link instead of del:
if(isset($_POST['del_link'])) {
$Link = $_POST['del_link'];

Related

Prevent Double Form Submit using Tokens

I am trying to prevent the user from double submitting the forum by adding token hidden field.
So here is what I have done so far (before the forum loads I have this code to create a token with the current time as a value.
$token = time();
setcookie('formToken', $token, time() + 3600);
in my forum I have a hidden input like this
<form method="post" action="'.$PHP_SELF.'?action=update">
<input type="hidden" name="token" value="'.$token.'" />
<input type="submit" value="go" />
</form>
now on the top of my page where $action == "update" I have this code
if(isset($_POST) && ($_POST['token'] != $_COOKIE['formToken'])){
$error_list .= '<li>You can not submit this forum twise.</li>';
}
if i hit F5 to refresh the page it submit the form again without displaying my error.
I suggest you to use use the PRG pattern (Post/Redirect/Get), which is also implemented by forums like phpbb.
Post/Redirect/Get (PRG) is a web development design pattern that
prevents some duplicate form submissions, creating a more intuitive
interface for user agents (users). PRG implements bookmarks and the
refresh button in a predictable way that does not create duplicate
form submissions.
gd1 answer will not prevent double click submission or accidental double submit by various jQuery bindings on a complex javascript form code.
Double click may be even faster then disabling submit button, or hiding it with javascript, so this would not be a full answer either.
The session token will not work either because session is not yet written and thus available or updated for the second process which may be just milliseconds away sharing the same session ID. The session is stored only upon completion of the fist process.
Cookie technique could be an answer as far as both processes are able to communicate over cookie in a blocking way, which may result to the same problems as the session sharing above.
The best solution would be to use server's shared memory access to check if the other process had already processed the data (order, payment, etc..) with the pregenerated data hash, or use database table blocking select and insert to check if the pregenerated hash has been already submitted.
Why not just set a session when the form is successfully submitted?
so $_SESSION['submitted'] = 1;
Then you can check for it.
Or Do
if(isset($_POST['submit']) && ($_POST['token'] != $_COOKIE['formToken'])){
$error_list .= '<li>You can not submit this forum twice.</li>';
}
Suggestion 1)
on Successful Submission Delete the cookies (removeTokens)
function removeToken()
{
//set formToken cookie val to "" (or any default xxxx) and the past expiry date for it
setcookie("formToken", "", time()-3600);
//try to unset - this is not needed ,we may try it
unset($_COOKIE['formToken']);
}
ie simply on your page if(isset($_POST)) removeToken();
Suggestion 2)
Perform a redirect as suggested by Tom Wright here Avoiding form resubmit in php when pressing f5
header('Location: formsubmitSucess.php');
I use this way of preventing double form submissions, it has worked on all occasions so far. Let me know if you need additional questions as this tutorial assumes you have intermediate knowledge on database and PHP.
STEP 1 : add a field on your database like this:
replace YOUR-TABLE with the name of your database table.
ALTER TABLE `YOUR-TABLE` ADD `token` VARCHAR(35) NULL DEFAULT NULL AFTER `creationtoken`, ADD UNIQUE (`token`) ;
STEP 2 on your form page you add this to the very first line:
it will create a unique toke that will be inserted into your database table along with you query, so that it can be checked for later to make sure no other like it is submitted into your database, meaning no double form submissions.
<?php
session_start();
date_default_timezone_set('America/Chicago');
$_SESSION['token'] = md5(session_id() . time());
?>
then just before your submit button add this:
// add this before the submit button
// this will post the unique token to the processing page.
<div style="width:100%; color:#C00; font-weight:normal;">Session Token: <?php echo strtolower($_SESSION['token']) ?></div>
<input type="hidden" name="token" id="token" value="<?php echo $_SESSION['token']?>" />
// add this before the submit button
<input type="submit" id="submit" name="submit" class="button" value="Submit" />
STEP 3: now on your process.php page
//this is where all of your form processing takes place.
// this is where you call the database
// if you need the database file let me know...
include("../common/databaseclass.php");
$db= new database();
//here the token is posted then the database table is checked and
//if the form has already been added it will return a 1 and will
//cause the query to die and echo the error message.
$token = $_POST['token'];
$query = "SELECT token FROM YOURTABLE WHERE token = '$token' LIMIT 1";
$result = $db->query($query);
$num = mysql_num_rows($result);
if ($num>0) {die('your form has already been submitted, thank you');}
else {
$host = "localhost";
$user = "user";
$pass = "password";
$db_name = "database";
mysql_connect($host,$user,$pass);
#mysql_select_db($db_name) or die( "Unable to select database");
// table query
$sql1="INSERT INTO YOURTABLE (
`token`,
`user`,
`email`,
`password`,
`newaccount`,
`zipcode`,
`city`,
`state`,
`country`,
`telephone`,
`creationip`,
`createdaccount`
)
VALUES (
'$token',
'$username',
'$email',
'$password',
'$newaccount',
'$zipcode',
'$city',
'$state',
'$country',
'$phone',
'$ipadress',
'$createdaccount'
)";
$db->query($sql1);
header("location:" http://home.php ");
}
For the same issue I made a code to use it for my own stuff. It has the PRG pattern and flexible to use it on same page or with extern PHP file for redirection - Easy to use and safe, maybe this might help you.
class unPOSTer {
private
$post = "KEEP_POST";
public function __construct(string $name = null) {
if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if (!$_SESSION) {
session_start();
}
}
$this->post = $name;
}
public function unPost() {
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
} elseif (strcasecmp($_SERVER["REQUEST_METHOD"],"POST") === 0) {
$_SESSION[$this->post] = $_POST;
header("Location: " . $_SERVER["PHP_SELF"] . "?" . $_SERVER["QUERY_STRING"]);
exit;
} elseif (isset($_SESSION[$this->post])) {
$_POST = $_SESSION[$this->post];
}
}
public function retrieve($data) {
if (isset($_SESSION[$this->post])) {
$posts = #$_SESSION[$this->post][$data];
if (isset($posts)) {
return $posts;
} else {
return null;
}
}
}
public function reset() {
if (isset($_SESSION[$this->post])) {
unset($_SESSION[$this->post]);
}
}
}
Then use it like this:
<?php
require_once "unPOSTer.class.php";
$unpost = new unPOSTer();
$unpost->unPost();
?>
<form action='' method=POST>
<input type=text name=fname value="<?php echo $unpost->retrieve("fname"); ?>" placeholder="First Name">
<input type=text name=lname value="<?php echo $unpost->retrieve("lname"); ?>" placeholder="Last Name">
<input type=submit name=send value=Send>
</form>
<?php echo $unpost->reset(); ?>
Not much to configure, do it on every page you send form data if you like. The retrieve() method spits out the data you have sent, in case if you might go back and fix something. Feel free to fork/pull it at my GitHub page I added 2 demos there.
I had the same problem, here is a simple fix:
if(!empty($_SESSION['form_token']) && time() - $_SESSION['form_token'] < 3){
$data['message'] = 'try again later';
return;
}
$_SESSION['form_token'] = time();
In my case the PRG pattern didn't have any effect since form submitted multiple times at the same time and the code had not been executed and there is no data saved to compare it against.

converting an script from PHP mysql_insert_id header, location method to PHP session method

I have successfully implemented data transfer attempt from one page to another using PHP mysql_insert_id header, location method. What I did was:
I have validated it (transferring (i.e. form action) the form to the same page), I have saved it in database, and now I m trying to display the data on another page.
page1 (where original form is located)
$id = mysql_insert_id();
header('Location: page2.php?id='.$id);
and in page2
$id = $_GET['id'];
$query = "SELECT * FROM form1 WHERE id=$id";
{
// there after display of data
}
The problem I faced:
I m getting this link in the title bar
http://localhost/aaa/page2.php?id=76
now if I try to change id= 56 or 45 or any other it is changing displayed data to that id.. so any user can change it in address bar and hence will be able to see my db values..
I thought of encoding it in first place, then at second place I thought of changing it to sessions instead.
so I searched a lot on google to set it as session and I tried this
<?php
// Starting the session
session_start();
if(isset($_SESSION['id'])) //and is this use of id correct?
{ // then what?
}
thanks guys for your help
You have to explain what you are exactly trying to do ? so that we can give suggestion . Though below code will work fine. But i think no use of it.Use session_start before using the session.
Page 1:
$id = mysql_insert_id();
$_SESSION['last_id'] = $id;
header('Location: page2.php');
Page 2:
$id = $_SESSION['last_id'];
$query = "SELECT * FROM form1 WHERE id=$id";
{
// there after display of data
}
page1.php:
<form action="post" action="page2.php">
<input name="name" type="hidden" value="<?=mysql_insert_id();?>"></input>
</form>
page2.php:
<?php
$id = $_POST['name'];
$query = "SELECT * FROM form1 WHERE id=$id";
?>

PHP email glitch

This is a school assignment. I don't know all of the fine details of PHP variables and such, but! If I hardcode the id then it sends just like it should. If not, it doesn't at all. Suggestions?
if ((!empty($_subject)) && (!empty($_text))) {
$_dbc = mysqli_connect('localhost', 'user', 'password', 'db') or die ('Error Connecting to MySQL server.');
$_id = $_GET['id'];
$_query = "SELECT * FROM midterm WHERE id = '$_id'";
$_result = mysqli_query($_dbc, $_query) or die ('Error Querying Database.');
while($_row = mysqli_fetch_array($_result)) {
$_to = $_row['email'];
$_firstName = $_row['firstName'];
$_msg = "Dear $_firstName, /n $_text";
mail($_to, $_subject, $_msg, 'From:' . $_from);
echo 'Mail sent to: ' . $_firstName . ' at ' . $_to . '<br />';
}
Addressing $_GET/$_POST problems with a NULL $_GET['id']
<form name="example" action="http://example.com" method="POST"></form>
OR
<form name="example" action="http://example.com" method="GET"></form>
If variables are POSTed from a form, they will be sent through the server and you can access them on the submitted page with $_POST['key']. If variables are sent with GET, they will be appended to the URL in a query string and accessible on the page with $_GET['key'].
When you use the variable $_GET['id'] it is looking in the URL's query string for the key id. If your URL looked like http://example.com/sript.php?id=123 then $_GET['id'] would return 123 not NULL. This can either be accomplished by visiting a specific URL (like shown above) or arriving on the page through a form like below:
<form name="example" action="http://example.com/script.php" method="GET">
<input type="text" name="id" />
<input type="submit" value="Try Me" />
</form>
This form, when submitted, will send the $_GET['id'] variable to script.php using GET.
Addressing other issues with mail not sending
Can you add the following lines of code before your while loop and let me know what they say? This will let me know if your MySQL query is working.
echo "Rows returned: ".mysqli_num_rows($_result)."<br />";
// this line only works on PHP > 5.3.0
echo "Result dump:<br /><pre>".mysqli_fetch_all($_result)."</pre>";
Since mysqli_num_rows() returned 0, that means that your SQL query SELECT * FROM midterm WHERE id = '7' is not returning any results. I can't help any more without looking at the database structure. Double check your code (and compare it to code that works) to try to see what is going wrong. Make sure that there is a row in the table midterm that has an id = 7.

Javascript/PHP interaction only appears on second click

Have searched for the answer but no joy, so here goes...
I'm working on a mobile hybrid app. I want the user to fill in their id number, which is then submitted to a javascript function for basic validation, then kicks in a jQuery.getJSON request to my serverside PHP which returns the data and then my jQuery will repopulate the form div with the data.
Currently it doesn't really work at all in Firefox, and only works correctly in Safari after I press the submit button for a second time. It returns the correct data, so the link is ok.
My problem is: Why does the div not get repopulated after the first click?
HTML:
<div id="login540div">
<form id="login540form" onSubmit="login540()">
Enter Student ID number<input type="text" name="login540id" id="login540id"/>
<input type="submit" value="Submit" />
</form>
</div>
Javascript:
function login540(){
// validates the data entered is an integer.
var loginNo = document.getElementById("login540id").value;
//if(!isNaN(loginNo))
if((parseFloat(loginNo) == parseInt(loginNo)) && !isNaN(loginNo))
{
//jSonCaller(loginNo);
$.getJSON('http://localhost:8888/c05673160/login540.php?q='+loginNo, function(data){
//alert(data);
$('#login540div').html("<p>First Name ="+
data.firstName+
"</p> Last Name ="+data.lastName+" </p>Module No.1 ="+
data.moduleNo1+"</p> Module No.2 ="+
data.moduleNo2+"<p> Course ID="+
data.courseID+"</p>");
})
}
else
{
// alert(loginNo); CHECKED
alert("Please make sure to insert only a whole number");
}
Then the PHP goes like this...
<?php
include ("config.php");
/*
require_once('FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);
$var = array('i'=>10, 'j'=>20);
$firephp->log($var, 'Iterators');
*/
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'collegeData';
$q=$_GET["q"];
$table = "studentTable";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table} WHERE studentID = '".$q."'");
if (!$result)
die("Query to show fields from table failed!" . mysql_error());
$json = array();
while($row = mysql_fetch_array ($result))
{
$json = array(
'firstName' => $row['firstName'],
'lastName' => $row['lastName'],
'moduleNo1' => $row['moduleNo1'],
'moduleNo2' => $row['moduleNo2'],
'courseID' => $row['courseID']
);
}
$jsonstring = json_encode($json);
echo $jsonstring;
mysql_close($conn);
?>
I can't figure out what's wrong, and I've been messing around with various things for the last few days trying to fix it, but no joy, so I'd really appreciate any help you can give.
#Robbie had a good point that you don't appear to be stopping the default behavior of the form submission. To do this you need to change a couple things:
onSubmit="login540()" needs to change to onSubmit="return login540()" otherwise whatever you return from the login540() function will be ignored.
At the end of the login540() function you need to return false; to stop the form from submitting normally. You can also pass in the event object as the first argument and use event.preventDefault() instead: function login540(event){event.preventDefault();...}.
To do yourself a favor however, you can use jQuery to bind the submit event handler to the form rather than using inline JS (tisk, tisk, :) )
$('#login540form').on('submit', login540);
This way you can keep all of your JS in one place rather than spread-out all over your HTML.
The bottom of Function login540() is missing, but this needs to kill the default "submit" action: this can be done with "return false;" at the end. As I can't see the end, not sure if this happens or not, but the form probably "submits" while the AJAX is running.
This is compounded as the form doesn't have an action, which probably explains the different browser behaviour. I suggest setting action to "#" and then, if you see "#" added in the URL then the form has submitted and not been stopped by your function.

Creating an isset if function using php to avoid and update if the input is empty for a MYSQL update

Hi I am newish to php and I have created an update page for Content Management System. I have a file upload in this case a picture. I have other inputs that contain text and I can get them to populate my form and thats fine and works great because the user can see what has already been entered. But the file name for the photo can not have a value so if the user doesn't pick the picture from the directory again it will update minus the picture. What I think I need is a isset function that says if the file (picture) input is left blank don't update this field and use whatever what already in the database for it, that way if it was left blank when created it will still be, and if the user has changed it this time it will change; or if they want to leave it the same it won't leave their picture blank. Hope that makes sence.
Here is my coding currently for the Form:
<p>
Photo:
</p>
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input type="file" name="photo"/>
Below is my php code for my update if the update button is pressed:
$con = mysql_connect("localhost","******","********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*******", $con);
// run this only, once the user has hit the "Update" button
if (isset($_POST['update'])) {
// assign form inputs
$name = $_POST['nameMember'];
$position = $_POST['bandMember'];
$pic = $_POST['photo'];
$about = $_POST['aboutMember'];
$bands = $_POST['otherBands'];
// add member to database
$result = mysql_query("UPDATE dbProfile SET nameMember='".$name."',bandMember='".$position."',photo='".$pic."',aboutMember='".$about."',otherBands='".$bands."' WHERE id='".$id."'");
mysql_close($con);
Header("Location: listMember.php");
exit;
}
else { // read member data from database
$result = mysql_query ("SELECT * FROM dbProfile WHERE id='".$id."'");
while($row = mysql_fetch_array($result))
{
$name = $row['nameMember'];
$position = $row['bandMember'];
$pic = $row['photo'];
$about = $row['aboutMember'];
$bands = $row['otherBands'];
}
}
mysql_close($con);
?>
If you could help I would be very please and greatful.
You have to use the $_FILES variable for uploaded files. For further information, see Handling file uploads in the PHP manual.
Try:
if(is_uploaded_file($_FILES['photo']['tmp_name']))
From the manual:
Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

Categories