Can't submit an input for later use. php - php

I am trying to use a search bar to grab the users input but when i input and submit nothing happens, I its not submitting properly but i can't for the life of me find my mistake. I have copied the input code from a previously created login page which works fine and therefore baffles me even more.
<div class="container">
<div class="form-group">
<?php
$stocksymbol = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["stocksymbol"])) {
$stocksymbolErr = "Please enter Username.";
} else {
$stocksymbol = test_input($_POST["stocksymbol"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}}
$servername = "localhost";
$username2 = "root";
$password2 = "";
$dbname = "mydb";
$mysqli = new mysqli($servername, $username2, $password2, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$query = "SELECT * FROM tblstocks WHERE Symbol = '$stocksymbol'";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$_SESSION['stockavailable'] = true;
$_SESSION['stock']= $row;
header('Location: item.php');
}
$result->free();
}
$mysqli->close();
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="stocksymbol">Search:</label>
<input type="text" class="form-control" id="stocksymbol">
<br><br>
<input type="submit" class="btn btn-default" name="submit" value="Submit">
</form>
</div>

The input element must have an attribute name with the value to be the key that you are expecting on the server i.e. stocksymbol to be able to receive whatever entered in the element.
<input type="text" class="form-control" id="stocksymbol" name="stocksymbol">

Related

PHP isset function for website session not working correctly

