SELECT WHERE = sybol dont return data - php

a have an sqlite table
CREATE TABLE "lib" (
"id" INTEGER UNIQUE,
"addr" TEXT UNIQUE,
"data" TEXT,
PRIMARY KEY("id")
)
testing dataset contains:
...
1 arara arararar test
2 unit=comp comp test
...
I use code next to test requests
<? $db = new PDO('sqlite:main.db') or die('Unable to open database');
echo ("qry: ".$_SERVER["QUERY_STRING"]."<br>");
foreach ($db->query("SELECT * FROM lib WHERE addr='".$_SERVER["QUERY_STRING"]."'", PDO::FETCH_ASSOC/*_NUM*/) as $row) {
//echo($row[0].'<br>');
echo($row['addr'].'<br>');
echo($row['data'].'<br>');
}
$db = null; ?>
so, when I do script.php?arara it returns
qry: arara
arara
arararar test
but, when I do script.php?unit=comp it returns no data (just QUERY_STRING)
qry: unit=comp
what wrong with my code?
upd:
this question is not about security
php modified for PDO prepare, now its return no data with any request
<? $db = new PDO('sqlite:main.db') or die('Unable to open database');
echo ("qry: ".$_SERVER["QUERY_STRING"]."<br>");
$qry=$db->prepare("SELECT * FROM lib WHERE addr='?'");
$qry->execute(array($_SERVER["QUERY_STRING"]));
foreach ($qry as $row) {
//foreach ($db->query("SELECT * FROM lib WHERE addr='".$_SERVER["QUERY_STRING"]."'", PDO::FETCH_ASSOC/*_NUM*/) as $row) {
//echo($row[0].'<br>');
echo($row['addr'].'<br>');
echo($row['data'].'<br>');
}
$db = null; ?>

what wrong with my code?
... sadly quite a lot.
I've never seen someone inject the QUERY_STRING straight into a query. How easily corruptable would this string be? If I wanted to inject some malicious sql I just have to write it in. If I make a mistake then the query won't return anything. If I add a new parameter in the future because I want more than a single param then the query fails.
The malicious sql is the most dangerous problem here, the other's are about code maintainability and still very important. Check out this
https://bobby-tables.com/
and this
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
You need to parse the query string so you can check and sanitise the data. Php has an in-built function for this:
https://www.php.net/manual/en/function.parse-str.php
You then should be binding the data in the prepared statement you have now read about.
I don't know if you're in charge of the script calling this, but it seems like POST data would be better for this. GET parameters are visible and stored in web server logs, so you have a security vulnerability with potential personal data. You also then won't need to worry about url_encoding/decoding the string.
//EDIT
to be fair, using PHP's parse_str with decode the url anyway, so that at least will take care of that issue if you can't convert it to post

Related

Passing function result into sqli

