MySQL Functions Do Not Work - php

Thanks For Answers!
I got lots of feedback and I have an answer and I fixed it. Thanks!
I am working on making a user login system for my website. I want the updates to be faster so I moved the exact files to my local server, (Apache/2.2.22 (Ubuntu)), and it suddenly does not work. The Database is external so it does not need the hostname changed. Any ideas? I get no errors, it just does not parse the MySQL bit.
Connect File:
<?php
$host = "xxxxxxx.xxxxxxxxx.xx.xx";
$user = "sh0u_xxxxxx";
$pass = "xxxxx";
$db = "sh0u_1xxxxx_store";
mysql_connect($host,$user,$pass) or die("Unable To Connect To Database");
mysql_select_db($db)
?>
Login File:
<?php
session_start();
session_destroy();
include('connect.php');
$email = $_POST['email'];
$pass = md5($_POST['password']);
$query = mysql_query("SELECT * FROM users WHERE email='".$email."' AND password='".$pass."'");
$numrows = mysql_num_rows($query);
if($numrows === 1) {
session_start();
$_SESSION['sid'] = "".$email.":".$pass."";
header('Location:../index.php');
}else {
include('../login.php');
echo "<script>alert('Incorrect Username and/or Password');</script>";
}
?>

Most hosting providers do not allow external access to the databases they include with their plans. Not only that, most of them use localhost as a database server so as to force a socket connection (so that they can even disable network connections to their DBs altogether).
To test your script and site locally you will need to download a dump of your database and create a local version of it on your own.
Other issues with your code
As mentioned in comments you are:
You should be using the MySQL Improved Extension, instead of the old (and deprecated) MySQL extension
You are not sanitizing data you use for your queries (use prepared statements)
MD5 is not secure for passwords, you should be using the new password_hash instead

Related

What is servername

