473,396 Members | 1,895 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Is it okay to make a connection to the database in a session?

44
Hello,

I am making an interface to a database(MySQL) of questions. Is it possible to connect to the database using mysql_connect() just once, in a session and use the connection thereafter in the following pages and until the user logs out? If it is, Is it okay to do so.. I just read that the session files are stored in some directory on the computer. I wanted to know if its okay and wise to connect this way, given connecting requires the password to be given.

Thank you :)
Hanaa.
Sep 17 '08 #1
13 1848
Dormilich
8,658 Expert Mod 8TB
this will probably fail, since any mysql_connect() connection is closed at script end. you can use mysql_pconnect(), but what's wrong with connecting to MySQL each time when the next page is processed (build/loaded/...)? (despite that this is probably more secure)

regards
Sep 17 '08 #2
hanaa
44
Is there no problem.? I mean, is it okay to connect to the database on each page, I thought having to connect many times is some kind of an overhead. Please correct me if 'm wrong. I read about persistent connections too, and also that they are not closed until the server is shut down/restarted.. Would you please give me a few lines on as to why connecting each time is okay..?

Would you also tell me if storing username and password in a session is okay and safe? Cant session files be intercepted in any manner?

Thanks,
Hanaa
Sep 17 '08 #3
pbmods
5,821 Expert 4TB
Heya, Hanaa.

Opening a connection is not a whole lot of overhead, and there are negatives to using persistent connections (you won't always get the same connection, so you can't rely on temporary tables and variables in between page loads).

You shouldn't need to store the User's password in cleartext; run it through sha1() or md5() before storing it instead.

Storing sensitive information (including login credentials) in a session is generally a bad idea because it is possible to intercept them.

Session data is stored (usually) in files in the /tmp directory on your server, so if the attacker can access those files, he can read your Users' session data.

A really simple (if unlikely) example of an exploit would occur if you had an insecure image loader script:

Expand|Select|Wrap|Line Numbers
  1. <?php readfile("/path/to/images/{$_GET['imagefile']}"); ?>
  2.  
An attacker could abuse this by setting $_GET['imagefile'] to '../../../tmp/{session_key}', where {session_key} is the 40-char session ID. Then he would be able to see the User's session info.
Sep 18 '08 #4
hanaa
44
Thanks pbmods and Dormilich.

I am making a database interface. So, I granted the necessary privileges to a user. Since (I'm considering that) there will be only one administrator for the database, I didnt see the need to make a table for users of the database interface. And so, I thought I'd pass the username & password entered by the admin in mysql_connect(); To secure the password in a session, how could I use md5 here, because what the admin enters is what directly goes into mysql_connect() function. And if i use md5, to store it in a session, i'd have to pass the actual unencrypted password in the function, which cannot be retrieved from the encrypted thing.

And since you say that saving password in a session is not advisable, could you suggest some other method using which I can retain the username and pass entered by the user, until he logs out.. because i'll need those everytime I use mysql_connect()..

This is what I did

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3.  
  4. if(isset($_POST['submit_uname']))
  5. {
  6.     $_SESSION['username']=$_POST['username'];
  7.     $_SESSION['pass']=$_POST['pass'];
  8. }
  9. ?>
  10. //
  11.  //after a few lines
  12. //
  13. $conn=mysql_connect('localhost', $_SESSION['username'], $_SESSION['pass']);    
And on the next page too, I use the same session variables to connect to the database.

Thanks :)
Hanaa.
Sep 18 '08 #5
hanaa
44
:) Will someone please tell me how the username and password entered by the user be retained over the next few pages.. I've detailed what I did in the post above.
Sep 19 '08 #6
pbmods
5,821 Expert 4TB
As long as you call session_start() at the top, the session variables will be available.

It's rather... unconventional to make the User's login credentials the same as the database login.

Generally, this is frowned upon because it makes not just your site but your data vulnerable if your credentials are compromised. You might not even notice you've been phished; someone could be hosting their own database from your SQL server (think identity theft database... but with YOUR name attached to the hosting contract!), and you'd never know until you opened up PHPMyAdmin!

Generally a better idea is to hard-code your SQL login info into the script and then store a separate set of credentials in the database... or just hard-coded into the script, if you prefer.
Sep 19 '08 #7
ifedi
60
To agree with the preceding post, the point is that you're attempting to make a mysql connection for each and every person who visits the site. This is most definitely not the best approach. Rather, a code section or a file (named e.g. "connections.php" could be created like so:

Expand|Select|Wrap|Line Numbers
  1. $user="siteuser";
  2. $password="opensesame";
  3. //shortly later
  4. $link = mysql_connect('localhost', $user, $password);
  5. //etc
  6.  
The real point of security now lies in defining limited privileges for 'siteuser' within mysql.
Of course, you could create a number of users for different site features, depending on the levels of privileges you wish to assign for these features.
Sep 20 '08 #8
hanaa
44
Generally a better idea is to hard-code your SQL login info into the script and then store a separate set of credentials in the database... or just hard-coded into the script, if you prefer.
Did you mean hard code it into the script, and use that to check against the user entry? That way, it'd be safe and not in a session.. Did I get that right?
Something like the following?
Expand|Select|Wrap|Line Numbers
  1. if(isset($_POST['submit']))
  2. {
  3.  if($_POST['id']=='username' && $_POST['pass']=='password')
  4.     { //log him in
  5.      mysql_connect('--', 'username', 'password');
  6.      //
  7.     }
  8.  else
  9.     { //dont log him in
  10.     }
  11. }
