How to test Doctrine DBAL connection is successful - php

In my webapp, I am going to accept all the database connection parameters (such as username, server, database etc.) as input from the users and before saving those information, I want to quickly test if a connection can be obtained successfully based on those connection parameters.
Here is my code:
$config = new \Doctrine\DBAL\Configuration();
$url = "mysql://user:pass#server/instance"; // INFORMATION FROM USER
$connectionParams = array('url' => $url);
try {
$conn = \Doctrine\DBAL\DriverManager::getConnection ($connectionParams, $config);
if ($conn->connect()) { // GETTING ERROR HERE
echo "Connection Successful";
}
}
catch (Exception $e)
{
echo "Connection unsuccessful";
}
But I am getting HTTP 500 error at connect() call. My question is, how can I test if connection paremeters are valid?

Related

Is there a way for PHP PDO to detect if a t-sql database is being restored?

I'd like my PHP script (using PDO) to detect whether or not a target database is in the middle of a restore process other than waiting several minutes for a response from a failed connection.
My database connection code eventually returns the message below if a database is being restored, but it happens because the connection fails and it takes several minutes to respond when this happens. Searching on StackOverflow and Google doesn't seem to find anything that fits my need, nor does searching through PHP's documentation.
function getParameterizedPDOConnection($host = false, $overrideOptions = []) {
include(INCLUDE_DIR . "/itrain.config.php");
$host = strtolower($_SERVER["HTTP_HOST"]);
if (count($overrideOptions) > 0) {
$configOptions["host"][$host] = $overrideOptions;
}
$sthUserName = $configOptions["userName"];
$pwd = $configOptions["pwd"];
$addr = $configOptions["host"][$host]["addr"];
$db = $configOptions["host"][$host]["db"];
try {
$pdo = new PDO("sqlsrv:Server=$addr;Database=$db;ConnectionPooling=0", $sthUserName, $pwd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
return($pdo);
} catch (PDOException $e) {
return "Database connection failure: " . $e->getMessage();
}
}
Returns: "42000",927,"[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Database 'Workforce' cannot be opened. It is in the middle of a restore.

How to test a mongo connection in laravel 5.7?

I am using laravel 5.7 and mongo db(v1.5.3 stable).
I am trying to test connection from laravel to db but everytime I am getting successfull connection even I am providing wrong credentials.
I have tried by the following ways:
Jessengers
$arrMongo = [];
if(true == DB::connection('mongodb')) {
$arrMongo = array(
'status'=>true,
'message' => 'Mongo connection OK'
);
}else{
$arrMongo = array(
'status'=>false,
'message' => 'Mongo connection failed'
);
}
Normal PHP way
$server = "mongodb://google.com:27017/university";
$c = new \MongoDB\Client( $server );
if($c->connected)
echo "Connected successfully";
else
echo "Connection failed";
I am never getting as connection failed while testing with wrong credentials.
Please help me to resolve this problem.
Laravel only connects to the database when it needs something from the database.
You may opt for getting the list of databases inside try/catch block as follow:
try {
DB::connection()->getMongoClient()->listDatabases();
} catch (\Exception $e) {
echo $e->getMessage();
}

SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost' (2)

I have the following situation:
$DB_Environment = file('../DB/DB_Environment.txt');
$host = trim($DB_Environment[0]);
$dbname = trim($DB_Environment[1]);
$p1 = "mysql:host=".$host.";dbname=".$dbname;
$user=trim($DB_Environment[2]);
$pass=trim($DB_Environment[3]);
try {
$conection = new PDO($p1, $user, $pass);
$conection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e) {
echo $e->getMessage();
}
This is an fragment of code that gives me this error:
SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost' (2)
The code above finds the content on 1st to 4th lines in the .txt file that contains the data to configure the connection with the database.
It apparently works on my localhost, but when I run it on the server, the error appears. Then I changed the code to this:
try {
$conection = new PDO("mysql:host=infojr.com.br;dbname=pluginfo", "myuser", "mypass");
$conection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo $e->getMessage();
}
I changed the search on the .txt file by your content, and it works, but I want it to work like the first example, which only works on my localhost (PC).

How can I prevent this script from being freely accessed?

I am trying to create a simple PHP/MySQL message system. The following code is a section of the page that displays the messages a user has received, messages.php. The user's messages have been fetched from MySQL and stored in the variable $messages.
foreach($messages as $message) {
// formatting, printing the text, etc.
echo 'Remove';
}
And here is the file msg_del.php:
<?php
$id = $_GET['id'];
// Connect to the database
require("../info/dbinfo.php");
$db_user = constant("DB_USER");
$db_pass = constant("DB_PASS");
$db_name = constant("DB_NAME");
$db_server = constant("DB_SERVER");
try {
$conn = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM messages WHERE id = " . $conn->quote($id) . ";");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error connecting to database!";
exit();
}
// Redirect to messages page
header("Location: messages.php");
exit();
?>
The code is fully functional, but the problem is that anyone can type msg_del.php?id=SOMEID into a browser and delete messages. How can I secure this to where messages can only be deleted from the links on messages.php?
You're going to need some sort of token in your request to validate that this is indeed a valid request from your system.
One method would be to append a nonce to your request. This ensures that the request came from a form you control, and someone isn't using an old form to spoof a new request.
There are many nonce libraries for PHP you can choose from.
The script needs to know if the current user has permission to do the action. One simple way to do that is with the $_SESSION variable.
Something like:
session_start();
if (!isset($_SESSION['user_id']) && /*permission logic here*/) {
//display an error message
die();
}
// database query here

PDO Exceptions in PHP

Okay I have a bit of a question dealing with $_POST. I'm attempting to send a few values from an Android App (Using HTTPclient) I'm developing but the PHP sends the message from the exception back. I'm trying to figure out why is that happening and how to fix it:
login
<?php
//load and connect to MySQL database stuff
require("configmob.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
myusername,
mypassword
FROM Customer
WHERE
myusername = :myusername
mypassword = :mypassword";
$query_params = array(
':myusername' => $_POST['username'],
':mypassword' => $_POST['password']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
}
?>
config
<?php
// These variables define the connection information for your MySQL database
$host = "mysql17.000webhost.com";
$dbname = "a4335408_data1";
$username = "******";
$password = "******";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like ¢ or €, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an
associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
Thank you and I hope this question isn't too difficult or anyhting.
Try replacing the static error message with the exception message to see what's going wrong
Change:
$response["message"] = "Database Error1. Please Try Again!";
to:
$response["message"] = $ex->getMessage();
Conditions in a WHERE statement must be separated with AND keyword

Categories