-1

My php query code

<?php 
  if (isset($_POST['btn_add'])) 
      {
          $query_insert = "INSERT INTO Calc_Tbl(id_Customer,Flname_Customer, )
          VALUES (N'$_POST[id_Hidden]', N'$_POST[flname_Hidden]' )";
          mysqli_query($db, $query_insert);
      }
?>

And my html form code to send data to above query

<form method="post" action="" >
    <input type="hidden" name="id_Hidden">
    <input type="hidden" name="flname_Hidden">
    <button type="submit" class="btn btn-danger" name="btn_add"></button>
</form>

Now you know the hidden fields can edit in Inspect Source in Web browsers by every body, How Can I send data in form to query in same page without any input fields as hiddens? How can use variables instead of input hidden fields?

Thank you

Aria5h4h
  • 75
  • 2
  • 2
  • 12
  • `Inspect Source` is not the only way to manipulate data. A `curl` could be used as well. That SQL is open to injections. Parameterize. I'm also not sure what the leading `N`s are. – user3783243 Jun 10 '19 at 11:57
  • 3
    Your code is *wide open* to **SQL injection**. You should start reading here: https://www.php.net/manual/en/security.database.sql-injection.php and here: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – David Jun 10 '19 at 12:00
  • As for the question being asked, if you want to remove `` fields then go ahead and just remove them. But you'll either need to not rely on them in your SQL code or get those values from somewhere else. Where else would you like to track those values? Why shouldn't users be able to insert different values in the first place? If users aren't permitted to perform an action, check in your server-side code for that permission and don't perform that action. – David Jun 10 '19 at 12:01
  • at user3783243 and @David / , exactly i don't understand whats your mean? why my code open to SQL INJECTION?? please give me more information about.what do you mean? love you – Aria5h4h Jun 10 '19 at 19:44
  • @AriaShir: *"please give me more information"* - Please refer to the information that you've already been given. (Click on the links I provided in my first comment above.) – David Jun 10 '19 at 19:47
  • @David you want to say that SQL query can be edit by every body like can add drop table? yes? but how? the PHP codes never seen by users !!!!! – Aria5h4h Jun 10 '19 at 19:58
  • 1
    @AriaShir: SQL injection has nothing to do with a user being able to see your PHP code. SQL injection happens because you are executing user input as if it were code and simply trusting that the input is probably a valid value. It might not be a value, it might be SQL code. You are again encouraged to **follow the links which have been provided to you and to *read* about the subject**. They contain examples of what SQL injection is and how to prevent it. – David Jun 10 '19 at 20:02
  • Thanks dear David i reading your link and i got it what you say, you say I have to don't use like this code: (N'$_POST[id_Hidden]') ??! so how to set values ? please answer here i wanna know it what you do in your code and what should i do. – Aria5h4h Jun 10 '19 at 20:50

5 Answers5

2

You're looking at the problem from the wrong perspective. The problem is not that the user can submit incorrect values. The problem is that your server-side code assumes that the values are correct.

the hidden fields can edit in Inspect Source in Web browsers by every body

Yes, this is true. Users can also craft any request they want to your server entirely outside of a web browser. It's fundamentally true that any client can send any request to your server at any time.

Rather than try to fight this, simply account for it. Ask yourself...

Why shouldn't User X be allowed to submit Value Y in this field?

As an example, perhaps that value/record belongs to a different user and this user shouldn't be able to edit other users' records. Then that's exactly what you should be validating server-side.

Expressed as pseudo-code:

if (!CurrentUser->canEdit($_POST[id_Hidden])) {
    die "You are not allowed to edit this record.";
}
// continue editing the record here

So then what is CurrentUser? That depends on how you track who the current user is. (Not included in the question.) However you track your logged-in users, refer to that information. And what is canEdit()? That depends on how you determine whether any given user is permitted to edit any given record. You'll have to write that logic.

Please note that the above is pseudo-code and you won't be able to just copy/paste it as-is and expect it to work. But hopefully it's illustrating the overall point. To put it simply:

When a user attempts to perform an action, first determine if the user is allowed to perform that action. If they are not, return an error. If they are, perform the action.

That's really all there is to it. Never implicitly trust information from the client. Always validate that the user is authorized to do what they're trying to do.


Side note, following all of the other advice posted in this question/answers so far...

Sessions are not needed for this. And relying on them for this will be extremely limiting and overly complex as your application needs grow and as application complexity grows.

There's absolutely nothing wrong with the client providing "hidden" values that the server uses. Indeed, this allows your services to be much more RESTful and much simpler to use and maintain. All you need to do is validate those values server-side before using them.

