I'm new to this forum and have a dilemma with my MySQL/PHP site. Now I've created a function that will pass a SQL query to it and execute it. What I didn't account for was the fact my SQL query being passed to the function is showing up in the "view source" of all browsers; which is BIG security concern because hackers can see the query. Here is a snippet of the function:
// connect to MySQL
$connection = mysql_connect($host,$username,$password) or die("Couldn't connect to MySQL". mysql_error());
// selects the database
$db = #mysql_select_db($db_name,$connection) or die("Couldn't select database");
function statement ($query)
{
global $connection, $db;
$sql = $query;
$results = mysql_query($sql, $connection) or die(mysql_error());
return $results;
}
Here's how its called:
$cat_results = statement("select * from $category");
Is there a way to hide the query passed from the browser using the function I have? If not any recommendations on a better approach to this function?
Really appreciate any thoughts on this!!
Andre
First of all PHP isn't viewable by the client, it is always executed by the server. Second of all at no point can the client execute SQL on your server. This is the basis of SQL Injection. If you are building a query with JavaScript and then sending it a php script to be executed then you have a very serious vulnerability on your hands.
it is not recommended to pass the query string all the way to the browser/client. you should only pass the query outcome to the client.
Unless you disable PHP on your server, or something breaks, your users won't ever see your PHP code.
PHP code should never show up in the html source. When things are working properly it should all be processed by the server and only the results sent to the client. Maybe you've missed a <? or ?> tag somewhere that's preventing it from being seen as php?
Related
I was wondering if some one could direct me on the right path to take because every way I have tried has failed or really broken my code. To keep it simple I have page with a dynamically created select box populated with peoples names from a mySQL database its element id is 'insert'. This page also holds the php query
my query on the database works if I hard code a name in but I want to pass it as a variable from the select box. I can't seem to get it to post my variable and return me an id.
heres my query
<?php
function getElementById($id) {
$xpath = new DOMXPath(NEW domDocument);
return $xpath - > query("//*[#id='$id']") - > item(0);
}
$insertName = getElementById('insert');
printf($insertName);
$con = mysqli_connect("localhost", "root", "", "karaoke");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = "Select id FROM queue where singer = '$insertName'";
$result = mysqli_query($con, $sql) or die("Bad SQL: $sql");
while ($row = mysqli_fetch_assoc($result)) {
$insertAt = ("{$row['id']}");
printf($insertName);
printf($insertAt);
};
?>
whats the best way to get my variable sent to the script and then return me the answer.
thanks
You can use either the POST or GET form methods to send data from your HTML form to your PHP script. In the form element, you will want to set the action to your PHP script like so: <form action = 'your_php_file.php' method = 'GET or POST'>. This means that when the form is submitted, you can get the data from this PHP file. Then, in your PHP, you will want to use the global variable for either POST or GET (depending on which you have used for the form method) to get the value from the select box. Using this method means you can replace your GetById function and assign the value from the form to the $insertName variable using the superglobals.
Another problem in your code is that you use your PHP variables in your SQL query. This means that your code is open to an SQL injection which could lead to problems such as people getting all of the database info (which is bad for a database storing poorly encrypted/hashed passwords, or even storing them in plain text)or could even lead to your database being deleted. To avoid this, you should use prepared statements and parameters whereby the statement is sent first without the variable and the variable is bound after.
Also, take a look at the links above about POST and GET and also about the PHP global variables which will allow you to get the data from your HTML form. Also, here are some links which explain prepared statements and parameters so that you can write more secure PHP code:
Mysqli prepare statement used to prepare the statement. The use of question marks are as placeholders as you later bind your variables to the query.
Mysqli Bind Param used to add in the variable to the SQL statement after the statement has been prepared which prevents SQL injection.
That's all for now, but be sure to ask any questions you may have and I will try my best to answer them all.
EDIT
ADDED CODE - hopefully will demonstrate what you were after, there are some small changes that may need to be made. There may be some extra code needed to fit in with any other code you have, but this should demonstrate the principle of POST and prepared statements with parameters. Written in OOP as opposed to your procedural as I find it cleaner and easier (personal opinion). If there are any problems integrating this be sure to tell me about any errors or issues/further questions. I too am fairly new to PHP.
<?php
$insertName = $_POST['insert']; // Get the value of the select box which will need to have the attribute 'name = "insert"' by POST
printf($insertName);
$con = new mysqli("localhost", "root", "", "karaoke");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = "Select id FROM queue where singer = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $insertName); //Binds the string insertName to the question mark in the query
$stmt->execute();
while ($row = $stmt->fetch_assoc()) { // Left as was because syntax is different from PDO which I use. Therefore, I am assuming this part is correct.
$insertAt = ("{$row['id']}");
printf($insertName);
printf($insertAt);
};
?>
I am using an Nginx reverse proxy to tie back to a MySQL DB store. I need to write an authentication service for a reverse IMAP/SMTP proxy.
There are two examples on the Nginx wiki to tie back to most databases: an embedded Perl and a PHP script. I am not familiar with Perl and since my HTTP server uses PHP to tie back to MySQL using PDO statements, I am more comfortable with the PHP script, seen here:
Using a PHP Script on an Apache Server as the IMAP Auth Backend
My problem is that I don't know exactly what I need to input inside the functions since it just mentions to put your logic here. If you scroll a bit down, you will see two functions: authuser and getmailserver. Should these be PDO prepare statements to select the email with LIMIT 1?
Would appreciate any help with this.
Should these be PDO prepare statements
Generally speaking - yes
to select the email with LIMIT 1?
I doubt so. You don't need no email here. for the authuser you need only boolean
function authuser($user,$pass){
global $pdo;
$stmt = $pdo->prepare("SELECT pass FROM users WHERE login = ?");
$stmt->execute([$user]);
$dbpass = $stmt->fetchColumn();
return password_verify($pass, $dbpass); // should be hashed this way
}
getmailserver have to return server. if you have only one then
function getmailserver($user) {
return 'server';
}
I have been writing php and mySQL functions all day and as I was writing the simplest part of my project I have hit a wall.
The function should simply count how many entries are in the database and return that number (If there is a more simple way please let me know, this is my first php + mysql project)
Here is the code:
function quoteCount(){
global $db;
$totalQuoteNum = array();
$query = "SELECT * FROM Quotes";
$result_set = mysqli_query($db, $query)
or die ("Query $query failed ".mysqli_error($db)); //fails here
$totalQuoteNum = mysql_num_rows($result_set)
or die ('couldnt count rows'.mysqli_error($db));
echo 'COUNTED EVERYTHING!!!';
return $totalQuoteNum;
};
Now when the die statement prints I get the string but not the mysqli error.
Things I have tried and ruled out:
$db is correct
query works in mysql
I wasnt sure if the database was connected, so I added the connect inside this function and stil nothing.
Any ideas? From what I see it should work and its not giving me any error to work from. Please help!
Based on the comments, it seems as though $db is the database name.
Functions such as mysqli_query() expect a database link (resource), not simply the database name.
This resource is created by constructing a new mysqli object. Following your procedural style, use mysqli_connect().
I'm using HostMonster as my web host and I'm trying connect to a database I created using MySQL inside of HostMonster. In order to call that database in my website do I need to use PHP? Or is there a way to create a javascript OnClick function that can call the database. I'm not using ASP.Net so it's not quite as simple as I would like it. Just curious if the best solution is PHP, if so I guess I should go learn it.
what are you planning to do with the database, other than just 'calling it'? You will need some language like PHP to connect to the DB to retrieve, insert, update or delete data in the DB.
here is a code for connection MySQL from PHP using MYSQLI extension
<?php
$dba_host='localhost';
$dba_name='root';
$dba_pass='';
$dba_db='sn';
$con=mysqli_connect($dba_host,$dba_name,$dba_pass,$dba_db) or die('Connection Refused !');
$stmt=mysqli_prepare($con,"SELECT UID FROM Main");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $value);
while(mysqli_stmt_fetch($stmt))
$result[] = $value;
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
Your javascript onClick function is running on the client side (in the browser) and the database is running on the server-side. You will need a server-side language to get the information from the database and send it to the browser.
You do not HAVE to use PHP to connect to a MYSQL database. Also, you can't connect to your database using only client-side javascript (ie. an onClick() function). You need to use a server side language, PHP is one choice.
To connect to a MYSQL database on hostmonster using PHP you will need to know your credentials that use to log into phpMyAdmin from your cpanel. Once you have made the connection you can then select the MYSQL database that you created. Once the database is selected you can query it using the "mysql_query" function in PHP. The following code does all of that and stores the results of the MYSQL query in a PHP variable called $result.
<?php
$con = mysql_connect("www.yourdomain.com","phpMyAdmin_username","phpMyAdmin_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql_database_name", $con);
$query = "SELECT * FROM TableName"
$result = mysql_query($query);
?>
Now you've got the results of the query inside the PHP variable $result and you can use it anyway you like.
If you put this in your 'public_html' folder and named it 'index.php' or 'index.html' this would automatically be run when someone went to www.yourdomain.com.
You can find a great tutorial series on PHP here http://thenewboston.org/list.php?cat=11.
I currently have a javascript file 'score.js' which makes use of jQuery.js, which is being called correctly via a link. The code in score.js is:
function originalUpdateScore(answer,correct){
if (answer == correct)
{
$.post('updateScore.php');
}
window.location.reload(true);
}
This function calls 'updateScore.php':
<?php
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='$_SESSION[logname]')";
mysqli_query($con, $updateScore);
?>
However the database is not being updated correctly. If I replace the line:
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='$_SESSION[logname]')";
with:
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='123pf')";
Where 123pf is the value that the SESSION variable contains in the php file calling the javascript it updates correctly. Why does using the session variable not work? Am I calling it incorrectly in the query?
Thanks in advance.
Are you calling session_start anywhere inside updateScore.php?
If you haven't started the session I do not believe that session variables will be available.
also, do you have complete control over $_SESSION['logname']? If not, someone could easily change their logname to inject SQL and damage/compromise your database. For example, if they were able to set their logname to be this, you could lose your user table:
$_SESSION['logname']="'; DROP TABLE user;-- ";
You're opening yourself right up to cheaters by playing like this. Under this scenario, any user could visit updateScore.php at any time to increase their stats, since that script neither checks their answer nor checks for a token that the JS builds to say the score is ok. It is a bad idea to keep this kind of logic on the front-end (javascript) without also having it verified on the back end (PHP); javascript & AJAX are very helpful shortcuts that can improve user experience, but they cannot be trusted as sole validity checkers.
It's probably just a transcription error, but the code that you have shown in your question uses $_SESSION[logname], it should be $_SESSION['logname'].