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';
}
Related
We have a remote server containing a SQL MariaDB. I have to write a piece of code to be placed in that same server whose mission is to execute querys asking for data, modify that data and send it to an external api hosted in another server. When I was shown the DB, it was through ssh commands and entering sql mode inside the server rather than trough code like PHP as I have always done it before.
So, my code is to placed in the same server as the DB, brings the data, modifys some info and calls the api to upload it.
As I said, I am completely lost so my question is simple: can this be achieved? if so, how?
I've read about ssh_connect and exec, but since the code will be placed in the same server I don't think this is necessary, correct me if I am wrong. I can't place any code since I don't know how to start.
Thank you guys for all the help, I am closing the question now:
All I had to do was to use PDO as a secure way to establish a connection and to prepare and execute the querys. Remember I placed my php file in the same server that hosts the DB and note that I had to create a user and grant permissions to the DB you can find how in one of the comments above or here. Here is the code:
try {
$conn = new PDO('mysql:host=yourhostserver;dbname=dbname','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
//Example of query
$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids FROM cdr');
$stmt->execute();
foreach ($stmt as $row) {
$string = $row['ids'];
}
I've been checking on this error with no solutions specific to my code. I have connected to mysql server using the mysqli_connect() call. then passed the connection result to a $_SESSION to have it available over the whole website - as i normally do in all my other projects, But for some reason i keep getting the error:
"mysqli_query(): Couldn't fetch mysqli"
There is the code that generates the error:
if(!isset($_GET['sortBy']))
{
$listSQL = "SELECT * FROM '".$_SESSION['WorkTable']."'";
}
else
{
$listSQL = "SELECT * FROM '".$_SESSION['WorkTable']."' where ".$_GET['sortBy']."='".$_GET['sortBy']."'";
}
//get Contacts From DB
if(!empty(mysqli_query(#$_SESSION['IMWEDBcxn'],$listSQL)))
Here is the connection class code...
if(!empty($cxn))
{
$_SESSION['WorkTable'] = $dbTable;
$_SESSION['IMWEDBcxn'] = $cxn;
}
Anything I'm missing here?
As stated by Ivan Solntsev, do not store a connection handler in a user's session for 2 obvious reasons :
1- Handlers can not be serialized.
2- Anything you store in a user's session (using $_SESSION), would only be available under that user's scope. I suggest you read more about sessions and PHP, $_SESSION is not a way to store data over sessions.
So doing something like :
$connect = mysqli_connect("...");
$_SESSION["dbconnection"] = $connect;
mysqli_query($_SESSION["dbconnection"], $query);
IS WRONG!
If you want a persistent connection, to avoid reconnecting on each DB query, read about MySQLi and Persistent connections : http://php.net/manual/en/mysqli.persistconns.php . If you are running on a PHP version under 5.3, I'd recommend using PDO (which I'd recommend regardless of the PHP version you're using).
I am using WYSIWYG Webbuilder 8 to construct a website. Part of the website will be restricted access to registered users only. To this end I have created a MySQL database. I also have a sign-up form. When a new user wishes to sign-up I would like to have the username automatically checked against the database to make sure it doesn't already exist. I intend doing this using an AJAX function as the WYSIWYG software has this option built in. What I need to build myself and this is where I'm struggling is the validate.php that the AJAX command will go to.
I have something like this at present (please excuse my ignorance!):
<?php
$username = $_POST['data'];
// TODO: lookup username in database...
if ($username == 'user')
{
echo "true";
}
else
{
echo "false";
}
?>
I have no real idea if this is adequate or secure. I have been reading some scary stuff about sql injection and other black arts involving the use of forms and I'd like to avoid pitfalls if possible.
Would some kind soul please have a look at my request and help me out? I'm not a programmer by any stretch of the imagination and I'm way out of my depth here.
Thanks in advance for your help
You want to use something that will handle the chatter between your application and the database for you. One of the best tools available for this today is the PDO library, specifically PDO-MySQL for your usage. It will handle escaping and SQL injection issues for you by using parameterized (prepared) statements
Here's an example of connecting to a database and issuing a query in MySQL
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF-8', 'username', 'password');
$statement = $db->prepare('SELECT user_id FROM users WHERE username = :username LIMIT 1');
$statement->bindValue(':username', $_POST['data']);
$statement->execute();
if (false == $userId = $statement->fetchColumn()) {
// No matching username was found in the database
} else {
// A matching username was found in the database
// $userId contains the matching user ID
}
Knowing how to pass this back to your JS/AJAX integration could be dependent on what framework (if any) you are using and what format you would like that data in
I am rather new to the PDO library, so I apologize for my inexperience. I am writing a class that uses the PDO library to build and execute queries and return the results, no matter what they are.
Within the class, I detect whether there is an open connection to a database, and if it is the same as the one being configured, it uses this one instead. This is really easy to do using the MsSQL library as the PDO::getAttribute() function returns 'CurrentDatabase' and 'SQLServerName', so I can just apply a condition like so:
if(!empty($this->PDO)){
// Get the current connection information
$current_connection = $this->PDO->getAttribute(PDO::ATTR_SERVER_INFO);
// Return if the connection is the same
if($this->connection_parameters['hostname']==$current_connection['SQLServerName']&&$this->connection_parameters['database']==$current_connection['CurrentDatabase']){
return;
}
}
However, when it comes to MySQL, the data returned from PDO::getAttribute is completely different and I cannot seem to get the database name from the current connection.
Does any body know a function or method to get the currently connected database of a MySQL connection using the PDO library in PHP?
I order to connect to both MySQL and MsSQL, you must have 2 connections. However, changing the database on a live connection is very simple.
The following simply checks if a PDO instance already exists and whether or not it is using the required database. If so then it continues with this connection, if not it changes the database.
// Test if the PDO object already exists
if(!empty($this->PDO)){
// If connection is the same then select the database
if($this->connection_engine==$this->PDO->getAttribute(PDO::ATTR_DRIVER_NAME)){
// Get the current database in use
$database = $this->PDO->query("SELECT {$this->select_db_function}");
$database = $database->fetchAll(PDO::FETCH_NUM);
$database = $database[0][0];
// If the current database matches the new database then return
if($database==$this->connection_parameters['database']){
return;
}
}
}
I see no point in looking for the opened connection and - especially - in checking for the current database.
Why can't you just open the connection, select the database for it and then use this connection all the time throughout your class - just like everyone does?
See comments on the MySQL manual page for 'USE database'
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?