php $_POST var clearing itself when i check it - php

i have a crazy problem that i just can't figure out. my form has two fields and a submit button. when i submit the vars get passed into $_POST just fine...
print('<div class=error>');
print_r($_POST);
print('</div>');
that gives me the two fields with the expected values along with the value of the submit button.
HOWEVER! when i add the following line of code so i can process based on the submit button, it clears all of the data. the post array shows up empty.
if ($_POST['submit'] == 'Submit') {
that clears the data. if i change the value from 'Submit' to anything else, the vars still show up in $_POST, they just get cleared when i try to check them.
any ideas what i'm doing wrong here?
here's the form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<?
if (isset($msg)) {
echo "$msg";
}
?>
<input type=text name='email'><br>
<br><input type=password name='password'>
<br>
<input type="submit" name="submit" value=Submit>
</form>
and here's the processing code:
if ($_POST['submit'] == 'Submit') {
echo "<div class=error>made it here</div>";
$u = $_POST['email'];
$p = $_POST['password'];
$auth = mysql_query("Select * from member where email='$u' and password='$p'");
$auth = mysql_fetch_array($auth);
if ($auth) {
$pid = $auth[id];
echo "aa";
sess_register("sess_msg");
$sess_msg = null;
global $auth, $pid;
}
}
if i change the value when i check to see if the submit button has a value to something other than the actual value of the submit button, which is 'Submit' - it clears all variables sent to $_POST

If you want to check which submit button was clicked, you just have to look for its name as a key in the array $_POST.
So you should do:
if (array_key_exists('submit', $_POST)) {
// your code
}
Little advice: you'd better escape your $_POST data before putting it into a query!
Check this out: http://php.net/manual/en/function.mysql-real-escape-string.php

From your post, it doesn't look your code should be emptying the $_POST array. The only thing that I can think of at the moment is that maybe in the code you actually only put one '=' sign.
var_dump( $_POST );
if ( isset( $_POST['submit'] ) ) {
var_dump( $_POST );
echo "<div class=error>made it here</div>";
$u = $_POST['email'];
$p = $_POST['password'];
$auth = mysql_query("Select * from member where email='$u' and password='$p'");
$auth = mysql_fetch_array($auth);
if ($auth) {
$pid = $auth[id];
echo "aa";
sess_register("sess_msg");
$sess_msg = null;
global $auth, $pid;
}
}
var_dump( $_POST );

Related

PHP submitting a form is destroying my sessions

Hello I am trying to make a form in the page where I created a session so when I submit the form the sessions gets destroyed here is my code:
<form method="post">
<h5>Name</h5>
<input type=text name="name" class="insertname">
<br>
<br>
<input type="submit" name="namesearch" class="insertbutton"></input>
</form>';
PHP code to start the session :
<?php
if(isset($_POST['s']))
{
$a=$_POST['uid']; //accessing value from the text field
$enteredpass = $_POST['pwd']; //accessing value from the text field
$client = new MongoDB\Client('xxxx');
$companydb = $client->test;
$jsons = $companydb->jsons;
$ownerid = $jsons->findOne(
['ID' => $a]
);
$idcoded = $ownerid->ID;
if (empty($idcoded)) {
echo "<h1>empty</h1>";
}
if (!empty($idcoded)) {
$passcoded = $ownerid->pass;
if ($passcoded == $enteredpass) {
session_start();
}
}
}
?>
Make sure you have session_start(); at the top of all the PHP scripts
So, put the session_start(); at the top of the script and set say $_SESSION["uid"] when the user has correctly entered the credentials
A normal practice is to set $_SESSION["uid"]=""; (set initial value) before the user logs in the system, and then use this session variable to determine whether the user has successfully logged in.
So
<?php
session_start();
if(isset($_POST['s']))
{
$a=$_POST['uid']; //accessing value from the text field
$enteredpass = $_POST['pwd']; //accessing value from the text field
$client = new MongoDB\Client('xxxx');
$companydb = $client->test;
$jsons = $companydb->jsons;
$ownerid = $jsons->findOne(
['ID' => $a]
);
$idcoded = $ownerid->ID;
if (empty($idcoded)) {
echo "<h1>empty</h1>";
}
if (!empty($idcoded)) {
$passcoded = $ownerid->pass;
if ($passcoded == $enteredpass) {
$_SESSION["uid"]=$_POST['uid'];
} else {
$_SESSION["uid"]="";
}
}
}
?>

Check if Variable is empty. if so, set value. else, perform function

Can this be done?
I created a form which performs the function giveReaction. Can anybody tell me what I'm doing wrong?
This is my code so far:
function giveReaction (){
global $firstname;
if ( empty($firstname) ) {
$firstname = 'fill in your name, and get a response.';
echo "$firstname";
}
else {
$firstname = $_GET['firstname'];
echo "hello, $firstname";
}
}
echo "<form action=\"index.php?func_name=giveReaction()\" method=\"GET\">
<input type=\"text\" name=\"firstname\">
<input type=\"submit\" value=\"send\">
</form>";
giveReaction();
There are a two immediate problems with your code:
You never define $firstname prior to checking it's empty
The action in your form does nothing, as you never handle func_name - this is not a built in feature of the language
To start fixing your code, you need to correctly handle the firstname input when the form has been submitted, for example:
$firstname = isset($_GET['firstname']) ? $_GET['firstname'] : '';
This ensures that $firstname will be the submitted value, or an empty string if it hasn't been provided yet.
So then you can define your function as follows:
function giveReaction (){
$firstname = isset($_GET['firstname']) ? $_GET['firstname'] : '';
if ( empty($firstname) ) {
echo 'fill in your name, and get a response.';
} else {
echo "hello, $firstname";
}
}
Secondly adjust your form to remove the unnecessary action, as by default forms will submit to the current page, and the func_name parameter isn't used.
echo "<form method=\"GET\">
<input type=\"text\" name=\"firstname\">
<input type=\"submit\" value=\"send\">
</form>";
Then you can finish as you have, by calling your function.
giveReaction();
Your function can simply be:
function giveReaction() {
$firstname = $_GET['firstname'];
echo $firstname ? "hello, $firstname" : 'fill in your name, and get a response.';
}
There's no need to add it to the form.

$_POST setted after I unset it

Here, I have made validation for checkbox.
First when I select on submit button, it shows validation error.
After that when I click on "selectall" button, it goes in update query that is on submit button.
That mean, $_POST is setted.
I have unset that submit button for that, although it is going in update query through "selectall" button.
Why this is happening?
if(!empty($_SESSION['id']) && isset($_POST['processorder']))
{
echo "hello";exit;
$chk = $_SESSION['id'];
$query="update order_details set process_order='1' where id IN(".implode(',',$chk).")";
//mysql_query($query) or die(mysql_error());
unset($_SESSION['id']);
unset($_SESSION['on']);
$_SESSION['flash']['success'] = 'Order processed successfully.';
header('Location: '.$_SERVER['REQUEST_URI']);
die();
}
if(empty($_SESSION['id']) && $_POST['processorder'])
{
print_r($_POST);
$error = "Please select an Order(s)..!!";
unset($_POST['processorder']);
echo "<br>";
print_r($_POST);
}
<input type="button" name="selectpage" value="Select All Page" onclick="selectall()"/>
<input type="submit" id="processorder" name="processorder" value="Process Order" class="submit-green"/>
<input type="checkbox" name="id[]">
If you would like to unset all $_POST values you shouldn't just unset $_POST['processorder'].
if (isset($_SESSION['id']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
// to unset processorder
unset($_POST['processorder']);
var_dump($_POST);
// To unset all $_POST values
unset($_POST);
var_dump($_POST); // Will return bool(false)
}
Since you've unset($_SESSION['id']);, if(empty($_SESSION['id'])) will return TRUE.
This happens because if(empty(unset($var))) will always return TRUE.

I can't get my update query to work (php / mysqli)

I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>

Why does this SQL execute but not update anything?

For some reason or another, this sql is executing and outputting:
successfully added the following paypal button to this product... But it's not updating. I'd appreciate any help on this.
if(isset($_REQUEST['submitedform'])) {
if ($_POST['paypal']) {
$paypal=$_POST['paypal'];
$id = $_GET['id'];
$query = "UPDATE `video_info` SET paypal_button_html='".$paypal
."' WHERE id='".mysql_real_escape_string($id) ."'";
mysql_query($query) or die(mysql_error());
echo "successfully added the following paypal button to this product:
<br /><br />
{$paypal}";
}
}
?>
<?
if ($_GET['id']) {
?>
<h1>Add PayPal Button In for this product:</h1>
<form action="add_paypal.php" method="POST">
*Paypal button html: <br><textarea rows="2" cols="20" name="paypal"></textarea><br>
<input type="hidden" name="submitedform" value="true" />
<input type="submit" value="Add paypal button in for this product">
</form>
<?
} else {
echo "You can not come to this page manually.";
}
?>
A few problems:
You were not being consistent in sanitising your Database Input
You did not have clear validation rules
Your form was not setting the $_GET['id'] field (so the database submission was always failing)
Amended code:
<?php
// Init an Array to hold any error messages
$errors = array();
if( isset( $_REQUEST['submitedform'] ) ){
// Validate the required fields
if( !isset( $_POST['paypal'] ) || $_POST['paypal']=='' )
$errors['paypal'] = 'No value for "paypal"';
if( !isset( $_GET['id'] ) || !is_numeric( $_GET['id'] ) )
$errors['id'] = 'No value for "id"';
// If Validation was successful
if( !$errors ){
// Prepare the Variables for Database Usage
$paypal = mysql_real_escape_string( $_POST['paypal'] );
$id = (int) $_GET['id'];
// Template and Complete the SQL Query
$sqlTpl = 'UPDATE `video_info` SET paypal_button_html="%s" WHERE `id` = %s';
$sqlStr = sprintf( $sqlTpl , $paypal , $id );
// Submit the Query
if( !mysql_query( $sqlStr ) ){
// Something went wrong
$errors[] = 'An error occured when submitting the data to the database';
}else{
// Submitted OK
echo 'Successfully added the following paypal button to this product:'.$paypal;
}
}
}
// Check for any errors
if( $errors ){
// Show errors to user
echo 'The following errors occurred:';
echo '<ul><li>'.implode( '</li><li>' , $errors ).'</li></ul>';
}
?>
<?
if( isset( $_GET['id'] ) && is_int( $_GET['id'] ) ){
?>
<h1>Add PayPal Button In for this product:</h1>
<form action="add_paypal.php?id=<?php echo $_GET['id']; ?>" method="POST">
*Paypal button html: <br><textarea rows="2" cols="20" name="paypal"></textarea><br>
<input type="hidden" name="submitedform" value="true" />
<input type="submit" value="Add paypal button in for this product">
</form>
<?
} else {
echo "You can not come to this page manually.";
}
?>
This code...
Includes the id in the form's action URL
Checks for the submission
Validates the submitted values
Creates the Database Query
Submits the Query
Checks the Query worked OK
AMENDED: Replaced is_int() with is_numeric() as, after RTFMing, I found that a string, comprised of only digits, will apparently return false if tested with is_int().
UPDATE
Please, use $_REQUEST OR $_GET OR $_POST but not all 3 of them.
Also, why don't you mysql_real_escape_string the variable $_POST['paypal'] ?
You mix $_GET and $_POST variables. You should use either GET or POST, but not both. If this is a post request, change $_GET['id'] to $_POST['id'].
In this case, the update doesn't fail because of where id = ''. This doesn't update anything, because there's no id with an empty string. But it also doesn't fail, since it is a valid update statement.

Categories