I'm new to this and I know I'm probably doing this entire thing the wrong way, but I've been at it all day trying to figure it out. I'm realizing there's a big difference between programming a real project of my own rather than just practicing small syntax-code online. So, I lack the experience on how to merge/pass different variables/scopes together. Understanding how to fit everything within the bigger picture is a completely different story for me. Thanks in advance.
What I'm trying to do, is to make the function "selectyacht" output data in a different location from where it's being called (in viewship.php). The output data (in viewship.php) needs to be only certain fields (not everything) returned and those results will be scattered all over the html page (not in a table). In addition to that, I have this variable: "$sqlstatement" (in sqlconn.php) that I'm trying to bring outside the function because I don't want to repeat the connection function every time. I tried a global variable, as much as I shouldn't, and it thankfully it gave me an error, which means I have to find a better way.
Basically my struggle is in understanding how I should structure this entire thing based on two factors:
To allow the second conditional statement in sqlconn.php to be typed
as least often as possible for different "selectyacht" functions
that will come in the future.
To allow the connection instance in sqlconn.php to reside outside the function since it will be used many times for different functions.
Returning data in a different place from where it's being called in viewship.php because the call will be a button press, not the results to be shown.
This is probably very simple, but yet it eludes me.
P.S. Some of this code is a copy/paste from other resources on the internet that I'm trying to merge with my own needs.
sqlconn.php
<?php
$servername = "XXXXXXXX";
$username = "XXXXXXXX";
$password = "XXXXXXXX";
$dbname = "XXXXXXXX";
// Instantiate the connection object
$dbconn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection works or show an error
if ($dbconn->connect_error) {
die("Connection failed: " . $dbconn->connect_error);
}
// Create a query based on the ship's name
function selectyacht($shipname) {
global $sqlstatement;
$sqlstatement = "SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
}
// Put the sql statement inside the connection.
// Additional sql statements will be added in the future somehow from other functions
$query = $dbconn->query($sqlstatement);
// Return the data from the ship to be repeated as less as possible for each future function
if ($query->field_count > 0) {
while($data = $query->fetch_assoc()) {
return $data;
}
}
else {
echo "No data found";
}
// Close the connection
$dbconn->close();
?>
viewship.php
<html>
<body>
<?php include 'sqlconn.php';?>
<!-- ship being selected from different buttons -->
<?php selectyacht("Pelorus");?>
<br>
<!-- This is the output result -->
<?php echo $data["Designer"];?>
<?php echo $data["Length"];?>
<?php echo $data["Beam"];?>
<?php echo $data["Height"];?>
</body>
</html>
Mate, I am not sure if I can cover whole PHP coding standards in one answer but I will try to at least direct you.
First of all you need to learn about classes and object oriented programming. The subject itself could be a book but what you should research is autoloading which basically allows you to put your functions code in different files and let server to include these files when you call function used in one of these files. This way you will be able to split code responsible for database connection and for performing data operations (fetching/updating/deleting).
Second, drop mysqli and move to PDO (or even better to DBAL when you discover what Composer is). I know that Internet is full of examples based on mysqli but this method is just on it's way out and it is not coming back.
Next, use prepared statements - it's a security thing (read about SQL injection). Never, ever put external variables into query like this:
"SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
Anyone with mean intentions is able to put there string which will modify your query to do whatever he wants eg. erase your database completely. Using prepared statements in PDO your query would look like this:
$stmt = $this->pdo->prepare("SELECT * FROM ships WHERE Name = :ship_name");
$stmt->bindValue(':ship_name', $shipname);
Now to your structure - you should have DB class responsible only for database connection and Ships class where you would have your functions responsible eg. for fetching data. Than you would pass (inject) database connection as an argument to class containing you selectYacht function.
Look here for details how implementation looks like: Singleton alternative for PHP PDO
For
'Returning data in a different place from where it's being called'
If I understand you correctly you would like to have some field to input ship name and button to show its details after clicking into it. You have 2 options here:
standard form - you just create standard html form and submit it with button click redirecting it to itself (or other page). In file where you would like to show results you just use function selectYacht getting ship name from POST and passing it to function selectYacht and then just printing it's results (field by field in places you need them)
AJAX form - if you prefer doing it without reloading original page - sending field value representing ship name via AJAX to other page where you use selectYacht function and update page with Java Script

How to dump MySQL table to a file then read it and use it in place of the DB itself?

