0

I have a form which contains two fields Username and Password. I want to store the values entered by the user in an array named as stack.

The following code stores the values in the stack array and displays me the array with the exact values which i entered. Even if i have a slash or any html,javascript in my fields it just stores it into the array.

May i know where is my mistake as function check() is not executing properly.

<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "test";
$stack = array();
$connect = mysqli_connect($hostname,$username,$password,$db);
if(!$connect){
    die("Couldn't connect to the database");
    exit();
}
function check($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
if(isset($_POST['login'])){
    foreach($_POST as $value){
        if($value == $_POST['login']){
        break;
        }
        else{
            check($value);
            array_push($GLOBALS['stack'],$value);
        }
    }
    print_r($stack);
}

?>

2 Answers2

1

Please check the commented line.

<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "test";
$stack = array();
$connect = mysqli_connect($hostname,$username,$password,$db);
if(!$connect){
    die("Couldn't connect to the database");
    exit();
}
function check($data){
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
if(isset($_POST['login'])){
    foreach($_POST as $value){
        if($value == $_POST['login']){
        break;
        }
        else{
            $value = check($value); //returned value is not captured
            array_push($GLOBALS['stack'],$value);
        }
    }
    print_r($stack);
}

?>
Varun Victor
  • 100
  • 5
1

you got two options.

  • save the return value from the check function in a variable

    $value = check($value);

  • change function check($data) to function check(&$data)

c4pone
  • 777
  • 7
  • 17