Things About Web Design Logo

Things About Web Design

PHP CSS MySQL JS Scripts & Tutorials

MySQL Snippets


.

MySQL Database Connect

MySQL / PHP code below can be called into any page from a directory on your server using something like <?php require_once("db/connect.php"); ?>:

4


<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER''db.host.com');
define('DB_USERNAME''dbuser');
define('DB_PASSWORD''dbpassword');
define('DB_NAME''db_name');
 
/* Attempt to connect to MySQL database */
$link mysqli_connect(DB_SERVERDB_USERNAMEDB_PASSWORDDB_NAME);
 
// Check connection
if($link === false){
    die(
"ERROR: Could not connect. " mysqli_connect_error());
}
?>
.

Top Of Home Page

MySQL / PHP code below goes at top of home page. Before <!DOCTYPE html> For example in "index.php":

3


<?PHP
  
if($_POST && "all required variables are present") {
    
session_start();
    if(
$user && password_verify($password$user['password'])){
     
$_SESSION['id'] = $user['id'];
}
    if(
$_POST['captcha'] != $_SESSION['digit']) {
// If the user is not authenticated, send
// a Location header to redirect the browser to index.php
header("Location: index.php?msg");
// Stop rendering the rest of the page
die();
}
    
session_destroy();
  }
?>
<?php
// Include MySQL connect file
require_once "db/conect.php";
// Define variables and initialize with empty values
$username $password "";
$username_err $password_err "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    
// Check if username is empty
    
if(empty(trim(mysqli_real_escape_string($link$_POST["username"])))){
        
$username_err "Please enter username.";
    } else{
        
$username trim(mysqli_real_escape_string($link$_POST["username"]));
    }
    
    
// Check if password is empty
    
if(empty(trim(mysqli_real_escape_string($link$_POST["password"])))){
        
$password_err "Please enter your password.";
    } else{
        
$password trim(mysqli_real_escape_string($link$_POST["password"]));
    }
    
    
// Validate credentials
    
if(empty($username_err) && empty($password_err)){
        
// Prepare a select statement
        
$sql "SELECT id, username, password FROM users WHERE username = ?";
        
        if(
$stmt mysqli_prepare($link$sql)){
            
// Bind variables to the prepared statement as parameters
            
mysqli_stmt_bind_param($stmt"s"$param_username);
            
            
// Set parameters
            
$param_username $username;
            
            
// Attempt to execute the prepared statement
            
if(mysqli_stmt_execute($stmt)){
                
// Store result
                
mysqli_stmt_store_result($stmt);
                
                
// Check if username exists, if yes then verify password
                
if(mysqli_stmt_num_rows($stmt) == 1){                    
                    
// Bind result variables
                    
mysqli_stmt_bind_result($stmt$id$username$hashed_password);
                    if(
mysqli_stmt_fetch($stmt)){
                        if(
password_verify($password$hashed_password)){
                            
// Password is correct, so start a new session
                            
session_start();
                            
                            
// Store data in session variables
                            
$_SESSION["loggedin"] = true;
                            
$_SESSION["id"] = $id;
                            
$_SESSION["username"] = $username;
                            
$_SESSION["digit"] = $digit;                          
                            
                            
// Redirect user to welcome page
                           
header("location: $username/index.php");
                        } else{
                            
// Display an error message if password is not valid
                            
$password_err "The password you entered was not valid.";
                        }
                    }
                } else{
                    
// Display an error message if username doesn't exist
                    
$username_err "No account found with that username.";
                }
            } else{
                echo 
"Oops! Something went wrong. Please try again later.";
            }
        }
        
        
// Close statement
        
mysqli_stmt_close($stmt);
    }
    
    
// Close connection
    
mysqli_close($link);
}
?>
.

Home Page Login Form

PHP code below goes in <body> of home page for example in "index.php":

2


<h2>Login</h2>
        <p>Please fill in your credentials to login.</p>
<?php
if(isset($_GET['msg']))
    {
        
$Message "<i><b>Sorry, the CAPTCHA code entered was incorrect!</b></i>";
        echo 
$Message;
    }
