Where does my PHP code make connection to the database? - php

So I am very new to MongoDB and PHP and I am trying to make a connection to the database and perform an insert query on it. I have managed to make it work, but know I do not really understand my own code.
My code:
<?php
// PHP version 7.4 used here
try {
require 'mongophp/vendor/autoload.php';
//$mongo = new MongoDB\Driver\Manager('mongodb://localhost:27017');
echo "Connection to database successfully\n";
$collection = (new MongoDB\Client)->shinto->users;
$insertOneResult = $collection->insertOne([
"name" => "testuser",
"password" => "1234",
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
echo "so far so good";
}
catch (Throwable $e) {
// catch throwables when the connection is not a success
echo "Captured Throwable for connection : " . $e->getMessage() . PHP_EOL;
print("\ndoes not work\n");
}
?>
The thing that I do not understand is how the code knows where my database is since I do not have to use the connection string.
My guess is that the mongophp/vendor/autoload.php takes care of this part, but I have looked through those files and can't seem to find the answer to my question in there as well.
Can someone help me understand how my code knows where my database is without a connection string or provide me with a link that will explain this to me?
Thank you very much in advance!

Related

PHP - Is this way I update and select from my database secure?

Recently, I switched to PDO and wanted to ask if is as safe as I do it or not?
(I filter the data before with much filter methods provided by php)
QUERY db:
include 'path_to_config_file_with_login_creds_for_db.php';
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
PDO::ATTR_PERSISTENT => false,
);
try {
$pdo = new PDO('mysql:host=' . $database_host . ';dbname=' . $database_name . ';charset=utf8mb4', $database_user, $database_pass, $options);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $exception) {
die("some error message");
}
try {
$statement = $pdo->prepare($sql);
$statement->execute($bindings);
$statement->closeCursor();
return $output;
} catch (PDOException $stmEx) {
die("again some error message");
}
UPDATE db:
include 'again_path_to_config_file_where_creds_to_db.php';
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
PDO::ATTR_PERSISTENT => false,
);
try {
$pdo = new PDO('mysql:host=' . $database_host . ';dbname=' . $database_name . ';charset=utf8mb4', $database_user, $database_pass, $options);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $exception) {
die("...");
}
try {
$statement = $pdo->prepare($sql);
$statement->execute($bindings);
$statement->closeCursor();
} catch (PDOException $stmEx) {
die("...");
}
Is this way safe or not?
It's all working fine but I want to know it its safe too
From the security point of view it should be safe as long as the query in $sql uses param binding properly. If the $sql variable is build like this then your code won't help you.
//DO NOT TRY THIS AT HOME
$sql = "SELECT * FROM `users` WHERE user='" . $_POST['user'] . "'";
But i can see several other issues with your code.
1) Your try ... catch blocks are useless. When you use PDO::ERRMODE_SILENT the PDO won't raise any exception. Only the $pdo->errorCode or $statement->errorCode properties will be set when error is encountered.
2) You are opening too many connections. I assume that you have the code you've shared in some function that you plan to call like queryDb($sql, $params); That means that every time you will call that function you will create new instance of PDO and open new connection. You might want to move the part that creates PDO instance into the db-config file then use that single instance everytime you are going to create new statement using $pdo->prepare().
3) The use of die. It's common practice to use die or exit when the query goes wrong in examples. But in actual application it would mean the user will see ugly empty page with single sentence saying something went wrong. It's better to throw an exception that will be handled higher in your app. That would let the application to display the page layout with menu and other things even if the requested action failed.
4) You do not set the value to $output variable in your first "Query DB" part of code. Although i'm not sure if you just left it out when copying or if you have it like this in your actual code.
In regards to SQL injection, as long as you parameterize all inputs and white list all dynamic SQL parts, you should be safe.
However, your code has another serious problem. You are silencing errors. PDO::ATTR_ERRMODE should be set to PDO::ERRMODE_EXCEPTION. But, that would leave your code even in a worse state, as you have die all over the place. Don't catch the exceptions unless you have extremely good reason to do so. Read this article https://phpdelusions.net/pdo#errors
Silencing or displaying errors to the user opens up new vectors for exploitation. That is why the best course of action is to leave them alone. In production system you should have the configuration set to never display errors. They will be securely logged on the server.

error in PDO connection