Or to hard code my login and make a table of users, and check the form entries with that in the table? ( I wanted to avoid that. lazy me) I am doing that with the front end users. I'm making an online test taker.
Just to clarify, the script that i posted earlier is part of a database interface, and is meant to be used only by one person (or so I assumed for convenience's sake). I did define limited and only necessary privileges to the user ('username'). On the whole, what I wanted to avoid was to make a table for the database interface users(there's only one). Which is why I decided to pass the form entries directly into mysql_connect(). So, its still a bad idea? even if I've granted only the necessary privileges (I'll hard code it now anyway, just asking.)
Bear with me this one time :)
Thanks,
Hanaa
Sep 20 '08 #9
pbmods
5,821 Expert 4TB
You could do it that way, though I'd be sure to make the website login/password different from your MySQL login/password.

It's generally a bad idea to design your security around what *should* happen; nobody's omniscient, and one just simply cannot predict what will happen if someone gets ahold of his MySQL credentials.

If you're only going to have one User working on this part of your app, it's perfectly acceptable to forego the traditional database-driven authentication model and simply hard-code the credentials you are looking for.

What I'd be a little more insistent upon, however, would be encapsulating your MySQL credentials so that an attacker would only be able to compromise your application, not your entire database.
Sep 20 '08 #10
hanaa
44
What I'd be a little more insistent upon, however, would be encapsulating your MySQL credentials so that an attacker would only be able to compromise your application, not your entire database.
Thanks a lot pbmods
Encapsulating the mysql credentials means?
Sep 21 '08 #11
coolsti
310 100+
I am not sure about the issue of one connection per page when there are many many users. I have not encountered this myself since my applications have been for a limited amount of simultaneous users (a company app).

If a user is not logged into the application already (see below), then the user is redirected to a log in page where he/she is requested to enter username and password. Submitting this will then do the usual code to see if the user is authorized. If so, then the user is logged in to the application for his/her session. When doing this, I create a large string composed of the user's IP address, a 16 character random string, the user's username, and an application specific string (since I have more than one application that the user can log in to on this server). This string is then saved in a Session variable, let us call it here $_SESSION['loginID']. I also save another variable, let us call it $_SESSION['loginstump'] which is composed of only the 16 character random key part of $_SESSION['loginID']. Note that the string does not contain the user's password.

When the user requests a page of the application, one of the first things that is done is to see if the user is logged in. This is done by checking to see if the $_SESSION['loginID'] is equal to $_SESSION['loginstump'] catenated with the user's username and IP address and application specific string. If so, the user is considered to be logged in, and can proceed with the page he/she requested. If not, then the user is redirected to the login page.

This is not totally secure against someone stealing the session. But at least there is some safeguard because I do a check here against the IP address. If someone steals the session but is coming from a different IP address, that user will not get the requested page.

I am open to any suggestions from others out there how to do this better, but this is how I do things. It requires a password only during the initial login, and will not require it again as long as the user does not a) time out, b) change computers or opens a completely new browser window.
Sep 21 '08 #12
pbmods
5,821 Expert 4TB
Thanks a lot pbmods
Encapsulating the mysql credentials means?
Keeping the MySQL credentials separate from the application credentials.
Sep 21 '08 #13
hanaa
44
Yes Okay... :) Thanks coolsti and pbmods.
Sep 22 '08 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: ndsoumah | last post by:
hi all How can I make a database connection available to all the pages in my application? I tried doing it with session but it doesn't seem to work. here's what a did: start_session();
1
by: Bina Desai | last post by:
I get the following error: Error Type: Microsoft VBScript runtime (0x800A01A8) Object required: '' /myweb4/authorised_user_page.asp, line 70 and line 70 of my code is: <% rsCheckUser1.Open...
8
by: Johannes A. Brunner | last post by:
Got a simple problem. I code some site and because Im a freak I made my own session-handling. When a user open up my site it will check if there is a ssid in the url if not generate one. this will...
10
by: Brian Conway | last post by:
I have no idea what is going on. I have a Login screen where someone types in their login information and this populates a datagrid based off of the login. Works great in debug and test through...
1
by: Esteban Felipe | last post by:
Hi, thanks for reading. I hope to find some help here before I commit suicide because this is driving me crazy. Please excuse me if this looks like a long post, but I hope that a complete...
3
by: Grigs | last post by:
Hello, I have a web service that reads its web.config file to connect to an Oracle database. There are a number of methods in this socalled BACKBONE that either send inforomation to or from the...
3
by: Andy G | last post by:
I have some code that hits a DB2 database from my ASP.NET application. I haven't been able to exactly nail it down but my connections are not getting closed for some reason. I look at the...
11
by: Madison Kelly | last post by:
Hi all, I am new to the list and I didn't want to seem rude at all so I wanted to ask if this was okay first. I have a program I have written in perl which uses a postgresSQL database as the...
1
by: sbettadpur | last post by:
hi everybody, l have one doubt, please clarify that if anybody knows. Can i able to take database connection across the page through session variable, without initializing connection on every...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.