because a provider I use, has a quite unreliable MySQL servers, which are down at leas 1 time pr week :-/ impacting one of the sites I made, I want to prevent its outeges in the following way:
dump the MySQL table to a file In case the connection with the SQL
server is failed,
then read the file instead of the Server, till the Server is back.
This will avoid outages from the user experience point of view.
In fact things are not so easy like it seems and I ask for your help please.
What I did is to save the data to a JSON file format.
But this got issues because many data on the DB are "in clear" included escaped complex URLs, with long argument's line, that give some issue during the decode process from JSON.
On CSV and TSV is also not workign correctly.
CSV is delimited by Commas or Semilcolon , and those are present in the original content taken from the DB.
TSV format leave double quotes that are not deletable, without avoid to go to eliminate them into the record's fields
Then I tried to serialize each record read from the DB, store it and retrive it serializing it.
But the result is a bit catastrophic, becase all the records are stored in the file.
When I retrieve them, only one is returned. then there is something that blocks the functioning of the program (here below the code please)
require_once('variables.php');
require_once("database.php");
$file = "database.dmp";
$myfile = fopen($file, "w") or die("Unable to open file!");
$sql = mysql_query("SELECT * FROM song ORDER BY ID ASC");
// output data of each row
while ($row = mysql_fetch_assoc($sql)) {
// store the record into the file
fwrite($myfile, serialize($row));
}
fclose($myfile);
mysql_close();
// Retrieving section
$myfile = fopen($file, "r") or die("Unable to open file!");
// Till the file is not ended, continue to check it
while ( !feof($myfile) ) {
$record = fgets($myfile); // get the record
$row = unserialize($record); // unserialize it
print_r($row); // show if the variable has something on it
}
fclose($myfile);
I tried also to uuencode and also with base64_encode but they were worse choices.
Is there any way to achieve my goal?
Thank you very much in advance for your help
If you have your data layer well decoupled you can consider using SQLite as a fallback storage.
It's just a matter of adding one abstraction more, with the same code accessing the storage and changing the storage target in case of unavailability of the primary one.
-----EDIT-----
You could also try to think about some caching (json/html file?!) strategy returning stale data in case of mysql outage.
-----EDIT 2-----
If it's not too much effort, please consider playing with PDO, I'm quite sure you'll never look back and believe me this will help you structuring your db calls with little pain when switching between storages.
Please take the following only as an example, there are much better
way to design this architectural part of code.
Just a small and basic code to demonstrate you what I mean:
class StoragePersister
{
private $driver = 'mysql';
public function setDriver($driver)
{
$this->driver = $driver;
}
public function persist($data)
{
switch ($this->driver)
{
case 'mysql':
$this->persistToMysql($data);
case 'sqlite':
$this->persistToSqlite($data);
}
}
public function persistToMysql($data)
{
//query to mysql
}
public function persistSqlite($data)
{
//query to Sqlite
}
}
$storage = new StoragePersister;
$storage->setDriver('sqlite'); //eventually to switch to sqlite
$storage->persist($somedata); // this will use the strategy to call the function based on the storage driver you've selected.
-----EDIT 3-----
please give a look at the "strategy" design pattern section, I guess it can help to better understand what I mean.
After SELECT... you need to create a correct structure for inserting data, then you can serialize or what you want.
For example:
You have a row, you could do that - $sqls[] = "INSERT INTOsong(field1,field2,.. fieldN) VALUES(field1_value, field2_value, ... fieldN_value);";
Than you could serialize this $sqls, write into file, and when you need it, you could read, unserialize and make query.
Have you thought about caching your queries into a cache like APC ? Also, you may want to use mysqli or pdo instead of mysql (Mysql is deprecated in the latest versions of PHP).
To answer your question, this is one way of doing it.
var_export will export the variable as valid PHP code
require will put the content of the array into the $data variable (because of the return statement)
Here is the code :
$sql = mysql_query("SELECT * FROM song ORDER BY ID ASC");
$content = array();
// output data of each row
while ($row = mysql_fetch_assoc($sql)) {
// store the record into the file
$content[$row['ID']] = $row;
}
mysql_close();
$data = '<?php return ' . var_export($content, true) . ';';
file_put_contents($file, $data);
// Retrieving section
$rows = require $file;

preventing xss in jquery, php, mysql in some examples - please advice