Hye, kindly need your help to assist me finding the error of this connection. The reason is that i didn't get submitting the data in a form to the database.
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=;charset=utf8', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
You are missing the database name.
dbname=You Forgot The Name Here;
P.S. if you don't want to include the database, you should leave the entire part.

Get bad WSDL from SoapFault?

I'm connecting to a 3rd party service with SoapClient. Most of the time it works fine, but every once in awhile, maybe once out of every 100-150 calls, I get the error
Soap Failed: SOAP-ERROR: Parsing Schema: unexpected in complexType
My code is in a try/catch with a retry, and it will work on the next round through. But I'd like to examine the WSDL to find out why that fails, partly for my own curiosity, and in case I need to pass it along to the company I'm connecting to. Can I get that information from the SoapFault? Or would I have to call the URL to get the string? I'm afraid if I get the WSDL after the fact, it may already be fixed.
$pass = FALSE;
$this->soap = NULL;
$this->session = NULL;
do {
try {
Doc::i("Starting session");
$this->soap = new SoapClient($this->wsdl_url, ['trace' => 1]);
$pass = TRUE;
} catch (\SoapFault $e) {
Doc::e('Soap Failed: ' . $e->getMessage());
if(str_contains($e->getMessage(),'Parsing Schema') && !empty($e->detail)) {
Doc::e($e->detail); // Something new I'm trying to see if it helps
}
} catch (FatalErrorException $e) {
Doc::e("Soap failed really bad: " . $e->getMessage());
} catch (\Exception $e) {
Doc::e("Soap failed bad: " . $e->getMessage());
}
} while (!$pass);
You should be able to use $this->soap->__getLastResponse() since you are passing 'trace' => 1 option to SoapClient.
You might also consider logging $this->soap->__getLastRequest as well as the headers versions of both of these to ensure you're capturing as much information as possible at run-time.
Refer to the SoapClient method list for the possible options. Just remember the trick here is the trace option: without that, these will not return anything useful!

WSO2AS Soapcall of service returns null

I'm developing a web-app, which needs data from a database.
For the communication with the db I use WSO2AS.
I made a database and linked that to the data service created, when i test the service in the admin panel of WSO2, I get the data needed from the database.
The data service I created is called TestService.
Now I want to have the same response in my php template as well, using this code.
<?php
try {
$client = new SoapClient('http://192.168.178.12:9763/services/TestService?wsdl');
$result = $client->__soapCall('greet');
printf("Result = %s\r\n", $result->return);
} catch (Exception $e) {
printf("Message = %s\r\n",$e->__toString());
}
?>
But this gives NULL, when I try to dump the $result.
When I try to execute an example WSO2 created, I do get the right result. While the soapcall code is the same, only the service name is different.
<?php
try {
$client = new SoapClient('http://192.168.178.12:9763/services/HelloService?wsdl');
$result = $client->__soapCall('greet', array(array('name' => 'Sam')));
printf("Result = %s\r\n", $result->return);
} catch (Exception $e) {
printf("Message = %s\r\n",$e->__toString());
}
?>
This code returns "Hello Sam !!!".
So I wonder what I did wrong, I personally think I made a mistake in implementing the service itself, but can't find it.
If any more information is needed feel free to ask, hope someone can help me with this.
Thanks in advance!
Apparently you need to have arguments in your soapcall.
After calling this __soapCall('greet', array());
It gave the proper response.

Check if soap connection working

Quick one,
How would you go about checking if your connection to a soap server is actually connecting?
I have this code:
$m_wsdl = "https://m2mconnect.orange.co.uk/orange-soap/services/MessageServiceByCountry?wsdl";
try {
$client = new SoapClient($m_wsdl);
$this->m_messages = $client->peekMessages('','',10,"");
} catch (Exception $e) {
echo "Exception: \n" . $e->getMessage() . "\n";
}
$this->do_parse_xml();
Obviously my username and password are in the peekmessages field where they should be, and they are both correct i am 100%.
For some reason its not returning any data at all and i dont know how to check to see if the connection is actually working??
Im getting no exceptions being echo'd
Thanks for any help
Use isSoapFault() http://php.net/manual/en/function.is-soap-fault.php
Also, the peekMessages method would probably return false or a SoapFault.
You can also set Exceptions to true on the SoapClient

Categories