Thursday, 29 September 2016

php - Using user-supplied database credentials across multiple pages



I am learning to use MySQL with PHP and while practicing, I tried to create a simple web application using Core PHP and MySQL. It is summarized below:



-It has a pretty simple html page where username(uname) and password(pword) for MySQL are input in a form and are sent by POST method to a PHP script called PHP1.php



-PHP1 makes connection to MySQL. The code is(skipping PHP tags):



//Get input username and password
$username = $_POST['uname'];
$password = $_POST['pword'];
//Server information
$server = "localhost";
//Connect
$conn = new mysqli($server, $username, $password);
//Check success/failure
if ($conn -> connect_error)
{
die("Connection failed".$conn->connect_error);
}


After connecting, PHP1 retrieves information about the databases stored in the respective account and displays radio buttons to select the database and sends the name of the selected database by GET method to another script PHP2.php



-In PHP2.php I want to display the TABLES in the selected database.
However, when control is transferred to PHP2.php, connection to MySQL is terminated. I first tried to include my PHP1.php file in PHP2.php and use the $conn variable but ofcourse it'll try to reconnect to MySQL due to the above mentioned code and at the same time, the first request containing uname and pword is lost resulting in an authentication error.



How can I overcome this problem?



EDIT:
I have seen other questions here but all of them have fixed usernmae/passwords and so the connection script can be placed in a separate file easily. I require to take username and password from the user.


Answer



Use Sessions which will persist the session variables across pages:



PHP1



session_start();
$_SESSION['username'] = $username = $_POST['uname'];
$_SESSION['password'] = $password = $_POST['pword'];

$server = "localhost";
$conn = new mysqli($server, $username, $password);


PHP2



session_start();
$username = $_SESSION['username'];
$password = $_SESSION['password'];

$server = "localhost";
$conn = new mysqli($server, $username, $password);


In PHP1 you're going to want to check that the $_POST values are set and in other pages you'll want to check that the $_SESSION variables are set. See isset.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...