David
  • 208,112
  • 36
  • 198
  • 279
  • suppose that a customer should buy something then in order page he/she should select the count of that products. so i Multiplication the selected number count to the price and store Sum of calculated to hidden field (now with sessions it`s safe) and then i store the Sum price of hidden field to data base. – Aria5h4h Jun 10 '19 at 19:54
  • @AriaShir: (1) You don't need to submit calculated values on the form. Just calculate them when you need them. When an order is submitted you are given the selected product and quantiy from the client, and you know the price on the server. Basic arithmetic on the server will provide you with the total price. You can store the total in the database with the order since prices can change, but it may make more sense to store the price at the time and still perform calculations when needed. (2) What does any of this have to do with the question being asked? – David Jun 10 '19 at 19:57
  • maybe he added one product to cart and other day can add again some others, so he open the Cart page and change the count of every products Separate of others and in my hidden filed the Sum will change every time by every count of product. :) and can Submit if he want – Aria5h4h Jun 10 '19 at 20:03
  • @AriaShir: At this point it sounds like you're trying to ask "How do I build a shopping cart?", which is far too broad for a Stack Overflow question (let alone just a comment). If you have a question to ask, you are encouraged to ask it. – David Jun 10 '19 at 20:07
  • it`s my project and i am exciting to doing that and improve it and learning step by step in this project... i just had a problem in this issue – Aria5h4h Jun 10 '19 at 20:42
1

Put your variable data into $_SESSION global variables.
For that first thing to do is to start your sessions like this

<?php
session_start();
//now you have created $id and $flname somewhere in your code
//which you want to submit
$_SESSION['id']=$id;
$_SESSION['flname']=$flname;
?>

Rest of your form HTML code will remain as it is

The PHP program where your form is posted to will begin with

<?php
session_start();
$id=$_SESSION['id'];
$flname=$_SESSION['flname'];

If any other field were submitted, they will be inside $_POST, naturally
Until $_SESSION is destroyed using session_destroy;, your variables will be found in any other program you use subsequently.

  • hi, thanks. I have some other sessions if I use session_destroy(); other sessions also will destroy. how to prevent it? – Aria5h4h Jun 10 '19 at 12:34
  • 1
    @AriaShir: That sounds like a different, unrelated problem. `session_destroy()` only destroys the current session, it has no effect on other users' sessions which may be open simultaneously. If you are observing otherwise then it sounds like there's a problem in how you're managing session data. – David Jun 10 '19 at 12:37
  • @david , I used session_destroy(); after finished the query , then page loaded and all sesions destroyed. :/ – Aria5h4h Jun 10 '19 at 12:40
  • @AriaShir: Then either you're describing it incorrectly or something else, outside of the code/functionality shown, is wrong. Either way, using sessions for this at all is essentially a bad idea and overcomplicates matters. It *can work*, so the answers recommending it are valid in their own right. But you're probably better off simply validating submitted data rather than trying to track all of that data server-side. State management is difficult, and in this case it's also unnecessary. – David Jun 10 '19 at 12:46
  • 1
    @AriaShir : If you want to destroy specific session variable, you can use like `unset($_SESSION['id']);` `unset($_SESSION'flname');` - this will unset only variables you want to remove from $_SESSION. session_destroy(); will remove everything from $_SESSION. – Rajesh Kakkad Jun 11 '19 at 06:07
0

you may use session for such fields..

No need to take hidden fields..

You can use session variables directly..

<?php 
          if (isset($_POST['btn_add'])) 
          {
              $query_insert = "INSERT INTO Calc_Tbl(id_Customer,Flname_Customer)
              VALUES ('".$_SESSION["id"]."','".$_SESSION["flname"]."')";
              mysqli_query($db, $query_insert);
          }
?>
Rakesh Hiray
  • 721
  • 3
  • 15
  • i used it befor but did not work. please wite me an example in same page by sessions. thansk very much. – Aria5h4h Jun 10 '19 at 12:00
  • form should be like this: ? or ... i confused with form filesd to send. – Aria5h4h Jun 10 '19 at 12:18
  • 1
    @AriaShir: Session values have nothing to do with the HTML form. *If you want to use Session in this case* (you shouldn't, but you seem to want to) then you would set your session values in the server-side code when the page loads. Then when the user submits the form you would read those session values for use in your query. (This will get complicated very quickly if you have a page with multiple records, such as a table of records with "delete" buttons. Or if users start navigating around the site in unexpected ways, which they often do.) – David Jun 10 '19 at 12:29
0

See

You can encrypt this data and validate it on the server side, as it is said in one of the answers of that question, goes

As it was said in this link in some of the answers, you can encrypt the hidden fields in some way.

-1
        With Ajax you can do like this :
var first = 'data1';
var second = 'data2';
    $("body").off("submit","#assignedUserForm").on("submit","#assignedUserForm",function(){
            $("#assignedUserForm [type='submit']").text('Loading...').prop('disabled', true);
            $('<input>').attr({
                type: 'hidden',
                name: 'id_Hidden',
                value: first 
            }).appendTo('#assignedUserForm');
            $('<input>').attr({
                type: 'hidden',
                name: 'flname_Hidden',
                value: second 
            }).appendTo('#assignedUserForm');
            var formData = new FormData(this);  
            $.ajax({
                url: 'url.php',
                type: 'POST',
                data: formData,
                contentType: false,
                cache: false,
                processData: false,
                success: function (response) {
                    $("#assignedUserForm [type='submit']").text('Submit').prop('disabled', false);

               }
            });
            return false;
        });
kishan
  • 16
  • 3
  • How does this address the concern of users being able to submit invalid data? – David Jun 10 '19 at 12:14
  • your have to define in jquery as a global variable i will edit it – kishan Jun 10 '19 at 12:21
  • Users can still submit whatever values they like to the API in this case. AJAX is not a magic wand, and jQuery is not a magic wand. In your code the server is still relying on values from the client, and is still assuming those values are correct. – David Jun 10 '19 at 12:26
  • than you should add the http headers from your end it should be come from the same domain else you can generate some token and then validate from your end – kishan Jun 10 '19 at 12:32