For a while I am more and more confused because of possible XSS attack vulnerabilities on my new page. I've been reading a lot, here on SO and other googled sites. I'd like to secure my page as best as it is possible (yes, i know i cant be secure 100%:).
I also know how xss works, but would like to ask you for pointing out some vulnerable places in my code that might be there.
I use jquery, javascript, mysql, php and html all together. Please let me know how secure it is, when i use such coding. Here's idea.
html:
<input name="test" id="id1" value="abc">
<div id="button"></div>
<div id="dest"></div>
jQuery:
1. $('#id').click (function() {
2. var test='def'
3. var test2=$('#id1').val();
4. $.variable = 1;
5. $.ajax({
6. type: "POST",
7. url: "get_data.php",
8. data: { 'function': 'first', 'name': $('#id').val() },
9. success: function(html){
10. $('#dest').html(html);
11. $('#id1').val = test2;
12. }
13. })
14. })
I guess it's quite easy. I have two divs - one is button, second one is destination for text outputted by "get_data.php". So after clicking my button value of input with id 'id1' goes to get_data.php as POST data and depending on value of this value mysql returns some data. This data is sent as html to 'destination' div.
get_data.php should look like this:
[connecting to database]
switch($_POST['function']) {
case 'first':
3. $sql_query = "SELECT data from table_data WHERE name = '$_POST[name]'";
break;
default:
$sql_query = "SELECT data from table_data WHERE name = 'zzz'";
}
$sql_query = mysql_query($sql_query) or die(mysql_error());
$row = mysql_fetch_array($sql_query);
echo $row['data']
For now consider that data from mysql is free from any injections (i mean mysql_real_escaped).
Ok, here are the questions:
JQuery part:
Line 2: Can anybody change the value set like this ie. injection?
Line 3 and 11: It's clear that putting same value to as was typed before submiting is extremely XSS threat. How to make it secure without losing functionality (no html tags are intended to be copied to input)
Line 4: Can anybody change this value by injection (or any other way?)
Line 8: Can anybody change value of 'function' variable sent via POST? If so, how to prevent it?
Line 10: if POST data is escaped before putting it into database can return value (i mean echoed result of sql query) in some way changed between generating it via php script and using it in jquery?
PHP part:
Please look at third line. Is writing: '$_POST[name]' secure? I met advice to make something like this:
$sql_query = "SELECT data from table_data WHERE name = " . $_POST['name'];
instead of:
$sql_query = "SELECT data from table_data WHERE name = '$_POST[name]'";
Does it differ in some way, especially in case of security?
Next question to the same line: if i want to mysql_real_escape() $_POST['name'] what would be the best solution (consider large array of POST data, not only one element like in this example):
- to mysql_real_escape() each POST data in each query like this:
$sql_query = "SELECT data from table_data WHERE name = " . mysql_real_escape($_POST['name']);
to escape whole query before executing it
$sql_query = "SELECT data from table_data WHERE name = " . $_POST['name'];
$sql_query = mysql_real_escape($sql_query);
to write function that iterates all POST data and escapes it:
function my_function() {
foreach ( $_POST as $i => $post ) {
$_POST[$i] = mysql_real_escape($post)
}
}
What - in your opinion is best and most secure idea?
This post became quite large but xss really takes my sleep away :) Hope to get help here dudes once again :) Everything i wrote here was written, not copied so it might have some small errors, lost commas and so on so dont worry about this.
EDIT
All right so.. if I understand correctly filtering data is not necessery at level of javascript or at client side at all. Everything should be done via php.
So i have some data that goes to ajax and further to php and as a result i get some another kind of data which is outputted to the screen. I am filtering data in php, but not all data goes to mysql - part od this may be in some way changed and echoed to the screen and returned as 'html' return value of successfully called ajax. I also have to mention that I do not feel comfortable in OOP and prefering structural way. I could use PDO but still (correct me if i am wrong) i have to add filtering manually to each POST data. Ofcourse i get some speed advantages. But escaping data using mysql_real_escape looks to me for now "manual in the same level". Correct me if i am wrong. Maybe mysql_realescape is not as secure as PDO is - if so that's the reason to use it.
Also i have to mention that data that doesnt go to database has to be stripped for all malicious texts. Please advice what kind of function I should use because i find a lot of posts about this. they say "use htmlentities()" or "use htmlspecialchars()" and so on.
Consider that situation:
Ajax is called with POST attribute and calls file.php. It sends to file.php POST data i.e. $_POST['data'] = 'malicious alert()'. First thing in file.php I should do is to strip all threat parts from $_POST['data']. What do you suggest and how do you suggest I should do it. Please write an example.
XSS is Cross-site scripting. You talk about SQL injection. I will refer to the latter.
JQuery Part
It's possible to change every single JavaScript command. You can try it yourself, just install Firebug, change the source code or inject some new JavaScript code into the loaded page and do the POST request. Or, use tools like RestClient to directly send any POST request you like.
Key insight: You cannot control the client-side. You have to expect the worst and do all the validation and security stuff server-side.
PHP Part
It is always a good idea to double-check each user input. Two steps are usually mandatory:
Validate user input: This is basically checking if user input is syntactically correct (for example a regex that checks if a user submitted text is a valid email address)
Escape database queries: Always escape dynamic data when feeding it to a database query. Regardless where it's coming from. But do not escape the whole query string, that could yield in unexpected results.
Maybe (and hopefully) you will like the idea of using an ORM solution. For PHP there are Propel and Doctrine for instance. Amongst a lot of other handy things, they provide solid solutions to prevent SQL injection.
Example in Propel:
$result = TableDataQuery::create()
->addSelectColumn(TableDataPeer::DATA)
->findByName($_POST['name']);
Example in Doctrine:
$qb = $em->createQueryBuilder();
$qb->add('select', 'data')
->add('from', 'TableData')
->add('where', 'name = :name')
->setParameter('name', $_POST['name']);
$result = $qb->getResult();
As you can see, there is no need for escaping the user input manually, the ORM does that for you (this is refered as parameterized queries).
Update
You asked if PDO is also an ORM. I'd say PDO is a database abstraction layer, whereas an ORM provides more functionality. But PDO is good start anyway.
can firebug any malicious code in opened in browser page and send
trash to php script that is somwhere on the server?
Yes, absolutely!
The only reason you do validation of user input in JavaScript is a more responsive user interface and better look & feel of your web applications. You do not do it for security reasons, that's the server's job.
There is a firefox addon to test your site for XSS, it called XSS Me
Also you can go to
http://ha.ckers.org/xss.html
for most XSS attacks
and go to
http://ha.ckers.org/sqlinjection/
for most sql injection attacks
and try these on your site

