I learned (from internet tutorials) to create separate file, like mysql.php, with password and username.
$dbserver = "localhost";
$dbname = "";
$dbpass = "";
$dbname = "";
$db = mysql_connect($dbserver, $dblogin, $dbheslo);
mysql_select_db($dbnazev, $db);
And whenever I would need connect to mysql, I would use in my code include "mysql.php".
But doesn't it mean, that anybody in the internet can include this file to his script and get into my database?
BTW: My hosting is not using localhost, it's using mysql87.example.com... .
For your situation I can say to that it IS safe to use it that way (not my way, i like classes) and this is why:
When you start your web server there is php server started also (mod_php, php-fpm, php-cgi or other). This php server exclude from document, that will be shown to any other person that includes it thru web server.
This means that code
<!-- SOME CODE HERE -->
<?php require('mysql.php'); ?>
<!-- SOME CODE HERE ALSO -->
will be rewrited to
<!-- SOME CODE HERE -->
<!-- SOME CODE HERE ALSO -->
So anyone who includes this file will not see php code.
This means that it is safe to use it like this. But i recommend to secure direct access to such kind of files.
index.php
<?php
define ('MY_CUSTOM_CONSTANT', 42);
require('mysql.php');
// Other code
mysql.php
<?php
defined('MY_CUSTOM_CONSTANT') or die('You cannot access to this file directly');
In this case even if they include or just call this file from web - they will just get text message and code will not be executed in this case
Anyone can browse to your script, and it'll connect to the database, but the script will then immediately end. Assuming you aren't messing around with form or cookie variables in your mysql.php script, the would-be attacker is left with no way to run a query, so your database is safe.
Related
I am writing php scripts for a server code. These include sign up, log in, and similiar functions. These functions often reference the same database and URLs. I have been reading on stackoverflow and google that the user of a global PHP file and using a simple include is a bad idea. Seen below:
global.php
<?php
$databaseHost = "someurl.com";
$databaseUser = "adminUser";
$databasePassword = "adminUsersPassword";
$databaseName = "dbName";
?>
serverFile.php
<?php
include 'global.php';
//mysql functions that use the variables below
$databaseHost;
$databaseUser;
$databasePassword;
$databaseName;
?>
Can someone explain to me the safest way to do such includes or is it better that I just write all the information directly into every server php file? This seems like it will be hard to keep updated if we change / update our database or change our server host.
If you could also explain why you recommend what you recommend that would be greatly appreciated. I have a very good understanding of other programming languages and hardware (I'm a computer engineer), so in depth explanations are welcome.
Sorry for not having an exact problem, but I am very lost on how to best approach this. Thanks in advance for the stackoverflow knowledge.
This is fine. The only thing you should do is put the file outside of your web root (public_html). That way it can't be accessed directly, but instead can only be accessed from code.
I have created a database connection instance in PHP like:
$mysqli = mysqli_connect("localhost", "root", "blabla", "blabla");
I need to pass this database connection to other PHP files, since I have an HTML form that first inserts data into a database and then it goes to a PHP page that retrieves data.
I know that I must not instantiate the database connection each time but I do not know how to do it, because I am not so familiar with OO PHP.
You can just name a file connection.php and store your line for connection to database.
Then you can include your file like this :
require_once('connection.php');
This will be the content of connection.php :
$mysqli = mysqli_connect("localhost", "root", "blabla", "blabla");
And then this way, your file will never load twice.
If I understand you correctly, I think you misunderstand what you've read.
In PHP how most systems (phpBB, WordPress, etc) do it is there is a base include file that is included at the start of each PHP page. In phpBB it is called "Common.php" if I remember correctly.
Common.php goes through and does a few things:
It reads the database configuration files and connects via the most acceptable database connection type (mysql_connect, or mysqli_connect, depending, or another connection if you aren't using MySQL).
It then unsets the database password variable (so that someone, on an off chance, couldn't figure it out via SQL Injection)
includes other files necessary for the system to function - certain user-made functions or class definitions.
This is done via one of 4 functions:
include('common.php') will include the contents of the file at the point it is written in the file. E.G.
<?php
do_function();
include('common.php');
do_other_function();
?>
Will run do_function(), then run any script in the common.php file, which could theoretically hold the definition for do_other_function(), and then run do_other_function();
include_once('common.php') makes sure that a file is run through the process only once. This is good for things like class definitions as it ensures a class is not accidentally re-defined. E.G.
<?php
include_once('database_class.php');
//Code here code here
...
//Oh crap, did I include that database class? I can't remember. I think so...maybe not
include_once('database_class.php');
?>
Will only include the database class def one time. Where as the same example above with include('database_class.php'); instead of include_once would throw an error akin to the class 'database' is already defined
Note, include and include_once will only throw warnings if a file does not exist, and if you have error reporting set to only show fatal errors, you won't notice when something isn't included except for perhaps a "constant/function/class 'something' not defined" and you'll scratch your head for perhaps a long time. So if you try to include the file 'cmmon.php' when you meant 'common.php', you may or may not see an error.
then there is the require and require_once functions, they do effectively the same thing as include and include_once, but unlike the latter two the script will stop running if it cannot include the file and throw an error, like "could not include file 'something.php' on line # [line] in file [file path]"
Use require for scripts that are absolutely necessary - function/class/constants that your scripts will need in order run properly.
Use include for things that are voluntary, the first thought that came to mind would be plugins - things that don't necessarily have to be there in order for your system to work as intended.
If $mysqli is global, then all php files can see it by peeking the $GLOBALS array, assuming the php is included.
For example:
$mysqli = mysqli_connect(..); // in global space
another php file:
$GLOBALS["mysqli"]; // use that
inside a php function you could also do:
global $mysqli; // use that
How to connect a html page to MySQL for example, i want to use <?php echo $_POST['username']; ?> in a HTML file. How do i connect to MySQL.
I have tryed this:
<?php
$con=mysql_connect("HOST", "USERNAME", "PASSWORD");
mysql_select_db("DATABASE");
?>
But it did not work.
HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.
You need to run it on a server not just in a browser.
Download Apache, Install PHP and save the file with a .php extension. It then should work.
Then you can echo out a $_POST value but you wont need SQL for that.
You cannot add whatever PHP code to an HTML page. it have to be a PHP page.
you don't need a mysql connection to echo $_POST['username']
you should never echo any $_POST variable. After processing a POST request, web-server ought to order the browser to reload the page using GET method. Not required for the AJAX calls though.
You cannot run PHP scripts in HTML files. Your file must have .php extension to run php scripts.
You should use MySQLi instead of mysql_ functions, because these functions are depricated!
You can not do this in html page, you need to write the code in a PHP file and save it on a server then execute it.
NOTE : mysql_* functions are deprecated, you should use the newer mysqli_* or PDO features of PHP.
Of course it should not work because html is client side and you are doing connection at server side so you might need a something great called server-side scripting language to accomplish your task.
How ever you can still do it in html page with ajax but as i said you has to use server-side scripting language.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to secure database passwords in PHP?
Recently I was given a website project which was supposed to be done in PHP but I don't have much experience in PHP. Anyway, it is up and running but there is a big room to improve. The one thing that I am not feeling well is the way I am dealing with database: I put the database connection information in a separate db.php file and include it where needed. But I remember seeing PHP source files returned by the server many a time.
So now my question is: what is a better or the best way / place to put database sensitive data?
By the way, how NOT to let PHP show error messages on web pages when things are gone wrong? A custom error page or settings somewhere in php.ini? Thanks!
Note: I am using PHP in it's old flavor not object-oriented way. But I am open to object-oriented or MVC way if there are better approaches that way to prepare for future projects
I don't know if this is what you are looking for:
You can put your sensitive data in your db.php, but outside the web root directory (public_html or www).
For example, you could have a directory called config which is a sibling of your web root directory, and store your db.php file there.
You can include your db.php file like this:
require_once('../config/db.php');
I hope this helps.
Its fine to put it in a db.php file, just use require_once() just after the opening <?php tag of each document.
If basedir restriction is not in effect, move db.php file outside of your web/ftp root that way its definitely not accessible via http/ftp. Make sure permissions are set properly on this file though.
Since you aren't using OOP or an MVC structure for your code this is the best route to go.
I would personally create a file called db.php and place this above the public_html folder on your server
for example
<?php
error_reporting(0);
$link = FALSE;
$link = mysql_connect('hostname', 'username', 'password');
if ( ! $link)
{
die("Couldn't connect to mysql server!");
} else {
mysql_select_db('databasename');
}
?>
This turns off error reporting at the same time as connecting to your database, from your index.php you would include the file like so:
<?php require('../db.php'); ?>
I am getting the following error:
Access denied for user 'apache'#'localhost' (using password: NO)
When using the following code:
<?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
echo "<h1>Delete Story</h1>";
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)){
echo '<b>'.$row[1].'</b><span align="right">Delete</span>';
echo '<br /><i>'.$row[2].'</i>';
}
}
else {
echo "No stories available.";
}
?>
The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if.
I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.
And if it matters at all, apache#localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.
If it is saying 'apache#localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection.
If you do the connection right in your script, not in a called file, do you get the same error?
Change the include() to require(). If the "connect.php" file can't be require()d, the script will fail with a fatal error, whereas include() only generates a warning. If the username you're passing to mysql_connect() isn't "apache", an incorrect path to the connect script is the most common way to get this type of error.
Don't forget to check your database error logs. You should be able to see if you are even hitting the DB. If you aren't, you should check your firewall rules on the box. On a linux box you can run iptables -L to get the firewall list rules.
Otherwise it will be a pure access issue. Do a "select * from mysql.user" to see if the apache user is even set up in there. Further, I would recommend creating an account specifically for your app as opposed to using apache, since any other app you create will run as apache by default, and could get unauthorized access to your db.
Just look up "GRANT" in the documentation # dev.mysql.com to get more info. If you have more specific questiosn regarding db, just edit your question, and i will take a look.
Does the connect.php script actually make the connection or does it just define a function you need to call to create a connection? The error you're getting is symptomatic of not having a previously established connection at all.
ETA: Also change the include to a require. I suspect it's not actually including the file at all. But include can fail silently.
Dude the answer is a big DUH! which unfortunately it took me a while to figure out as well. You probably have a function like dbconnect() and you are using variables from an include file to make the connection. $conn = mysql_connect($dbhost, $dbuser, $dbpass).
Well since this is inside a function the variables from the include file need to be passed to the function or else the function will not know what $dbhost, $dbuser and $dbpass is. A way to fix this is to make those variables global so your functions can pick them up. Another solution which is not very secure would be to write out you host, user and pass in the mysql_connect function.
Hope this helps but I had the same problem.
Did you remember to do:
flush privileges;
If the user is not set up then it will give the 'apache'#'localhost' error.
Just to check, if you use just this part you get an error?
<?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
If so, do you still get an error if you copy and paste one of those Inserts into this page, I am trying to see if it's local to the page or that actual line.
Also, can you post a copy of the connection calls (minus passwords), unless the inserts use exactly the same syntax as this example.
Just to check, if you use just this part you get an error?
If so, do you still get an error if you copy and paste one of those Inserts into this >page, I am trying to see if it's local to the page or that actual line.
Also, can you post a copy of the connection calls (minus passwords), unless the inserts >use exactly the same syntax as this example.
Here is what is in the connection.php file. I linked to the file through an include in the same fashion as where I execute the INSERT queries elsewhere in the code.
$conn = mysql_connect("localhost", ******, ******) or die("Could not connect");
mysql_select_db("adbay_com_-_cms") or die("Could not select database");
I will try the working INSERT query in this area to check that out.
As to the others posting about the password access. I did, as stated in my first posting, check permissions. I used phpMyAdmin to verify that the permissions for the user account I was using were correct. And if it matters at all, apache#localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.
You can do one of the following:
Add the user "apache" and setup its privileges from phpmyadmin or using mysql on a shell
Tell php to run mysql_connect as another user, someone who already has the privileges needed (but maybe not root), look for mysql.default_user in your php.ini file.
Does the apache user require a password to connect to the database? If so, then the fact that it says "using password: NO" would lead me to believe that the code is trying to connect without a password.
If, however, the apache user doesn't require a password, a double-check of the permissions may be a good idea (which you mentioned you already checked). It may still be beneficial to try executing something like this at a mysql prompt:
GRANT ALL PRIVILEGES ON `*databasename*`.* to 'apache'#'localhost';
That syntax should be correct.
Other than that, I'm just as stumped as you are.
If indeed you are able to insert using the same connection calls, your problem most likely lies in the user "apache" not having SELECT permissions on the database. If you have phpMyAdmin installed you can look at the permissions for the user in the Privileges pane. phpMyAdmin also makes it very easy to modify the permissions.
If you only have access to the command line, you can check the permissions from the mysql database.
You'll probably need to do something like:
GRANT SELECT ON myDatabase.myTable TO 'apache'#'localhost';