?>        
<?php
session_start
();      
if(isset(
$_SESSION['success'])){
  echo 
$_SESSION['success'];
 unset(
$_SESSION['success']);//so you do not have to display it over and over again
session_destroy();  
}
?>
        <form action="<?php echo stripslashes(strip_tags(htmlspecialchars($_SERVER["PHP_SELF"]))); ?>" method="post">
            <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' ''?>">
                <label>Username</label>
                <input type="text" name="username" onpaste="return false" class="form-control" value="<?php echo stripslashes(strip_tags(htmlspecialchars($username))); ?>" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" maxlength="8" autocomplete="off" autofocus required>
                <span class="help-block"><?php echo $username_err?></span>
            </div>    
            <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' ''?>">
                <label>Password</label>
                <input type="password" name="password" id="myInput" onpaste="return false" class="form-control" value="<?php echo stripslashes(strip_tags(htmlspecialchars($password))); ?>" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" maxlength="13" autocomplete="off" required>
                <span class="help-block"><?php echo $password_err?></span>
                 &nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" onclick="myFunction()"> Show Password
            </div>
            <div class="form-group">
               <img src="captcha.php?rand=<?php echo rand(); ?>" width="120" height="30" border="1" id="captchaimg" alt="CAPTCHA"> Enter the code: <input type="text" id="captcha" size="7" maxlength="6" name="captcha" value="" autocomplete="off"><br><br>
                 <small>Can't read the image? <a href='javascript: refreshCaptcha();'><b>Get New Code </b></a></small>
                   &nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Login">
            </div>
            <?php //echo "<p>Don't have an account? <a href='register-mail.php'>Sign up now</a>.</p>
          //<p>Forgot Password? <a href='password-recovery/index.php'>Click here</a>.</p>" 
?>
        </form>      
<script>
function myFunction() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
  </script>
<script>
  function checkForm(form)
  {
    if(!form.captcha.value.match(/^\d{6}$/)) {
      alert('Please enter the CAPTCHA digits in the box provided');
      form.captcha.focus();
      return false;
    }
    return true;
  }
</script> 
<script>
function refreshCaptcha()
{
    var img = document.images['captchaimg'];
    img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>  
.

Captcha-Code

PHP code below goes in "captcha.php":

1


<?php 
/*
*
* this code is based on captcha code by Simon Jarvis 
* http://www.white-hat-web-design.co.uk/articles/php-captcha.php
*
* This program is free software; you can redistribute it and/or 
* modify it under the terms of the GNU General Public License 
* as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, 
* but WITHOUT ANY WARRANTY; without even the implied warranty of 
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
* GNU General Public License for more details: 
* http://www.gnu.org/licenses/gpl.html
*/

session_start();
//Settings: You can customize the captcha here
$image_width 120;
$image_height 40;
$characters_on_image 6;
$font 'fonts/monofont.ttf';

//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters '23456789bcdfghjkmnpqrstvwxyz';
$random_dots 10;
$random_lines 20;
$captcha_text_color="0x142864";
$captcha_noice_color "0x142864";

$code '';


$i 0;
while (
$i $characters_on_image) { 
$code .= substr($possible_lettersmt_rand(0strlen($possible_letters)-1), 1);
$i++;
}


$font_size $image_height 0.75;
$image = @imagecreate($image_width$image_height);


/* setting the background, text and noise colours here */
$background_color imagecolorallocate($image255255255);

$arr_text_color hexrgb($captcha_text_color);
$text_color imagecolorallocate($image$arr_text_color['red'], 
        
$arr_text_color['green'], $arr_text_color['blue']);

$arr_noice_color hexrgb($captcha_noice_color);
$image_noise_color imagecolorallocate($image$arr_noice_color['red'], 
        
$arr_noice_color['green'], $arr_noice_color['blue']);


/* generating the dots randomly in background */
for( $i=0$i<$random_dots$i++ ) {
imagefilledellipse($imagemt_rand(0,$image_width),
 
mt_rand(0,$image_height), 23$image_noise_color);
}


/* generating lines randomly in background of image */
for( $i=0$i<$random_lines$i++ ) {
imageline($imagemt_rand(0,$image_width), mt_rand(0,$image_height),
 
mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}


/* create a text box and add 6 letters code in it */
$textbox imagettfbbox($font_size0$font$code); 
$x = ($image_width $textbox[4])/2;
$y = ($image_height $textbox[5])/2;
imagettftext($image$font_size0$x$y$text_color$font $code);


/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
$_SESSION['digit'] = $code;

function 
hexrgb ($hexstr)
{
  
$int hexdec($hexstr);

  return array(
"red" => 0xFF & ($int >> 0x10),
               
"green" => 0xFF & ($int >> 0x8),
               
"blue" => 0xFF $int);
}
?>