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.
Related
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'd like to know if I can use PHP in order to get data from a MySQL database. A fraction of the code can be seen here:
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT aa, bb, cc FROM data";
$result = $conn->query($sql);
...
?>
This is placed inside an HTML file in the Play Framework folder "views", and is properly loaded by the controller, but when it loads, it just shows me the code as if it were text, and not code or the action that would be supposed to do, so it is like it does not recognise it. How can I solve it?
No, you cannot use PHP inside templates, Play doesn't parse PHP at all, actually it doesn't even know there is something like PHP.
P.S. Trying to reuse PHP code in your Java app will be much more difficult than learning the valid approach with Java only, see answer for similar post (it's about MySQL raw access, not PHP integration) which you can reuse in several minutes: https://stackoverflow.com/a/31118795/1066240
As bjfletcher mentioned you would need to configure both runtimes to be able work with Java and PHP at one server but it will NOT allow you for using PHP in Play's templates anyway! so it doesn't make deeper sense.
Play doesn't know PHP.
You need two runtimes:
Play runtime
PHP runtime
and use HTTP for integration. For example, if PHP code is on http://localhost/products then Play would send a GET request to this URL for a response. Play can then use this response to do whatever you want.
For example:
def index() = Action {
WS.get("http://localhost/products").get.map { resp =>
Ok(views.html.index(resp.body))
}
}
then in your view template:
#(resp: String)
<h1>Products</h1>
#resp
Best thing to do is write it totally in php. Forget about using the bloated playframework and trying to figure out all the connections that you would have to make to tie it all together.
Is it safe to store data required to connect to a database in a .ini file ?
I build something like this
<?php
include_once($_SERVER['DOCUMENT_ROOT']."proto/class/Database.php");
function connect()
{
$config = parse_ini_file($_SERVER['DOCUMENT_ROOT']."proto/admin/config.ini");
$host = $config['host'];
$username = $config['username'];
$password = $config['password'];
$database = $config['dbname'];
$db = new Database($host,$username,$password,$database);
return $db;
}
?>
I wonder if using important variables within a function is a good way to proceed.
If you save your infos in an ini file or in a php file is a personal thing I guess. What makes it secure is that your file should not be saved in your public web path.
So ensure that the file you read/include is outside of your document root.
I would ask why? Why not make it a PHP file?
<?php
return array(
"host" => "...",
"username" = "...",
//...
);
Then when you need it, just call $config = require "config.php";
This is better than an ini file, since it's parsed (you'll get syntax errors for mistakes rather than ignoring the mistake) and since the parsing is cachable (opcode cache).
Additionally, it's protected from direct web access even if it's in the webroot (or a server misconfiguration allows direct access to the file).
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).
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.