So i'm trying to do implement a log in for a website and I want it to change the menu bar on the top.
However I do not get the desired outcome when using php sessions
I use session_start at the beginning
<?php
session_start();
?>
And then in order to change the menu bar I use
<?php
if (!isset($_SESSION['username'])){
?>
<ul>
<li>Home</li>
<li>About</li>
<li><a onclick="document.getElementById('log').style.display='block'" style="width:auto;">Log In</a> </li>
</ul>
<?php
}else if (isset($_SESSION['username'])){
?>
<ul>
<li>Home</li>
<li>About</li>
<li>PLEASE LOG OUT</li>
</ul>
<?php
}
?>
My modal box and script for the log is is the following is
<div id="log" class="modal">
<form class="modal-content animate" action="logindata.php" method="post">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="usrname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
</div>
<div class="container">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
</div>
<script>
// Get the modal
var modal = document.getElementById('log');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
And my logindata.php contains the following
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phpmysql";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user1 = $email1 = $pass1 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user1 = test_input($_POST["usrname"]);
$pass1 = test_input($_POST["psw"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "SELECT username, password, email FROM users";
$result = $conn->query($sql);
$row = $result->fetch_array();
if ($row["username"]==$user1 && $row["password"]==$pass1) {
session_start();
$_SESSION["username"] = $row["username"];
//$_SESSION["email"] = $row["email"];
header("Location: Main_login_authentication.php");
} else {
header("Location: Denied.php");
}
$conn->close();
?>
I know its not a good tactic to send passwords over plaintext.
session_start needs to be at the first line of your code... i see that you have this on the other page but, this one was still wrong ;) otherwise, before the isset do a:
print_r($_SESSION);
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phpmysql";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user1 = $email1 = $pass1 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user1 = test_input($_POST["usrname"]);
$pass1 = test_input($_POST["psw"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "SELECT username, password, email FROM users";
$result = $conn->query($sql);
$row = $result->fetch_array();
if ($row["username"]==$user1 && $row["password"]==$pass1) {
$_SESSION["username"] = $row["username"];
//$_SESSION["email"] = $row["email"];
header("Location: Main_login_authentication.php");
} else {
header("Location: Denied.php");
}
$conn->close();
?>

How to use $_POST in another file

I am making a panel with PHP. It contains a login script. It's working good, just what I expect. The next step is: Echo the username.
With $_POST you can echo the username what the person has typed. So, just like: Welcome, $username.
The problem now is, that I can't echo the $_POST. It's not possible because you will redirect to another page. My question is: How can I echo a username.
My login script:
<?php
//DATABASE CONNECTION
session_start();
$host = "localhost";
$username = "root";
$password = "root";
$database = "test_tutorial";
$message = "";
try {
$connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fname = $_POST["fname"];
//LOGIN CHECK
if(isset($_POST["login"])) {
if(empty($_POST["fname"]) || empty($_POST["lname"])) {
echo 'All fields required';
}
else
{
$query = "SELECT * FROM users WHERE fname = :fname AND lname = :lname";
$statement = $connect->prepare($query);
$statement->execute(
array(
'fname' => $_POST["fname"],
'lname' => $_POST["lname"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
//VISITED
header("Refresh:0; url=veilig.php");
//END
}
else
{
echo 'Wrong data';
}
}
}
}
catch(PDOException $error) {
$message = $error->getMessage();
}
?>
My form:
<form action="" method="post">
<label>fname</label>
<input type="text" name="fname" class="form-control" />
<br />
<label>lname</label>
<input type="password" name="lname" class="form-control" />
<br />
<input type="submit" name="login" value="Login" />
</form>
So, how can I echo a post if someone is redirected to another page?
You've already called session_start so you're ready to use the $_SESSION superglobal which will persist data for the user across all pages that call session_start first.
For example, here on index.php
<?php
session_start();
$_SESSION['username'] = 'Prabhjot.Singh';
header('Location: veilig.php');
Then later on veilig.php
<?php
session_start();
echo $_SESSION['username'];
Prabhjot.Singh

PHP shuffled token not displaying with email entered and button selected

Using a form that has a user submit his/her email and a php query of the database, I am hoping to generate a shuffled token, however, upon button click, the token is not displaying on the page. I have checked the connection to the database and it is successful. Code is as follows:
<?php
$servername = "localhost";
$username = "admin";
$password = "";
$database = "registration";
if (isset($_POST["forgotPass"])) {
$connection = new mysqli($servername, $username, $password, $database);
$email = $connection->real_escape_string($_POST["email"]);
$data = $connection->query("SELECT id FROM users WHERE email='$email'");
if ($data->num_rows > 0) {
$str = "0123456789qwertyuiopasdfghjklzxcvbnm";
$str = str_shuffle($str);
$str = substr($str, 0, 10);
echo $str;
} else {
echo "Please check your inputs!";
}
}
?>
<html>
<body>
<form action="forgotpassword.php" method="post">
<input type="text" name="email" placeholder="Enter Email Address..."><br>
<input type="button" name="forgotPass" value="Request Password" />
</form>
</body>
</html>
Thanks for any and all help/suggestions.

Upload file in a form containing multiple textfields using PHP

I'm trying to figure out how to upload a file into the database where that form contains multiple textfields. I uploaded a BLOB field into the database. So as I try to search the field using the ID number, it will retrieve me the values associated with it. Which works fine, so I added the function of being able to upload a file into that specific id number. I get all sorts of errors and I would like to have an assistance with it. Anyone care to help out? Here are the codes:
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE id = $data[0]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `members` SET `firstname`='$data[1]',`lastname`='$data[2]',`username`='$data[3]' WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
}
<!--UPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOADUPLOAD -->
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'ntmadb');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
// Create the SQL query
$query = "
INSERT INTO `members` (
`data`
)
VALUES (
'{$data}' NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
?>
and here is the html file:
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index4.php" method="post" enctype="multipart/form-data" >
<input type="number" name="id" placeholder="Id" value="<?php echo $id;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<p>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</p>
<p>
<input type="file" name="uploaded_file">
<br>
<input type="submit" value="Upload file">
</p>
</div>
</form>
</body>
</html>
Thanks to anyone who can provide me with help. :)

php /mysql form validation issue

so my php validation has two check functions, first it checks for an empty name or password entry and second if user enters unwanted characters while entering his name, the problem is that if the user does enter an unwanted character or numbers in the 'name' entry the form is still saved to the database which it should not, nothing is saved to the database if the users leaves both the name and password field empty and the error is shown, which means half of my validation check is working fine . can any one help me out ?
<?php
// Connect to data base
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// define variables and set to empty values
$nameErr = $userpasswordErr = "";
$name = $userpassword = "";
//check for error
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//validate name and password
if (
empty($_POST["name"]) ||
empty($_POST["userpassword"] ||
!preg_match("/^[a-zA-Z ]*$/",$name))
) {
$nameErr= "* Incorrect username or password ";
} else {
$name = test_input($_POST["name"]);
$userpassword = test_input($_POST["userpassword"]);
$sql = "INSERT INTO users(name,email)
VALUES ('$name','$userpassword')";
if ($conn->query($sql) === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<span class="error"></span>
<form method="post" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]);?>">
name : <input type="text" name="name" value="<?php echo $name;?>"/>
<span class="error"><?php echo $nameErr ;?> </span>
<br/><br/>
password : <input type="text" name="userpassword" value="<?php echo $userpassword ; ?>">
<span class="error"><?php echo $userpasswordErr ;?> </span>
<br/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
The $name in regular expression check should be $_POST['name']
if(empty($_POST["name"]) || empty($_POST["userpassword"] || !preg_match("/^[a-zA-Z ]*$/",$_POST["name"])))
{
$nameErr= "* Incorrect username or password ";
}

Categories