Creating link to database

I am currently making a project on Universal Identification Number(not such a big one, but like that kind of....upto college level)..I want to create a page with tabs to the respective databases.... like If I press key 'A' for a tab then all the names starting with letter 'A' should appear...
Plz help me !!!!
Regards !!
Not entirely understanding your question, but if I was to create a tab for different names, and/or situations, I'd use a switch statement with cases that allows you to change the order_by in your sql query.
I think this is kinda what you want to display all names starting with an A passed on with a get request:
<?php
//connect to mysql database (if you don't know search google)
if(isset($_GET['namestartingwith'])){
$namebegin = $_GET['namestartingwith'];
$query = mysql_query("SELECT * FROM database WHERE name LIKE \"$namebegin%\"");
while(mysql_fetch_array($query) = $data){
echo $data['name'];//name being the name op your column with the name data
}
}
?>
This should do the trick for php+mysql
In Java+MySQL, after downloading and instating the requisite jars:
public static Connection dbConnect() throws SQLException, ClassNotFoundException {
String DB_URL;
Class.forName("com.mysql.jdbc.Driver");
DB_URL = "jdbc:mysql://your_db_url?autoReconnect=true";
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);
return conn;
}
In the calling program,
public static Object dbExecute() throws SQLException, ClassNotFoundException {
Statement stmt;
Connection conn = dbConnect();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("your_sql_statement");
Object result = null;
while (rs.next()) {
result = rs.getObject("field_you_want_to_retrieve");
}
rs.close();
stmt.close();
conn.close();
return result;
}
I think you need to take this from the start. Are you using PHP or Java? Are you using MySQL or Oracle for your database? Maybe set yourself a simpler goal, build a PHP page (or Java servlet) that fetches data from your database and displays it in a table in the web browser. When you get this working, you can build on it.
When you get to a question that you can't answer, then submit that question to Stackoverflow. Explain what you have working, what you are trying to do and where the expected result deviates from the actual result.

Is it safe to run this query on the page people will be on?

Sorry, this is probably a really stupid question, but is it safe to run this code on the page the people will be viewing, or should I wrap this into a function instead and call it?
$stmt = $db->prep_stmt("select * from .... where userid = ? and username = ?");
/* Binding 2 parameters. */
$stmt->bind_param("is", $userid, $username);
/* Binding 2 result. */
$stmt->bind_result($isbn, $title, $author, $coef, $bookid);
/* Executing the statement */
$stmt->execute( ) or die ("Could not execute statement");
/*
* Making PHP buffer the whole result,
* not recommended if there is a blob or
* text field as PHP eats loads of memory
*/
$stmt->store_result();
while ($stmt->fetch()) {
/*
* Here you can use the variables $isbn, $title, $author, $coef, $bookid,
* which contatin the data for 1 row.
*/
print "<tr>".
"<td>".$isbn."</td>".
"<td>".$title."</td>".
"<td>".$author."</td>".
"</tr><tr><td>";
}
They will be the same from a security point of view. It's a question of software design. However, you may want to consider better error handling (at least for production). Specifically, it's not really necessary to leak the cause of the error ("Could not execute statement"). Usually, you want a generic error page ("Sorry, the server's having problems! Try going to the home page.").
Correct me if im wrong, but you seem to be concerned that people can view your PHP code, but that you put it in a different file and did
$dataAccessor = new MyDataAccessorObject();
$dataAccessor->checkUser($userId, $userName);
they wouldnt't see anything meaningful, correct?
Whether or not that code is a function away doesn't matter. Even on PHPs that people 'view' they don't get to see the code, just the HTML that gets rendered. Between the php tags, the only stuff that effects what the user can see if they were to hit 'view source' is stuff that gets echoed or printed or whatever.
Try to view the PHP here, I dare you! http://lirr42.mta.info/schedules.php (this is just a random example, no special compared to anything else)
What you need to worry about it security wise is the input and SQL injection. It seems that your parameterization handles that. I would imagine either that user name or user id from a form, and you need to make sure that some jerk doesnt enter a username like blah' OR 1=1 and cheat. Your prepared statement and parameter binding should handle that. If you are unsure you can sanitize with mysql_real_escape

Categories