PHP - Newbie - Where To Store Mysql Connection Name/password
Hi there
I am just finalising my first ever PHP/MYSQL project and I am worried about where to safely keep my connection credentials for the SQL DB.
Currently, I am storing them in ../php/config.php and this works fine, but I am worried as to the security of this
Can anyone advise please
Thanks
Similar TutorialsI have had a load of people who are silly enought to forget their username and or password so wish to add in the option for them to save their details in a cookie, and break my number one rule, never to use them!!! can anyone suggest how i can do this so it is stored safely like most websites do it. Hi, my goal is to be able to create a web based interface for someone who has no programming skills or interest to be able to maintain a list of usernames and passwords for protecting a page of links on a website. so, I've created a page that can write to a database, and I can see that it is working, I can read entries, etc. now, I need to know how to make a script that will check against that database for valid UN/PW combinations. what is the best method for this? James It seems that a class can't inherit an object as attribute? I'm trying to make my UpperNavigation class access the $this -> db attribute which is a mysqli connection. Is this possible? If not, how do I manage my connection in other classes? Code: [Select] class Connection{ public $state = false; public $db; public $db_table_names; function __construct($name){ include('dbconfig.php'); $this -> db = new mysqli($dbconfig[$name]['server'], $dbconfig[$name]['username'], $dbconfig[$name]['password'], $dbconfig[$name]['database']); $this -> state = true; $this -> db_table_names = $db_table_names; $this -> db -> query("SET NAMES 'UTF8'"); } function close(){ if($this -> state == true){ $this -> state = false; $this -> db -> close(); unset($this -> db); } } } This is my attempt of accessing Connection::$db connection. Code: [Select] class UpperNavigation extends Connection{ public $all_parents_sorted; public function printUpperNavigation(){ echo '<a href=\''.$this -> current_page.'\'>'.$this -> title . '</a>'; } public function printSearchBar(){ echo '<input type=\'text\' value=\'Search by name...\' onfocus="if(this.value == \'Search by name...\'){this.value = \'\';}" onblur="if(this.value == \'\'){this.value = \'Search by name...\';}"/>'; } public function fetchAllParents($sp_id){ $latest_id = $sp_id; if(isset($this -> db)){ echo 'yes'; }else{ echo 'no'; } $query = 'SELECT default_name, type, sp_id FROM ' . $this -> db_table_names['sport'] . ' WHERE sp_id = "' . $sp_id . '"'; $result = $this -> db -> query($query); // THIS IS THE PROBLEM } } hi everyone I have a question... does creating a connection to mysql takes time depeding on the database size? Lets say that in my entire project I will be connection to 4 databases so I created a config.php which looks like this: Code: [Select] $hostname = "localhost"; $username = "root"; $pword = ""; $con1 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename1",$con1); $con2 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename2",$con2); $con3 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename3",$con3); $con4 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename4",$con4); so, this file is included in every pages, I put this on the top. Basically every page request it will open 4 connection and the script will only use 2 connection and another page will only 1 and so on..... this style is very convenient as for I am not creating a connection in every page.. But my concern is will it effect the performance of my system? Tnx in advance..... I am slightly puzzled when I attempt to connect to MySQL using variables, if I use this:- Code: [Select] // Connect to MySQL and select dbase mysql_connect("$host", "$user", "$pwd") or die("Computer say NO!"); mysql_select_db("test_site") or die("I've just had a senior moment, and cannot connect to the database..."); I get this error:- Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'@'localhost' (using password: YES) in C:\wamp\www\php\test site\regproc.php on line 24 Computer say NO! Whereas if I use this:- Code: [Select] // Connect to MySQL and select dbase mysql_connect("localhost", "root", "my password") or die("Computer say NO!"); mysql_select_db("test_site") or die("I've just had a senior moment, and cannot connect to the database..."); it works perfectly. Most of the tutorials I have read seem to indicate that one can use variables in this case, so I do not understand why it doesn't work... The below scenario works fine but why shouldnt you do this? Why can I not just run the mysql_connect and mysql_select_db at the top of each page and then run my queries under all of this. What I have read is that the mysql_connection will die after the script finishes (at the end of the page) any way so why do people create mysql_connection objects as php is stateless so it doesnt save this any way. Code: [Select] <?php mysql_connect('localhost', 'user', 'pass'); mysql_select_db('test'); ?> <html> <body> <?php $query = mysql_query("Select * from data"); while($row = mysql_fetch_array($query)) { echo $row['name']."<br />"; } ?> -------------- OTHER HTML HERE --------------- <?php $query = mysql_query("Select * from addresses"); while($row = mysql_fetch_array($query)) { echo $row['postcode']."<br />"; } ?> </body> </html> I have a class and a lot of the function in the class require a connection to a MySQL database. At the moment I am using the "__construct()" to connect to the database each time a new instance of the classes is created. Is this the best way to do it or should I have a separate class for connection to the database? Just wanted to get an idea of what other people do. Thanks for any help. Hey there, total n00b here... Just installed and learned the basic functions of PHP and MySQL (Only have very basic programming background.) Also managed to get an Apache server running. I'm attaching a screenshot that should explain my problem entirely but in short... I can connect to and send SQL queries to my MySQL server using my terminal. My browser reads php statements over the apache server fine and it 'seems' to connect to my MySQL server fine, but it won't select a database and doesn't seem to accept other SQL queries. If I use a non-existant server name I get an error code but when I change to a non-existant user name I don't get an error code. So I'm not sure if it actually does connect or not or why the other queries doesn't work. As I said I'm VERY new to this, so I might be making some other mistake as well. Please see attached document/screenshot. Thank you Ardinent Hi Friends, i am new one to this.i have a big problem i think i will get the correct solution... when i am connecting to the MySql Database i am getting this. Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server at 'reading initial communication packet', system error: 110 in /home/txtimg0/public_html/cherple/Scheduled_Campaigns.php on line 24 unable to select database define("prod_dbuser","xxxx"); //gtmdev1 define("prod_dbpass","xxxxx"); //gtmdev1 define("prod_database_cm2","cm2"); define("prod_database_glue","glue"); define("prod_hostname","xxxxxxxx"); i am defined these constants in gtm _constants.php i am includeing this file when ever i need to connect with database. this working fine in past.now we installed the new Database from then i am getting this error. can any one Please me Help to Resolve this Issue.? and why php is not connecting to the database??? Thanks, Ramky Perhaps this is a rather lay question, but, is there a way to gather specific connection details about an open MySQL connection in php? Example: <?php $connect = mysql_connect('localhost', 'username', 'password'); ?> Using the $connect variable, could I run a command that dumps the host, and username to a log file?? Thanks in advance, I'm still searching. E I am trying to get data out off a mysql database, by using an php file. But i am not getting any output?
Examples.html
<html ng-app="countryApp"> <head> <meta charset="utf-8"> <title>Angular.js Example</title> <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script> <script> var countryApp = angular.module('countryApp', []); countryApp.controller('CountryCtrl', function ($scope, $http){ $http.get('category.php').success(function(data) { $scope.countries = data; }); }); </script> </head> <body ng-controller="CountryCtrl"> <table> <tr ng-repeat="country in countries"> <td>{{country}}</td> </tr> </table> </body> </html>category.php <?php $servername = "localhost:3306"; $username = "root"; $password = "root"; $dbname = "myDB"; $conn = mysqli_connect($servername, $username, $password, $dbname); if(!$conn){ die("Connection failed: " .mysqli_connecet_error()); } $showData = "SELECT id FROM myDB"; $data = array(); $result = mysqli_query($conn, $showData); if(mysqli_num_rows($result) > 0){ while($row = mysqli_fetch_assoc($result)){ $data[] = $row; } } else { echo "0 results"; }; print json_encode($data); mysqli_close($conn); echo($outp); ?> I'm suddenly having trouble using my connection to my MySQL database... (yes it was working but now...) I have the Connection created in an include file and stored in variable $DB, in the main file that includes the file containing the$DB there are other includes for classes. These classes are SUPPOSED to use $DB to connect to and SELECT/UPDATE/INSERT, but for a reason I cant figure out they suddenly stopped seeing $DB. it keeps saying its an undefined variable. If you need to see code I can post... Hello guys. Trying to connect php with mysql database and then display results on the screen. This is my code: Code: [Select] <?php $dbhost = "localhost"; $dbuser = "username1"; $dbpass = "password1"; $db = "username1_myDB"; $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Could not connect"); mysql_select_db($connection, $db); $show = "SELECT Name, Description FROM people"; $result = mysql_query($show); while($show = mysql_fetch_array($result)){ $field01 = $show[Name]; $field02 = $show[Description]; echo "id: $field01<br>"; echo "description: $field02<p>"; } ?> However im getting this: Warning: mysql_select_db() expects parameter 1 to be string, resource given in /home/pain33/public_html/index.php on line 20 Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/pain33/public_html/index.php on line 26 Any ideas how to fix this? Thank you. Hi,
If I place the following into a file called db.php and save it into folder called includes using xampp:
$dbhost = 'localhost'; I am using wampserver 2.2 on window 7 64 bit machine. I am using jpegcam to take snapshots and it works fine. I make upload folder within jpegcam/htdocs/upload to store snapshots. All works fine but how can i store uploaded images into mysql. I also want to retrieve image from mysql and print in php page. The problem is jpegcam used java script in form in which POST method and type file was not used. I am already done task like upload images to folder and store it into mysql using POST an $_FILES varibales . here the code of in jpegcam/htocs/test.html <form name="f1" enctype="multipart/form-data" method="" action="" > <input type=button value="Configure..." onClick="webcam.configure()"> <!-- <input type=button name="img" value="Take Snapshot" onClick="take_snapshot()"> --> <a href="javascript:void(webcam.freeze())">Freeze</a> <a href="javascript:void(webcam.upload())">Upload</a> <a href="javascript:void(webcam.reset())">Reset</a> </form> and this the code of jpegcam/htocs/test.php $target = 'upload/'; $filename = $target . date('YmdHis') . '.jpg'; $result = file_put_contents( $filename, file_get_contents('php://input') ); if (!$result) { print "ERROR: Failed to write data to $filename, check permissions\n"; exit(); } Now please tell me how can i store snapshots in mysql an retrieve it an print it in another php page.please plzplz help me as soon as possibe. please please... Thanks in advance. Hi, how do I store as a string (in a variable) a mysql query b/c what I'm doing below outputs Resource id in client browser: Code: [Select] <?php //database connection set up etc $show=mysql_query("SELECT file_Name FROM xdocument WHERE doc_id=95"); print $show; ?> Any help much appreciated, thanks. hi i want to store url to images in database for logged in users (where id = $id) and recall the image hopefully using --------------------- <img src="<?php echo row['link']; ?>" /> or similar and need help with the sql update string any ideas please help i been stuck with this for some time and now decided to ask around in this forum for help, please help if you can. Hi, So I'm trying to use another mysql connection to complete a function of mine: Code: [Select] /** * This function checks the ban status of the account. * @return 1 if banned */ function checkBan() { require("./includes/wow.php"); $result = mysql_query("SELECT * FROM wow_logon.accounts WHERE forum_acc= '.$user->data['user_id'].', $connect"); $row = mysql_fetch_array($result); if($row["banned"] == "1") { return 1; $ban_reason = $row["banreason"]; } //$user->data['user_id'] mysql_close($connect); } Inside my "wow" file, I have this: Code: [Select] <?PHP // Connect to db (edit this vars) $conf["host"] = "**"; $conf["user"] = "**"; $conf["password"] = "**"; $conf["db"] = "**"; $connect = mysql_connect($conf["host"],$conf["user"],$conf["password"]) or die(mysql_error()); mysql_select_db($conf["db"],$connect) or die(mysql_error()); ?> When executing my function I get: [function.mysql-query]: Access denied for user 'nobody'@'localhost' (using password: NO) So, I guess that my function doesn't use the ", $connect" parameter for some reason, any tips? Ok, i really need help with my registration page for my website. I've been working on this for 2 days now and i can't seem to get it to work propertly. This problem is that whenever i'm trying to register myself as a new user at my localhost website i get "Could Not Process Form" error that i've put into the code myself. I beleive this has something to do with the connection to my MySQL but i've put in "membership" as the database "root" as the username and then my password. If anyone has the time to read through my coding, i have marked the line where the error message is placed in the code.. yeah see for your self. Really need help with this! <?php class Register { private $username; private $firstname; private $lastname; private $password; private $passmd5; private $email; private $gender; private $birthday; private $errors; private $token; public function __construct() { $this->errors = array(); $this->username = $this->filter($_POST['username']); $this->firstname = $this->filter($_POST['first_name']); $this->lastname = $this->filter($_POST['last_name']); $this->password = $this->filter($_POST['password']); $this->email = $this->filter($_POST['email']); $this->gender = $this->filter($_POST['gender']); $this->birthday = $this->filter($_POST['birth_day']); $this->token = $_POST['token']; $this->passmd5 = md5($this->password); } public function process() { if($this->valid_token() && $this->valid_data()) $this->register(); return count($this->errors)? 0 : 1; } public function filter($var) { return preg_replace('/[^a-zA-Z0-9@.]/','',$var); } public function register() { mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("membership") or die (mysql_error()); mysql_query("INSERT INTO users(username,password) VALUES ('{$this->username}','{$this->passmd5}')"); if(mysql_affected_rows()< 1) $this->errors[] = 'Could Not Process Form'; <------------------ HERE IS THE ERROR MESSAGE I'VE PUT IN THE CODE TO SPIT OUT IF SOMETHING GOES WRONG } public function user_exists() { mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db("membership") or die (mysql_error()); $data = mysql_query("SELECT username FROM users WHERE username = '{$this->username}'"); return mysql_num_rows($data) > 0 ? 1 : 0; } public function show_errors() { echo "<h3>Errors</h3>"; foreach($this->errors as $key=>$value) echo $value."<br>"; } public function valid_data() { if($this->user_exists()) $this->errors[] = 'Username Already Taken'; if(empty($this->username)) $this->errors[] = 'Invalid Username'; if(empty($this->firstname)) $this->errors[] = 'Invalid First Name'; if(empty($this->lastname)) $this->errors[] = 'Invalid Last Name'; if(empty($this->password)) $this->errors[] = 'Invalid Password'; if(empty($this->email) || !preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$/',$this->email)) $this->errors[] = 'Invalid Email'; if(empty($this->gender)) $this->errors[] = 'Invalid Gender'; if(empty($this->birthday)) $this->errors[] = 'Invalid Birthday'; return count($this->errors)? 0 : 1; } public function valid_token() { if(!isset($_SESSION['token']) || $this->token != $_SESSION['token']) $this->errors[] = 'Invalid Submission'; return count($this->errors)? 0 : 1; } } ?> |