1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Problem with login form

Discussion in 'PHP' started by ViggoAvatar, Dec 12, 2015.

  1. #1
    <div id="cd-login"> <!-- log in form -->
                <form class="cd-form" action="login.php" method="post">
                    <p class="fieldset">
                        <label class="image-replace cd-username" for="log_username">Login</label>
                        <input class="full-width has-padding has-border" id="username" name="username" type="text" placeholder="Username">
                        <span class="cd-error-message">Please enter a username!</span>
                    </p>
    
                    <p class="fieldset">
                        <label class="image-replace cd-password" for="log_password">Password</label>
                        <input class="full-width has-padding has-border" id="log_password" name="password" type="password"  placeholder="Password">
                        <span class="cd-error-message">Please enter a password!</span>
                    </p>
    
                    <p class="fieldset">
                        <input type="checkbox" id="remember-me" checked>
                        <label for="remember-me">Remember me</label>
                    </p>
    
                    <!--p class="fieldset"-->
                        <input class="full-width" id="submitBtn" type="submit" value="Login">
                    <!--/p-->
                </form>
    
                <p class="cd-form-bottom-message"><a href="#0">Forgot your password?</a></p>
                <!-- <a href="#0" class="cd-close-form">Close</a> -->
    HTML:
    <?php
    session_start(); // Starting Session
    $error=''; // Variable To Store Error Message
    if (isset($_POST['submit'])) {
    if (empty($_POST['username']) || empty($_POST['password'])) {
    $error = "Username or Password is invalid";
    }
    else
    {
    // Define $username and $password
    $username=$_POST['username'];
    $password=$_POST['password'];
    // Establishing Connection with Server by passing server_name, user_id and password as a parameter
    $connection = mysql_connect("mysql.hostinger.nl", "u470788761_viggo", "<password>);
    // To protect MySQL injection for Security purpose
    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);
    // Selecting Database
    $db = mysql_select_db("USERTBL", $connection);
    // SQL query to fetch information of registerd users and finds user match.
    $query = mysql_query("select * from login where password='$password' AND username='$username'", $connection);
    $rows = mysql_num_rows($query);
    if ($rows == 1) {
    $_SESSION['username']=$username; // Initializing Session
    header("location:/lol.php"); // Redirecting To Other Page
    } else {
    $error = "Username or Password is invalid";
    }
    mysql_close($connection); // Closing Connection
    }
    }
    ?>
    PHP:
    it doesnt work, at this point i dont know why it doesnt...
    in the MySQL table the column is called USERNAME/PASSWORD is it case sensitive or is there something wrong with the entire code?
     
    Solved! View solution.
    ViggoAvatar, Dec 12, 2015 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Since the case-sensitivity of SQL depends on the operating system, it's NEVER a good idea to use upper case in naming tables or databases. Always use lower case and underscores for spaces. Also, the normal convention is to use upper case for the statement. So your select statement would be:
    SELECT * FROM login WHERE password = '$password' AND username = '$username'
    Although using mysql_ is really not recommended. It's deprecated, and with the new PHP version, 7, no longer part of the PHP code. It's recommended using the object version of either mysqli_ or PDO.
     
    PoPSiCLe, Dec 12, 2015 IP
  3. #3
    I'd also be asking what in blazes makes labels and inputs be grammatical paragraphs.... much less the colossal joke of them having the class "fieldset" when there's a perfectly good fieldset tag -- though generally speaking I'd have that all as ONE fieldset and lose the stupid wrapping DIV since it's unlikely you're doing a blasted thing to that DIV you couldn't do to FORM or a proper <fieldset>!

    Of course you've got placeholders AND labels; that's pretty jacktarded too... hardcoded error messages, bet that makes tons of sense on non-CSS UA's.

    ... and yeah that decade out of date train wreck of mysql_ functions and broken insecure methodologies is just BEGGING for it to fail. HARD... much less not even bothering to hash your passwords... and the ridiculous comments. session_start starts the session? WHO KNEW?!?

    I'd probably also be axing the variables for nothing, making $errors an array so you can store SPECIFIC messages, more than one if need be...

    So "properly" that would be something more like this on the PHP side:
    <?php
    session_start();
    session_regenerate_id(); // reduces window for MitM attacks
    
    // WARNING, I'm using PHP 5.4/newer arrays and code
    
    $errorMessages = [];
    $errorChecks = [
    	'submit' => 'Error, this did not come from the login form',
    	'username' => 'You must provide a username',
    	'password' => 'You must provide a password'
    ];
    
    foreach ($errorChecks as $index => $message) {
    	if (!array_key_exists($index, $_POST)) $errorMessages[$index] = $message;
    }
    
    if (count($errorMessages) == 0) {
    
    	try {
    		$db = new PDO(
    			'mysql:host=mysql.hostinger.nl;dbname=usertbl',
    			'u470788761_viggo',
    			'password'
    		);
    	} catch (PDOException $e) {
    		die('Connection failed: ' . $e->getMessage);
    		// you may wish to consider a more robust handler here.
    	}
    	
    	// never, EVER pull the password FROM the DB. Keep that monodirectional!
    	$statement = $db->prepare('
    		SELECT id
    		FROM login
    		WHERE username = :username
    		AND password = :password
    	');
    	
    	/*
    		prepare + excecute autosanitizes for you, killing off half your codes
    		pointless bloat and redundancies
    	*/
    	$statement->execute([
    		':username' => $_POST['username'],
    		':password' => hash('sha256', $_POST['password'])
    	]);
    	
    	if ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
    	
    		/* 
    			I don't trust names, store the numeric ID. It's usually WAY faster to
    			use for querying extra data in other tables anyways. Many places have
    			the login name and display name be different for good reason too!
    		*/ 
    		$_SESSION['userId'] = $row['id'];
    		/*
    			I would NOT be redirecting here, that's an indication of sloppy
    			security handling, spaghetti code, and worst of all possible multiple
    			entry vectors! One index to rule them all FTMFW
    		*/
    		} else {
    			$errorMessages['login'] = 'Username or Password is invalid';
    			 // set invalid index to make SURE they're not logged in
    			$_SESSION['userId'] = -1;
    		}
    		
    		$db = null; // this is how you disconnect from PDO
    		
    	}
    	
    }
    
    // if (count($errorMessages)) at this point, include the login form again
    // otherwise proceed as they're logged in.
    Code (markup):
    Whilst that form... oh hey, in rewriting your form I found the problem. You don't have name="submit" on the submit, though you're checking for it in your PHP. Yeah, that's an easy one to miss. In any case:

    <form id="login" action="login.php" method="post">
    	<fieldset>
    		<label for="login_name">Login</label>
    		<input type="text" id="login_name" name="username">
    		<br>
        <label for="login_pass">Password</label>
    		<input type="password" id="login_pass" name="password">
    		<br>
    		<input type="checkbox" id="login_remember" name="remember" value="1" checked>
    		<label for="login_remember" class="forCheckbox">Remember me</label>
    	</fieldset>
    	<div class="submitsAndHiddens">
    		<input type="submit" name="submit" value="Login">
    		<a href="#0">Forgot your password?</a>
    	</div>
    </form>
    Code (markup):
    Would be a "well formed" form using the tags for what they mean and how they're SUPPOSED to be used.

    Hope this helps. Looks like you've been learning from some disastrously out of date sources -- it happens, more so now that PHP 7 is trying to tell all that outdated junk to go plow itself.
     
    deathshadow, Dec 13, 2015 IP
  4. ViggoAvatar

    ViggoAvatar Peon

    Messages:
    21
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #4
    It helped, and worked quite good, the problem was: the style was completely gone, i had CSS, and i tried putting back some style tags, it broke everything though ^^, some help here?
     
    ViggoAvatar, Dec 14, 2015 IP
  5. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #5
    First, you didn't show what you had for style, so there was no way for that. Different HTML needs different CSS.

    Second, and more important -- if you are adding tags for style, you're probably doing something wrong. HTML should be based on what things ARE, and NOT what you want them to look like. That markup I provided has MORE than enough hooks to target from the external stylesheet. (unless you're relying on one of those dumbass halfwit bloated steaming piles of manure known as "frameworks", in which case toss the entire site in the trash and start over)

    If you give me an idea what you are trying to do for layout and style, I can probably toss together some CSS to style it so.
     
    deathshadow, Dec 14, 2015 IP