Here's my config file:
<?php
#config variables
$host = ''; #your database host
$user = ''; #your database username
$password = ''; #your database password
$database = ''; #your database title
$page_title = ''; #this appears at the top of the webpage and in the browser tab/window.
$tbl_prefix = ''; #the prefix on your database tables.
$installed = false; #if false, you'll be redirected to an installation page.
if($installed == false) {
header('Location: install/index.php');
}
else {
#connect to db
$consult_err = ' Consult lib/sqlerrors.html';
$connect = #mysql_connect($host, $user, $password)
or die('Errno(1) - Invalid connection details.' . $consult_err);
#mysql_select_db($database, $connect)
or die('Errno(2) - Couldn\'t connect to database.' . $consult_err); #select database
}
?>
I have an installation script that gets all the variables above from a user, checks to make sure there's a mySQL connection/database present, and creates some tables. However, I haven't found a good way to edit the above file with the user's input.
I'm rather stuck on where to go from here, but I need the end result to be taking input from a form, and having the variables in the configuration file reflect that input.
Any suggestions?
I think that doing this will only lead you down a very difficult, twisty path. May I recommend using PEAR's Config package? It can generate, manipulate, and read configuration files in INI, PHP array or constant, XML, or generic formats.
Another option would be to only store the values that change very rarely (e.g. database connection info) in the configuration file and then store the rest of the configuration options in the database. This is how most larger PHP applications do it, I believe (I'm thinking of WordPress specifically). Users will have to edit the file manually if they want to change those settings, but since the more frequently-changed settings are in the database (and that's easy to hook up to your configuration form), they'll only very rarely have to edit the file.
You can use the PHP filesystem functions to open the file and write out a modified version.
Related
I am very new to php. Currently I am working on a project, where data from a database server should be fetched and then returned to a client. I have got this little code snippet:
<?php
$host_name = 'host';
$database = 'db';
$user_name = 'user';
$password = 'passwd';
$link = new mysqli($host_name, $user_name, $password, $database);
if ($link->connect_error) {
die('<p>Connection failed</p>');
} else {
echo '<p>Connection success.</p>';
}
?>
The ugly part is, that the password is written in the source code. When using gitlab or something similar, the password is always uploaded - in each software version. This is (of course) a huge security risk. How can I make this more safe? Store the password in a file and read the file with php to get the database password - would that be a good solution?
To do that, you could use a framework like Laravel, but It would be a major change in your development.
What Laravel does is generate a .env file. This file contains all the app credentials (database, mail, etc.). You could do the same : make a file that won't be in your git (add it to your .gitignore) (a JSON file for example).
When you clone the repository, you will just have to create this file.
For example, a JSON file named credentials.json :
{
"database": {
"login": "your-login",
"password": "your-secret-password"
}
}
You can easily read a JSON file with PHP.
Clearly, you have to manage your .htaccess to make this file unreadable from the outside.
Note : you can add to your git repository a blank file to keep the JSON file structure, without the credentials in a credentials-example.json :
{
"database": {
"login": "",
"password": ""
}
}
After cloning, you will just have to rename the file and add the credentials.
I'm a total beginner when it comes to PHP, I have a fair grasp of the syntax but I'm not sure about the safest way to utilise it to connect to my server. I apologise that this is a sort of generic question rather than a code problem, since my code technically works.
I have a .php site doc with a basic comment submission form. The only way I can think of to connect to the server is to allow a "dummy" user with select only privelege to call a stored function to accept the comment.
If my dummy account is called siteuser then am I going round this the right way? This is the section of the PHP that I'm using to connect. I believe this code is only visible server side so nobody can ever see it and use the password or username to connect some other way? Or is there a sort of default string I can use in my php without creating the dummy user, seeing as the php and server is all hosted via the same provider?
$sqlserv = "localhost";
$sqlname = "siteuser";
$sqlpass = "mypassword";
$sqldbdb = "comments_table";
$conn = new mysqli($sqlserv, $sqlname, $sqlpass, $sqldbdb);
What i do is this to connect to my DB
db.php:
<?php
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/somepath/config.ini');
//Mysqli Connection
$conn = new mysqli($config['host'], $config['user'], $config['pass'], $config['dbname']);
if($conn->connect_errno > 0){
die('Unable to connect to database [' . $conn->connect_error . ']');
//Set encoding
mysqli_set_charset($conn, "utf8") or die;
}
?>
and in config.ini:
[database]
user = johndoe
pass = someweirdpassword
dbname = the_name
host = localhost
both files have 700 permissions, so only user (and no one else can access it)
also the config.ini file is placed somewhere outside the public_html directory, i'm not totally sure if that helps or not but i do it that way.
I have a php file which retrieves some important data from my database, for now if anybody access the php file via URL, it directly displays the data which i don't want to happen.
Is it possible create a password input box which will prompt for the database password and assign its value to $password variable (see the code below) , so that only if the user inputs the correct password, only then the file will interact with the database?
UPDATE TO THE EXAMPLE CODE :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>`
When this php file is accessed via a browser, it displays :
Peter Parker
Glenn Forbes
I don't want people to see the output directly! I want them to first input the password, so that php file interacts with the database and displays the output!
Hope you people got me this time!
If I were you (and if I'm understanding your problem correctly) I would use an htaccess file. Basically, you will create two files in the directory you want to protect. The first, you will name .htaccess. That's all you need in the file name. Open the file in an editing program (e.g: Notepad++) and insert the following code:
AuthType Basic
AuthName "restricted area"
AuthUserFile "the/path/to/the/directory/you/are/in/.htpasswd"
require valid-user
The .htpasswd you see is the file name of the second file you will create. Create that file (with the name .htpasswd), and open it to edit it. In that file, type in the username of the person who is to enter the directory.
JohnDoe
Followed by a colon.
JohnDoe:
Now, go to a website like http://www.htaccesstools.com/htpasswd-generator/ and type in the Username (just put in "test") and password you want in the fields provided. Submit the information.
After you do that, it will pop up with a formatted line of information. Copy the mess of letters after the colon and paste them after the colon in your .htpasswd file. Save your work.
JohnDoe:$apr1$eBsB98Mg$93ckYxSmT5BBfPqOS5a/6.
Now that you have done all that, when someone goes to the directory on your website, they will be prompted to give the username and password. If they know it, it will let them in, and then display what is in your PHP file (you will need to make sure the file is named index.php.
I hope that helps!
There are many ways...
<?php
if($_GET['token'] != 'a1a2a3a4a5') {
die('Wrong request!');
}
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
Then access your page from:
http://www.example.com/readdata.php?token=a1a2a3a4a5
Apache (or any other server) will execute files based on the file extension it sees and that it has been told what to do with. If that isn't told specifically, it will display it simply as text.
If your server is running PHP files fine, you can include any filename you like - that includes the extension and PHP will assume it is simply PHP. If you try to get tricky however and call it a .php5 or a .include and you haven't set up your server to run these file types as PHP, it will be output to the user as simply text.
Set up the file types properly on your server or call them all by the default extension.
Based on the code you provided:
<?php
$host = "localhost";
$db_name = "NAME_OF_THE_DATABASE";
$username = "root";
$password = "PASSWORD_OF_THE_DATABASE";
?>
A user entering this exact URL will see a grand total of NOTHING. That is because when the file is being executed as PHP, it simply assigns the variables values - it doesn't ever display them.
If the file isn't associated as a PHP executable file, your server will send the contents to the user as they are - showing all your code as you wrote it.
From your question what i understood is you don't want any body to see the password, so i think
you can encrypt you php code and still run it on the server
user the following tools
you can definitely hide/encode/encrypt the php source code and 'others' can install it on their machine. You could use the below tools to achieve the same.
Zend Guard
IonCube
SourceGuardian
phpSHIELD
You should not see the code in the screen unless your file add .php, check extension.
I suggest you separate database detail in a new php file, and move it in up level directory
HTML CODE:
<form action="{your url}">
Please enter you password:<input name="password" type="password" />
<input type="submit" value="Submit" />
</form>
PHP code:
$password=$_GET['password'];
if($password=="1234"){
echo 'correct password';
//and add your code here
}
I am programming a game in PHP and have the following code to connect to a database
//$sqldb=mysql_connect('godaddy.hostedresource.com', 'godaddyUserName', 'godaddyPassword') OR die ('Unable to connect to database! Please try again later.');
$sqldb=mysql_connect('localhost', 'root', 'mypassword') OR die ('Unable to connect to database! Please try again later.');
The trick here is that if I am on the production server I comment out the godaddy database; when I upload the code to the server I then comment out the localhost code instead.
Unfortunately the ineveitable has happened and I uploaded the code with the wrong connection commented out; this led to 24 hours of locked out customers! :(
Is there a way to have the code to tell if it is on the localhost server, and if it isn't it then looks for the godaddy connection?
you can try this to identify if its on live or localhost
if($_SERVER["SERVER_NAME"] == "localhost"
&&
$_SERVER["SERVER_ADDR"] == "127.0.0.1"){
// in localhost
$hostname = "localhost";
$username = "localuser";
$password = "localpassword";
}else{
// not in localhost
$hostname = "livehost";
$username = "liveuser";
$password = "livepassword";
}
and fail if couldn't connect to database but save the error into a file.
if(!mysql_connect($hostname,$username,$password)){
file_put_contents("mysql_connect.error",mysql_error(),FILE_APPEND);
die("Couldn't connect to database");
}
a suggestion, try not to use mysql_* anymore, switch to PDO or mysqli ..
if ($_SERVER['SERVER_NAME'] == 'the.name.of.your.devel.server') {
$host = 'localhost';
} else {
$host = 'name.of.godaddy.server';
}
$sqldb = mysql_connect($host, ....);
i normally use a method of obtaining the URL / domain of the site? This can work in certain situations and setups. Otherwise if your operating with a fixed IP than you can also use this method
Have a look over the methods using $_SERVER
PHP $_SERVER
One way would be for you to check your external IP address and see where you are. A solution should present itself by looking at the properties inside the $_SERVER global variable.
I have a good suggestion : You coding a game , game is a big program, you don't use mysql* function directly in big program , because yourself should handling them, such as error handling.i suggest you use a DB-Handler. please google for : DB-Handler PHP
As has been mentioned by other people, you can obtain the current site your script is running on using the $_SERVER variable. However, I would like to provide an alternative solution.
You could make a folder in your website (both local and production), something like config, then store a configuration file in it, for example config.php, with the following:
<?php
// Local
$db_host = 'localhost';
$db_username = 'root';
$db_password = 'mypassword';
?>
And for production:
<?php
// Production
$db_host = 'godaddy.hostedresource.com';
$db_username = 'godaddyUserName';
$db_password = 'godaddyPassword';
?>
and disallow access to the directory with a .htaccess file in the directory, something like:
deny from all
Then, in your PHP code, do the following:
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/config/config.php");
$sqldb=mysql_connect($db_host, $db_username, $db_password) OR die ('Unable to connect to database! Please try again later.');
?>
Now, simply leave the different configuration files where they're at and upload everything else, so your code will access different configuration files whenever it runs.
Also, the .htaccess file should prevent anyone from accessing the file via HTTP, and having the file contents in PHP tags, as well as a .php extension should prevent anyone from seeing any contents if they were able to access the file (PHP would parse the file before it is rendered, and would output nothing).
I am using moodle and I change location of my web site, but I am facing this error.
My config.php is:
<?php /// Moodle Configuration File
unset($CFG);
$CFG->dbtype = 'mysql';
$CFG->dbhost = 'localhost';
$CFG->dbname = 'lightsys_test';
$CFG->dbuser = 'lightsys_test';
$CFG->dbpass = '123456a';
$CFG->dbpersist = false;
$CFG->prefix = 'mdl_';
$CFG->wwwroot = 'http://www.lightsystem.ir/aya/moodle';
$CFG->dirroot = '/home/lightsys/public_html/aya/moodle';
$CFG->dataroot = '/home/lightsys/public_html/aya/moodledata';
$CFG->admin = 'admin';
$CFG->directorypermissions = 00777; // try 02777 on a server in Safe Mode
require_once("$CFG->dirroot/lib/setup.php");
// MAKE SURE WHEN YOU EDIT THIS FILE THAT THERE ARE NO SPACES, BLANK LINES,
// RETURNS, OR ANYTHING ELSE AFTER THE TWO CHARACTERS ON THE NEXT LINE.
// /home/lightsys/public_html/aya/moodle/
?>
And my error is:
Error: Database connection failed.
It is possible that the database is overloaded or otherwise not running properly.
The site administrator should also check that the database details have been correctly specified in config.php
Thanks to everyone.
My problem is solved. I had not set the right permission to my database, for my user, and when I did it my problem was solved.
This error message could mean:
mysql server is not running on localhost (the indicated server)
any of the other parameters (db name, login, password) in config.php are wrong
Can you connect to mysql using those credentials through the mysql command line client (or phpmyadmin or similar)?
You may want to post more info about your server environment.
I had the same problem.
I edited the database port because I'm not using the default MySQL port which is 3306.
If you are using the default port, leave it as an empty string.
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,CREATE TEMPORARY TABLES,DROP,INDEX,ALTER ON moodle.* TO username#localhost;
Use the following query to grant permissions to your user. Remember to change username with your db user that you've created.