Wie kann ich meinen „mySQL“ Code bearbeiten, so kann ich SQL-Injection-Angriff vermeiden?

stimmen
0

Kann jemand bitte helfen Sie mir , meinen Code zu bearbeiten , so i „vermeiden können SQL - Injection - Angriff “? Ich wurde gesagt , dass mein Code für SQL - Injection - Angriff offen ist , aber ich weiß nicht , wie es zu bearbeiten. Würden Sie bitte so freundlich sein und mir helfen , es neu zu schreiben? Danke vielmals.

Ich sah andere ähnliche Fragen wie diese (Sie sagen Duplikat), aber da ich ein Neuling bin mysql Ich hatte gehofft, dass jemand von euch so gut sein wird mich mein Code neu schreiben zu helfen. Danke vielmals

Das ist mein Register Code:

<?php
// Include config file
require_once config.php;

//the form has been submitted with post
if ($_SERVER[REQUEST_METHOD] == POST) {


        //define other variables with submitted values from $_POST
        $username = $mysqli->real_escape_string($_POST['username']);
        $fullname = $mysqli->real_escape_string($_POST['fullname']);
        $jobtitle = $mysqli->real_escape_string($_POST['jobtitle']);

        $password = password_hash($_POST['password'], PASSWORD_BCRYPT);

        //path were our avatar image will be stored
        $avatar_path = $mysqli->real_escape_string('images/avatars/'.$_FILES['avatar']['name']);

        //make sure the file type is image
        if (preg_match(!image!,$_FILES['avatar']['type'])) {

            //copy image to images/ folder
            if (copy($_FILES['avatar']['tmp_name'], $avatar_path)){

                //set session variables to display on welcome page
                $_SESSION['username'] = $username;
                $_SESSION['avatar'] = $avatar_path;
                $_SESSION['jobtitle'] = $jobtitle;

                //insert user data into database
                $sql =
                INSERT INTO users (username, password, fullname, avatar, jobtitle) 
                . VALUES ('$username', '$password', '$fullname', '$avatar_path', '$jobtitle');

                //check if mysql query is successful
                if ($mysqli->query($sql) === true){
                    $_SESSION['message'] = Registration successful!
                    . Added $username to the database!;
                    //redirect the user to welcome.php
                    header(location: index.php);
                  }
                  else {
                      $_SESSION['message'] = 'User could not be added to the database!';
                  }
                  $mysqli->close();
              }
              else {
                  $_SESSION['message'] = 'File upload failed!';
              }
          }
          else {
              $_SESSION['message'] = 'Please only upload GIF, JPG or PNG images!';
          }
      }



?>

Das ist mein „ Config “ Code:

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'employees');

/* Attempt to connect to MySQL database */
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Check connection
if($mysqli === false){
    die(ERROR: Could not connect.  . $mysqli->connect_error);
}
?>

Dies ist der Code von der Login - Seite :

<?php
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION[loggedin]) && $_SESSION[loggedin] === true){
    header(location: dash.php);
    exit;
}

// Include config file
require_once config.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($_POST[username]))){
        $username_err = Внесете Корисничко Име;
    } else{
        $username = trim($_POST[username]);
    }

    // Check if password is empty
    if(empty(trim($_POST[password]))){
        $password_err = Внесете Лозинка;
    } else{
        $password = trim($_POST[password]);
    }

    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = SELECT id, username, password, fullname, avatar, jobtitle FROM users WHERE username = ?;

        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param(s, $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Store result
                $stmt->store_result();

                // Check if username exists, if yes then verify password
                if($stmt->num_rows == 1){
                    // Bind result variables
                    $stmt->bind_result($id, $username, $hashed_password, $fullname, $avatar_path, $jobtitle);
                    if($stmt->fetch()){
                        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[fullname] = $fullname;
                            $_SESSION[avatar] = $avatar_path;
                            $_SESSION[jobtitle] = $jobtitle;

                            // Redirect user to welcome page
                            header(location: dash.php);
                        } else{
                            // Display an error message if password is not valid
                            $password_err = Лозинката не е точна.;
                        }
                    }
                } else{
                    // Display an error message if username doesn't exist
                    $username_err = Не постои такво корисничко име;
                }
            } else{
                echo Упссс! Има некоја грешка. Обидетесе повторно.;
                }
        }

        // Close statement
        $stmt->close();
    }

    // Close connection
    $mysqli->close();
}
?>
Veröffentlicht am 27/11/2018 um 17:59
quelle vom benutzer
In anderen Sprachen...                            