i just wanted to insert data into database from a form, with php. i ran the code below in my Localhost using XAMPP and everything was fine but where i upload it to my host it didn't work.
Question is What shold i put for $servername and when should i look for it ?
There is my codes:
Register.php (in localhost)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$Name = $_POST['Name'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header("Location:#");
}
//Inserting Data
try{
$sql = "INSERT INTO User (uName , uUsername , uPassword , uEmail) VALUES ('$Name' , '$Username' , '$Password' , '$Email')";
mysqli_query($conn, $sql);
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$conn->close();
header("Location:#");
}
?>
If your MySQL database is on the SAME SERVER as your PHP script, then the usual logical approach is that your host is localhost. The same as you used on your local computer -- because they're on the same machine.
However, if your MySQL database is on ANOTHER SERVER seperate from your PHP scripts the you will need to access that server using a web address for your PHP to connect to yout MySQL.
We can't tell you what that is, and your server hosts (of your MySQL server) will be able to tell you and provide you with the correct login credentials.
I believe it would be more usual for MySQL and PHP to be on the same disk, especially for non-professional systems as your appears to be, so then the issue would be:
Are your login details set up correcty on your server? (same username/password)
Are there any MySQL errors or PDO errors (if you connect with PDO). Don't redirect on error, but instead output the error to a log file so you can read WHY the MySQL in your code didn't connect.
It is still possible for you to set your PHP to communicate with your localhost MySQL via a remote address (such as servername=$_SERVER['SERVER_NAME'];). (see note below)
Many online accounts (in things such as CPanel) will block you from accessing the MySQL as a root or at least will not give you the root MySQL password. Using root to access MySQL via PHP is NOT a good idea and you should instead set up a specific MySQL user for your PHP with only enough privileges that you need to read/write to the DB, and nothing more.
If your MySQL is remote (not localhost) then you may also need to supply a Port Number with the connection details. Usual port numbers are 3306 but this is something you'd need to know from your server hosts.
Immediately after a header(Location:); redirection instruction you should always set die(); or exit to stop PHP processing the rest of the script.
Your SQL insert data is highly suseptible to SQL injection and other SQL attacks and compromise. You should really, REALLY look into using MySQL Prepared Statements, you're already coding in OO style so you're almost there already.
Example remote connection from the manual
<?php
/***
* Remember 3306 is only the default port number, and it could be
* anything. Check with your server hosts.
***/
$conn = new mysqli('remote.addr.org.uk', 'username', 'my_password', 'my_databasa', '3306');
/***
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
***/
if ($conn->connect_error) {
error_log('MySQL Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
/***
* Upon failure, the above will output a connection error notice such as
* user not found or password incorrect. It won't explicity say these
* things but you should be able to deduce which from the notice
***/
echo "Success... \n" . $conn->host_info ;
$mysqli->close();
# : I seem to think that MySQL detects when the remote address given is the same as the server address and auto converts it to localhost, but I'm not sure on this.
The long and the short of it is that if your MySQL is on the same
server as your PHP it makes no sense to open up a network loop to send
data out just to get it back again. Use localhost instead.
I asked my host service providers about the "$servername" and they answered me that the "$serverneme" is localhost.

PHP MySQL Security Improvements UPDATED

I want to send form data to a server online.
At the moment i'm using xampp so the username and password are 'root' and ''
If I was to put this online I would have to put my hosting login details. Is that correct?
Clearly that would be a very serious security issue as anybody could see it written in my process file.
I have found a lot of info about prepared statements to prevent SQL injection but nothing about how to hide username/password, which I would have thought would be a bigger thing.
Am I missing something essential about usernames/passwords?
(I am not trying to create user login accounts, just basic newsletter signup)
<?
// database details
$servername = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database';
// form submission
$email=$_POST['email'];
// connect to database
mysql_connect($servername, $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
mysql_query("INSERT INTO newsletter VALUES ('$email')");
Print "Your information has been successfully added to the database.";
mysql_close();
?>
Update:
Ok, so I have since included prepared statements into my code, and it now looks like this:
<?php
// database details
$servername = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database';
// form submission
$email=$_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO scenariosubmission (Email) VALUES (?)");
$stmt->bind_param("s", $email);
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
My code should prevent SQL injection
So what I want to know is if I was to enter my username password database and upload this to the server, would those details be safe if I uploaded them like any other web page to public_html?
So when you move this to your hosting, the code will be something like this:
<?
// database details
$servername = 'localhost';
$username = 'your userid with your hosting company';
$password = 'hosting company provided mysql password';
$database = '';
Will that be a big security issue of everyone being able to see your MySQL password?
Not really, because only you and the people working for the hosting company should be able to see the PHP code. And the people working at the hosting company will have the root password to the database anyway, so they could look at what you have in the database without your particular mysql credentials.
But using <? rather than <?php may cause your code to be transmitted instead of run on some server setups. So if you upload it that way, initially some users may end up seeing the passwords you have in the code before you figure it out and fix it.
Another more serious issue than this is if the hosting company has you using phpmyadmin over http rather than https, because every time you login to it your credentials will be transmitted in plain text.
Well there a couple of things in play here.
Since you mentioned SQLi and considering you're using PHP + MySQL, you should look into doing prepared statements, by using the prepare(), bind() and execute() functions.
Second, even before thinking about putting something online or using SQL properly is to change the default username/password.
Now if you want to put your server online, I'm assuming you have a server or the credentials to someplace where you can ran either XAMP or configure its services by hand. Anyway, those credentials are the Database's, which are different from your host server login credentials.
As long as that .php file is properly secured on the server, it's common practice to have the username/password there in the file.

Connecting to database via php code

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).

My login scripts working fine on localserver but it not working on live server

I am using my admin panel login script where i have created a global.php file with code including this:-
<?php
$Global['host']="localhost";
$Global['username']="username";
$Global['password']="*******";
$Global['database']="database_name";
$Global['baseurl']='www.somesite.com/work/';
$connhandle=mysql_connect($Global['host'],$Global['username'],$Global['password'])or die('can\'t establish connection with mysql database');
$dbSelect=mysql_select_db($Global['database'],$connhandle) or die('could not connect to the database');
?>
and for calling the script on clock i m using a redirect.php file which include code as follows:-
<?php
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['password'] = $_POST['pass'];
$_SESSION['aid'] = 0;
include 'global.php';
$admin_themes=mysql_fetch_object(mysql_query("select * from admin where id='1'"));
$ruser = $admin_themes->username;
$rpass = $admin_themes->password;
if ($_SESSION['username'] == $ruser && $_SESSION['password'] == $rpass) {
$_SESSION['aid'] = 1;
header("location:../index.php");
}
else {
header("location:../admin_login.php?passcheck");
}
?>
no this scripts in working absolutely fine when i run this using my xampp server on local. but when i upload it to my online server the redirect script show me this error:-
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'username'#'localhost' (using password: YES) in /home/..../public_html/work/h_cms/configuration/global.php on line 9
can't establish connection with mysql database
any suggestion why its not showing on online server i have used the correct username and pass of my database i have checked it 5 times. But still not find where is the problem.
username#localhost is clearly not the correct username based on the error message. if you're subscribing to a hosting provider, you may want to check with them the correct username for your mysql account.
also, you might want to try using your domain name instead of localhost.
Your database username, password or hostname is not correct. You need to check what the correct details are and update your code accordingly.
Be aware afterwards you might need to create the necessary database and tables again so your app can run.

Cannot connect to my hosting service's MySql database. NB

I am EXTREMELY new to the html/php scene but I have been working at this for hours. I am stumped.
I am trying to connect to a sql database that will store username and password information. I use fortune city for hosting and I have already used their phpAdmin to setup up all of the necessary stuff (db, tables, etc..).
I am using Eclipse with Zend on the side. I am also running Sql Server and Apache 2.2.
I believe my issue is the following:
I have a db located at a certain ip address (remote fortunecity server) and I am testing my project on the local server. Fortune city offers two different host names, one for internal connections and one for external connections. I get different results from each one:
If I connect to the internal site it doesn't make any connection, I know this because of my die statement. If I connect to the external host it connects, but doesn't allow me to connect to the database. (see cases below code)
Currently my process is as follows. (PLEASSSSE TELL ME A BETTER WAY IF I'M DOING THINGS THE INEFFICIENTLY, I feel dirty every time I do it!!)
Create or edit my index.php, login.php, etc... in eclipse.
Copy the files that I edit into my Apache root.
Go back to eclipse and run the project in a browser "firefox."
repeat n to the n times.
Keep in mind my sql database is located on the net
Can this be done? Testing locally while accessing a db on the net?
Here is the code:
<?php
if (!isset($_POST['username']) || !isset($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
elseif (empty($_POST['username']) || empty($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
else{
$user = addslashes($_POST['username']);
$pass = md5($_POST['password']);
$dbHost = "mysql3341.dotsterhost.com";
$dbUser = "*********";
$dbPass = "******";
$dbDatabase = "**********";
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
$result=mysql_query("select * from userInfo where username='$user' AND password='$pass'", $db);
$rowCheck = mysql_num_rows($result);
if($rowCheck > 0){
while($row = mysql_fetch_array($result)){
session_start();
session_register('username');
echo 'Success!';
header( "Location: checkLogin.php" );
}
}
else {
echo 'Incorrect login name or password. Please try again.';
}
}
?>
Again, I have never made it past
Case :1 $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
Case :2 mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
Thanks for reading my novel!
Can this be done? Testing locally while accessing a db on the net?
Yes you can, but be aware if you are storing anything sensitive in your database you probably wouldn't want to be sending that data unencrypted over the net. (Unless you are connecting over a VPN or another type of secure network connection.)
Usually you'd want to setup a development environment on your local box or you can edit your files locally in something like Aptana (http://www.aptana.com/) and have it automatically deploy your files to the server every time you save.
Also, as suggested in the comments, using a framework to develop on usually give you a powerful database library without the need to reinvent it on your own. (That is unless you feel like wrapping your own!)

Categories