0

So i've decided to start looking into coding again since I gave up on it for a while, I've been attempting to create a PHP Login system for my website. And everytime I attempt to login I get a connection error stating "Failed To Connect" by using the or die function to test if there are, issues. Which normally I always find to be the case sadly. I had a look around at a few other questions/people who had similar issues. But sadly I can't seem to identify a problem nor find a solution from doing so. I've looked over at my script and there doesn't seem to be any issues. My best guess is its due to my MySQL Database. But honestly, i'm truly unsure. If any of you could give me some advise on what to do it'd be great. Thanks,

To mention also I looked around on the PHP website to have a look if there were any possible functions I could add to identify the issue but I was unable to. Im not sure if it's a stupid question to ask but is there a way to do this apart from just using die/exit? I also tried doing imgs.beastfox.net Which is where the location of all the files are located. Hope I gave you all the information needed. If you need any other details I hope I can help out. I will note again I have searched high and low for other articles that might help but I can't seem to figure out my problem. Another thing to note is I am hosting my website by Namecheap if that's any concern.

Thanks, David

--Website--

imgs.beastfox.net/php/login.php

Email:test@test.com

Password:test

--Code--

<?php
    session_start();

    if(isset($_SESSION["id"]) || isset($_COOKIE["id"]))
    {
        header("Location: dashboard.php");
    }

    if(isset($_POST["login"]))
    {
        //Gather input variables
        $email = $_POST["email"];
        $password = $_POST["password"];
        //Hash password as pasword should be hashed in database for security reasons.  See md5 hashing
        $hash_password = md5($password);
        $remember_me = $_POST["remember_me"];




        //Connect to Database
$host="beastfox.net";      
$username="{username}"; 
$password="{password}"; 
$db_name="{username}_login"; 
$tbl_name="login"; 

$con = mysqli_connect("beastfox.net","{username}","{password}","{username}_login","login")or die("cannot connect"); 




        //Check database to see if email registered to DB
        $sql = "SELECT id FROM users WHERE email='$email' LIMIT 1";
        $query = mysqli_query($con, $sql);
        $count_users = mysqli_num_rows($query);

        if($count_users == 1)
        {

            //Retrieve user details to perform login
            $sql = "SELECT * FROM users WHERE email='$email' LIMIT 1";
            $query = mysqli_query($con, $sql);
            while($row = mysqli_fetch_array($query))
            {
                $user_id = $row["id"];
                $user_password = $row["password"];

            }


            if($hash_password == $user_password)
            {
                if($remember_me == 1)
                {
                    //Set Cookie
                    $cookie_name = "id";
                    setcookie($cookie_name, $user_id, time() + (86400 * 30), "/");

                    header("Location: dashboard.php");
                }
                else
                {
                    //Set Session
                    $_SESSION["id"] = $user_id;
                    header("Location: dashboard.php");
                }
            }
            else
            {
                $error = '<p class="error">Password incorrect.</p>';
            }
        }
        else
        {
            $error = '<p class="error">Email address not registered.</p>';
        }

        mysqli_close($con); 
?>
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no'/>
    <title>User Login</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700,900" rel="stylesheet">

    <style type="text/css" media="screen">
        *{
            padding: 0;
            margin: 0;
            box-sizing: border-box;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            font-family: 'Roboto', sans-serif;
        }
        body, html{
            width: 100%;
            height: 100%;
        }

        body{
            position: relative;
            background: #2196f3; /* Old browsers */
            background: -moz-linear-gradient(top, #2196f3 0%, #1e88e5 40%, #1565c0 100%); /* FF3.6-15 */
            background: -webkit-linear-gradient(top, #2196f3 0%,#1e88e5 40%,#1565c0 100%); /* Chrome10-25,Safari5.1-6 */
            background: linear-gradient(to bottom, #2196f3 0%,#1e88e5 40%,#1565c0 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
            filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#2196f3', endColorstr='#1565c0',GradientType=0 ); /* IE6-9 */
            copy

        }

        label{
            display: block;

        }



        form{
            position: absolute;
            top:50%;
            left: 50%;
            transform: translate(-50%,-50%);
            width: 40%;
            padding: 30px;
            background: #FFF;
            -moz-box-shadow: 0 1px 2px 0 rgba(0,0,0,0.15);
            -webkit-box-shadow: 0 1px 2px 0 rgba(0,0,0,0.15);
            box-shadow: 0 1px 2px 0 rgba(0,0,0,0.15);
            border-radius: 5px;
        }

        .css-input {
             padding: 7px 10px;
             font-size: 15px;
             border-width: 1px;
             border-color: #CCCCCC;
             background-color: #FFFFFF;
             color: #455A64;
             width: 100%;
             border-style: solid;
             border-radius: 0px;
             box-shadow: inset 0px 0px 4px rgba(66,66,66,.14);
        }
         .css-input:focus {
             outline:none;
        }

        form p{
            display: block;
            margin-bottom: 20px;
        }

        .clear{
            clear: both;
        }

        .btn {
          background: #3498db;
          background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
          background-image: -moz-linear-gradient(top, #3498db, #2980b9);
          background-image: -ms-linear-gradient(top, #3498db, #2980b9);
          background-image: -o-linear-gradient(top, #3498db, #2980b9);
          background-image: linear-gradient(to bottom, #3498db, #2980b9);
          -webkit-border-radius: 8;
          -moz-border-radius: 8;
          border-radius: 8px;
          text-shadow: 1px 1px 3px #666666;
          font-family: Arial;
          color: #ffffff;
          font-size: 17px;
          padding: 10px 25px 10px 25px;
          border: solid #1f628d 1px;
          text-decoration: none;
          margin-top: 20px;
          cursor: pointer;
        }

        .btn:hover {
          background: #3cb0fd;
          background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
          background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
          background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
          background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
          background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
          text-decoration: none;
        }

        h1{
            color: #455A64;
            font-size: 22px;
            line-height: 22px;
            padding-bottom: 10px;
            border-bottom:1px solid #e9e9e9;
            margin-bottom: 20px;
        }

        label{
            display: block;
            padding-bottom: 10px;
            color: #546E7A;
        }

        label.remember{
            display: inline-block;
            line-height: 20px;
            cursor: pointer;
        }

        label.remember input{
            float: left;
            margin-top: 5px;
        }

        label.remember span{
            font-size: 14px;
            color: #1194EA;
            text-decoration: underline;
            padding-left: 6px;
        }

        p.error{
            padding-bottom: 0;
            margin-bottom: 0;
            color: #F44336;
            padding-top: 15px;
        }
    </style>


    </head>
    <body>

        <form method="post" action="login.php">
            <h1>Login to Dashboard</h1>
            <p>
                <label for="email">User Email</label>
                <input type="email" name="email" required="required" id="email" class="css-input" placeholder="Enter Email Address"/>
            </p>


            <p>
                <label for="password">Password</label>
                <input type="password" name="password" required="required" class="css-input" id="password" placeholder="Enter Password"/>
            </p>

            <label for="remember_me" class="remember">
                <input type="checkbox" name="remember_me" id="remember_me" value="1"/>
                <span>Remember Me</span>
            </label>

            <div class="clear"></div>

            <button type="submit" name="login" class="btn">Login</button>

            <?= $error; ?>
        </form>
    </body>
</html>

MySQL Database (Dont know if this helps at all)

Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
  • 4
    **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/master/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords with a weak, high-speed hash like SHA1 or MD5**. – tadman Jan 06 '18 at 23:43
  • 3
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Jan 06 '18 at 23:43
  • 3
    Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Jan 06 '18 at 23:43
  • @tadman Hi there, thanks for your reply. From what I was told before I should has my password with MD5? But I will make sure to change it immediately. But I am still very confused on what exactly I should do? are you asking me to remove what I currently have about the "or die" function and replace it with echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; }" as well as to remove $_POST, $_GET? And i am entirely confused about what you are trying to explain to me in your third note. Sorry for the lack of knowledge, Thanks –  Jan 06 '18 at 23:49
  • 4
    Please update your question with the connect error. Change your the `or die("cannot connect")` to `die("cannot connect: " . mysqli_connect_error());` – Will B. Jan 06 '18 at 23:50
  • 5
    If you were told MD5 you were told something wrong. It's useless for passwords because it's trivial to crack. Like I said, writing a login system is really hard, it's not for someone who just wants to learn programming. Find a framework you like the look of, then work through the introductory material to understand how to use the login system it provides. Then you can focus on doing new things instead of wasting your time badly re-inventing the wheel. – tadman Jan 06 '18 at 23:51
  • 2
    A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so mistakes aren't easily ignored. – tadman Jan 06 '18 at 23:51
  • 2
    MD5 is not cryptographically secure you should use the [built in php functions](http://php.net/manual/en/faq.passwords.php) `password_hash` instead – Will B. Jan 06 '18 at 23:52
  • Thanks for all of your replies, @fyrye In addition to what I already had I added the " . mysqli_connect_error()); to my script and funnily enough this returned. https://imgs.beastfox.net/ahpqhUEtsI.png –  Jan 06 '18 at 23:55
  • Also @tadman thank you for your response I'll make sure to change it now. Do you recommend any frameworks/would suggest any frameworks to start off with? I understand completely well that making a login system is challenging and well I'd like to try my hardest at making one at least. Thanks a lot, David –  Jan 06 '18 at 23:56
  • Your `mysqli_connect` has more arguments than it should – Douglas Santos Jan 07 '18 at 00:23
  • The problem with making a login system is making it secure. A badly implemented one does the opposite: It provides places for people to attack you. Unless you're familiar with the [basics of various attack vectors](https://www.owasp.org/index.php/OWASP_Cheat_Sheet_Series) you're going to be heading into this absolutely blind. This is why using a framework like [Laravel](http://laravel.com) which [already has this built-in](https://laravel.com/docs/master/authentication) is a good place to start. Study how that works, *then* consider making your own for academic reaasons. – tadman Jan 07 '18 at 00:42
  • Approach this like you would when trying to find a lock for the front door of your home. Don't look up YouTube totorials on "how to make lock" and hammer together something out of scraps of metal. Buy a professionally made one and install it according to their specifications. – tadman Jan 07 '18 at 00:44

1 Answers1

4

If you turn on error reporting you can validate the error message.

Add the following to the top of your php script.

<?php 

ini_set('error_reporting' -1);
ini_set('display_errors', 'on');

//...

Result:

Warning: mysqli_connect() expects parameter 5 to be long, string given

The reason you do not receive a mysqli_connect_error message, is that the arguments you supplied to mysqli_connect are invalid. See the manual.

mysqli_connect($host, $username, $password, $database_name, $port, $socket);
Will B.
  • 17,883
  • 4
  • 67
  • 69