1 antworten

Wie kann ich meinen „mySQL“ Code bearbeiten, so kann ich SQL-Injection-Angriff vermeiden?

stimmen
0

Kann jemand bitte helfen Sie mir , meinen Code zu bearbeiten , so i „vermeiden können SQL - Injection - Angriff “? Ich wurde gesagt , dass mein Code für SQL - Injection - Angriff offen ist , aber ich weiß nicht , wie es zu bearbeiten. Würden Sie bitte so freundlich sein und mir helfen , es neu zu schreiben? Danke vielmals.

Ich sah andere ähnliche Fragen wie diese (Sie sagen Duplikat), aber da ich ein Neuling bin mysql Ich hatte gehofft, dass jemand von euch so gut sein wird mich mein Code neu schreiben zu helfen. Danke vielmals

Das ist mein Register Code:

<?php
// Include config file
require_once "config.php";

//the form has been submitted with post
if ($_SERVER["REQUEST_METHOD"] == "POST") {


        //define other variables with submitted values from $_POST
        $username = $mysqli->real_escape_string($_POST['username']);
        $fullname = $mysqli->real_escape_string($_POST['fullname']);
        $jobtitle = $mysqli->real_escape_string($_POST['jobtitle']);

        $password = password_hash($_POST['password'], PASSWORD_BCRYPT);

        //path were our avatar image will be stored
        $avatar_path = $mysqli->real_escape_string('images/avatars/'.$_FILES['avatar']['name']);

        //make sure the file type is image
        if (preg_match("!image!",$_FILES['avatar']['type'])) {

            //copy image to images/ folder
            if (copy($_FILES['avatar']['tmp_name'], $avatar_path)){

                //set session variables to display on welcome page
                $_SESSION['username'] = $username;
                $_SESSION['avatar'] = $avatar_path;
                $_SESSION['jobtitle'] = $jobtitle;

                //insert user data into database
                $sql =
                "INSERT INTO users (username, password, fullname, avatar, jobtitle) "
                . "VALUES ('$username', '$password', '$fullname', '$avatar_path', '$jobtitle')";

                //check if mysql query is successful
                if ($mysqli->query($sql) === true){
                    $_SESSION['message'] = "Registration successful!"
                    . "Added $username to the database!";
                    //redirect the user to welcome.php
                    header("location: index.php");
                  }
                  else {
                      $_SESSION['message'] = 'User could not be added to the database!';
                  }
                  $mysqli->close();
              }
              else {
                  $_SESSION['message'] = 'File upload failed!';
              }
          }
          else {
              $_SESSION['message'] = 'Please only upload GIF, JPG or PNG images!';
          }
      }



?>

Das ist mein „ Config “ Code:

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'employees');

/* Attempt to connect to MySQL database */
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Check connection
if($mysqli === false){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}
?>

Dies ist der Code von der Login - Seite :

<?php
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: dash.php");
    exit;
}

// Include config file
require_once "config.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($_POST["username"]))){
        $username_err = "Внесете Корисничко Име";
    } else{
        $username = trim($_POST["username"]);
    }

    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Внесете Лозинка";
    } else{
        $password = trim($_POST["password"]);
    }

    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, username, password, fullname, avatar, jobtitle FROM users WHERE username = ?";

        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("s", $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Store result
                $stmt->store_result();

                // Check if username exists, if yes then verify password
                if($stmt->num_rows == 1){
                    // Bind result variables
                    $stmt->bind_result($id, $username, $hashed_password, $fullname, $avatar_path, $jobtitle);
                    if($stmt->fetch()){
                        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["fullname"] = $fullname;
                            $_SESSION["avatar"] = $avatar_path;
                            $_SESSION["jobtitle"] = $jobtitle;

                            // Redirect user to welcome page
                            header("location: dash.php");
                        } else{
                            // Display an error message if password is not valid
                            $password_err = "Лозинката не е точна.";
                        }
                    }
                } else{
                    // Display an error message if username doesn't exist
                    $username_err = "Не постои такво корисничко име";
                }
            } else{
                echo "Упссс! Има некоја грешка. Обидетесе повторно.";
                }
        }

        // Close statement
        $stmt->close();
    }

    // Close connection
    $mysqli->close();
}
?>
Beantwortet am 27/11/2018 um 17:59
quelle vom benutzer

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more