Protecting POST request between PHP and AJAX - No user input [duplicate] - php

This question already has answers here:
Use an array in a mysqli prepared statement: `WHERE .. IN(..)` query [duplicate]
(8 answers)
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 11 months ago.
I have a simple component on a website that is performing a query of all the prod ids from a cluster of products on the page and storing them into an array in jquery. I then send that array to PHP via AJAX as a POST which will ultimately perform a db query on all the ids.
My question is, how can I protect the array coming from the AJAX/JS file into the PHP file in the POST, against user manipulation... meaning I can find the ids in the source code and change them to some random value or even something malicious.
Normally in a user input scenario, you could do a real escape string or similar functionality in the PHP to cover the incoming data. Since I'm sending over an array of numeric values, what would be the best to way to secure that POST request?
Thank you,
-S

Let's assume, that you want to receive array of integer values from a client.
If you write on a raw PHP, then your code can look like this:
if (isset($_POST['ids']) && is_array($_POST['ids'])) {
$ids = array_map('intval', $_POST['ids']);
$ids = array_unique($ids); // Optional.
print(implode(', ', $ids)); // Print values.
}
Sample of user input:
ids[]=1&ids[]=2&ids[]=3&ids[]=malicious_input&ids[]=1
Output:
1, 2, 3, 0
intval takes argument and returns it's integer representation. malicious_input becomes 0 and it's safe for using it in SQL queries.
Some related links:
PHP Prepared Statements.
I have an array of integers, how do I use each one in a mysql query (in php)?

Related

input multiple check box data to database [duplicate]

This question already has answers here:
What's the best way to store Checkbox Values in MySQL Database?
(3 answers)
Closed 2 years ago.
I created a form with multiple checkboxes to add to database, what do I need to change in the VALUE $_POST[penerima] to enter multiple checkboxes data into the database?
if(isset($_POST['simpan'])){
$simpan = mysqli_query($koneksi, "INSERT INTO umum (tanggal_terima, pengirim, no_surat, perihal, disposisi, penerima )
VALUES ('$_POST[tgl_terima]',
'$_POST[pengirim]',
'$_POST[no_surat]',
'$_POST[perihal]',
'$_POST[disposisi]',
'$_POST[penerima]')
");
I'm not going to address the SQL injection issues in the code, but please read:
How can I prevent SQL injection in PHP?
You can store array data in a database using json_encode($array) - this will convert your array of checkboxes to a string which can be stored. I suggest using the TEXT column type, otherwise, the sting may be cut off if your values are long.
https://www.php.net/manual/en/function.json-encode.php
You can then json_decode the data back to an array once it's selected.
https://www.php.net/manual/en/function.json-decode.php

Is there a way to use PDO with a dynamic column name in an UPDATE query? [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
It's a little relative to the question I asked here
(PDO adds the apostrophe to the mySQL query) but this time column name is a parameter.
Not working PDO example would be like this:
"UPDATE tbl SET :COL1 = NOT :COL1;"
sure solution like this:
"UPDATE tbl SET $COL1 = NOT $COL1;" // works (but it's not PDO)
but why
"UPDATE tbl SET $COL1 = NOT :COL1;" // does not ??
while
"UPDATE tbl SET $COL1 = :VAL_COL1;" // is ok if I first get and negate COL1 value...
In a prepared statement, a parameter is a constant value that will be passed into the query without affecting how the query will be run. This allows the database to "prepare" the query ahead of time and figure out how it will be executed even without knowing the exact values that will be used.
Using this definition, a query like this does not have any parameters, and so the PDO and non-PDO versions of the query will look the same. Your working (first) example is as good as you're going to get. In fact, I'd claim that your first example actually is the PDO version.
To use a non-database example, a prepared statement is very much like a function in a programming language such as PHP. A function accepts parameters and uses their values, but (in normal circumstances) the parameters are not lines of code that will be run. The same code is run regardless of what the parameter values are - the function code itself is not changed by the parameters.
No. You cannot bind table names or column names as parameters. You can only bind values as parameters.
See more here: Can PHP PDO Statements accept the table or column name as parameter?

"SELECT :parameter FROM .." in PDO [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
I'm trying to select a variable column name in my table, but this doesn't seem to work:
$reponse = $bdd->prepare('SELECT :day AS day FROM TABLE WHERE id= :id');
$reponse->execute(array('day' => 'monday', 'id' => '5'));
$day = $reponse->fetch();
Even by setting 'day', to a sure known element in my table (monday), it doesn't work. Same for id.
Does someone know how to fix that?
I have no php error output, only a mysql query error (that doesn't show).
By replacing ':day' by monday, I have an output.
Due to the order in which the SQL is parsed, there's simply no way to use a bound parameter as part of the SQL statement (for example, a column or table name).
Instead, you'll need to build the string with string concatenation. If the value of :day comes from an external source (database, POST parameter, etc), to avoid possible SQL injection attacks you'll want to validate the input to make sure it's a valid column or expression.
Table and Column names cannot be replaced by parameters in PDO. You will need to filter and sanitize the data manually.

pagination in search page with search text starting with single quote in php [duplicate]

This question already has answers here:
How get post value in pagination
(2 answers)
Closed 8 years ago.
I am working on pagination on search result.I referred below link and I am not able to pass value when search text starts with single quote..
How get post value in pagination.
Can you please help me..
thanks
This is because the single quote is embedded into the literal string $sql. It halts the query, and this is dangerous because a hacker can do what is called SQL Injection -> https://www.acunetix.com/websitesecurity/sql-injection/ .
Anyway, the mysql extension has been deprecated, meaning it is no longer supported and maintained. You have two easy options: mysqli or PDO. I personally recommend using PDO -> http://cz1.php.net/PDO . It will be easy to convert your code.
With PDO you can bind your input to certain fields:
$sql="Select count(*) from FIMTRN_Memorial where FirstName like :search";
$sql = $database->prepare($sql);
$sql->execute(array(":search" => "%".$_SESSION['searchchar']."%"));
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
I hope I could help!
UPDATE:
With the above parameterized query, your search string cannot contain a percentage sign, as this will act as a wild-card character.
UPDATE 2:
I don't know if you noticed that $_GET{'page'} is meant to be $_GET['page'] in the previous answer.

Can PHP bind a list of numbers in a SQL prepared statement?

I am converting a Coldfusion website to PHP. I have a query that looks in a list of comma separated numbers to see if there is a match and then responds accordingly. This is the where statement I am currently using.
WHERE (`link_issue_category`.`Category_ID` IN (<CFQUERYPARAM value="#Category_id#" list = "yes">)
How do I write this in PHP?
CFQUERYPARAM does some validation on the value, and if possible sets up a bind parameter. You can probably just embed the value into the SQL, assuming you've already done validation / sanitization on it. The list parameter specifies that this is a comma-delimited list. You should be able to plug this list directly into the query, depending on the value type.
"WHERE (`link_issue_category`.`Category_ID` IN ($category_id)";
If your values in the list are strings, you may need to wrap them in qoutes before they go into the query.
FYI CF just creates a new prepared statement with the number of ? being the same as the length of your list behind the scene.
So if you want the same behaviour in PHP, it wouldn't be that hard really. Just dynamically create a new prepared statement, and bind them accordingly.
PHP Prepared statements: http://php.net/manual/en/pdo.prepared-statements.php
However, you could have just use regex to validate the list of values to numeric value and comma's only, and use the variable as part of the SQL statement.

Categories