I have an issue with mysqli_connect
expecting the parameter to be a string and apparently an array is given
I have a php file that writes the mysqli_connect
information to a file from variables “userconnection.txt”
'localhost','root','','forum'
Then I have a standard php connection.php file with the added userconnection.txt file for the host user and password.
<?php $connectionlink = file('userconnection.txt'); $connection = mysqli_connect($connectionlink); if (!$connection) { die('Connect Error: ' . mysqli_connect_error()); } ?>
It spits out the error:
Warning: mysqli_connect() expects parameter 1 to be string, array given in /Applications/XAMPP/xamppfiles/htdocs/forum/install files/connection.php on line 4 Connect Error:
Advertisement
Answer
This will not work and is actually a security risk.
Security
The txt file might be accessibe from your website via some URL. An attacker who know that URL (not difficult at all) can get the file and now has your login credentials. Save the file outside your webroot or change it’s extension and contents so they arent publcly avaiable. maybe a PHP file?
Error
You have two problems. First one is that file
returns all lines of the file as individual lines and not as one string. Use file_get_contents
instead.
Anyways, if you do this, you will still have all three parameters in one single variable of type string. But the mysqli_connect
function needs three seperate variables and not one. You can fix this with a explode
.
Quick and dirty Solution
$filecontents = file_get_contents('userconnection.txt'); $connectionvars = explode("," $filecontents); $connection = mysqli_connect($connectionvars[0], $connectionvars[1], $connectionvars[2]); if (!$connection) { die('Connect Error: ' . mysqli_connect_error()); }
Better but more complex solution
Create a PHP file with your connection variables:
<?php $DBHost = "host"; $DBUser = "user"; $DBPass = "pass";
change your connection file to this:
<?php require("connectionsettings.php"); $connection = mysqli_connect($DBHost, $DBUser, $DBPass); if (!$connection) { die('Connect Error: ' . mysqli_connect_error()); }