displaying variable content is not working
here's my php code with variable name of $schanName
if($_POST['thisfolder'] == 'default') {
$schanName = 'Please select a Name';
return;
}
i have tried this to echo out the string where ever i want
<div id="err" style="color:#fff;"><?php echo $schanName ?></div>
but it doesn't show anything at all.
if i try it like this it will work
if($_POST['thisfolder'] == 'default') {
echo 'Please select a Name';
return;
}
but i don't know what am i doing wrong up there and it's not working.
EDIT #2 HERE my whole page
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<div id="error"> i must display that error here</div>
<form class="s_submit" method="post">
<label class="def_lab">File:</label>
<input class="t_box" type='text' name='filename' placeholder='File Name'>
<label class="t_lab def_lab">Select Folder:</label>
<select id="soflow" name="thisfolder">
<option selected="selected" value="default">Default</option>
<option value="../embed/tv/xbox/">Xbox</option>
<option value="Folder2">Folder2</option>
<option value="Folder3">Folder3</option>
</select><br><br>
<label class="def_lab">Text Area 1:</label><br>
<textarea class="tarea_box" type='text' name='strin'></textarea><br><br>
<label class="def_lab">Text Area 2:</label><br>
<textarea class="tarea_box" type='text' name='strin2'></textarea><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<?php
var_dump($_POST);
$fNum = 'File Name is Required';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['filename'])) {
echo $fNum;
return;
}
if($_POST['thisfolder'] == 'default') {
$schanName = 'Please select a Folder';
return;
}
$filename=$_POST['filename'];
$words = array("1", "2", "3", "4", "5");
$arrlength = count($words);
$found = false;
for($x = 0; $x < $arrlength; $x++) {
if($filename == $words[$x])
{
$found = true;
}
}
if($found)
{
echo 'Not a valid File Name';
return;
}
// the name of the file to create
$filename=$_POST['filename'];
// the name of the file to be in page created
$strin=$_POST['strin'];
// the name of the file to be in page created
$strin2=$_POST['strin2'];
// the name of the folder to put $filename in
$thisFolder = $_POST['thisfolder'];
// make sure #thisFolder of actually a folder
if (!is_dir(__DIR__.'/'.$thisFolder)) {
// if not, we need to make a new folder
mkdir(__DIR__.'/'.$thisFolder);
}
// . . . /[folder name]/page[file name].php
$myFile = __DIR__.'/'.$thisFolder. "/page" .$filename.".php";
// This is another way of writing an if statment
$div = ($strin !== '') ? '<div id="area_code">'.$strin.'</div>' : '<div id="area_code">'.$strin2.'</div>';
$fh = fopen($myFile, 'w');
$stringData = "";
fwrite($fh, $stringData);
fclose($fh);
}
?>
</body>
</html>
U need to give this $schanName a value and html form need to be added after php because if u use php after html u can't get values or variable names. But if u use php then html then u can grab values and variables from php into html.
For error report i puted u errors in array so u will get all errors at once.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST['filename']))
{
$schanName[] = 'File Name is Required';
}
if($_POST['thisfolder'] == 'default')
{
$schanName[] = 'Please select a Folder';
}
$filename=$_POST['filename'];
$words = array("1", "2", "3", "4", "5");
$arrlength = count($words);
$found = false;
for($x = 0; $x < $arrlength; $x++)
{
if($filename == $words[$x])
{
$found = true;
}
}
if($found)
{
$schanName[] = 'Not a valid File Name';
}
// the name of the file to create
$filename=$_POST['filename'];
// the name of the file to be in page created
$strin=$_POST['strin'];
// the name of the file to be in page created
$strin2=$_POST['strin2'];
// the name of the folder to put $filename in
$thisFolder = $_POST['thisfolder'];
// make sure #thisFolder of actually a folder
if (!is_dir(__DIR__.'/'.$thisFolder))
{
// if not, we need to make a new folder
mkdir(__DIR__.'/'.$thisFolder);
}
// . . . /[folder name]/page[file name].php
$myFile = __DIR__.'/'.$thisFolder. "/page" .$filename.".php";
// This is another way of writing an if statment
$div = ($strin !== '') ? '<div id="area_code">'.$strin.'</div>' : '<div id="area_code">'.$strin2.'</div>';
$fh = fopen($myFile, 'w');
$stringData = "";
fwrite($fh, $stringData);
fclose($fh);
}
?>
<?php
// display your errors here
if(!empty($schanName))
{
foreach ($schanName as $sn)
{
echo '<div id="error"><ul><li>'.$sn.'</li></ul></div>';
}
}
?>
<form class="s_submit" method="post">
<label class="def_lab">File:</label>
<input class="t_box" type='text' name='filename' placeholder='File Name'>
<label class="t_lab def_lab">Select Folder:</label>
<select id="soflow" name="thisfolder">
<option selected="selected" value="default">Default</option>
<option value="../embed/tv/xbox/">Xbox</option>
<option value="Folder2">Folder2</option>
<option value="Folder3">Folder3</option>
</select><br><br>
<label class="def_lab">Text Area 1:</label><br>
<textarea class="tarea_box" type='text' name='strin'></textarea><br><br>
<label class="def_lab">Text Area 2:</label><br>
<textarea class="tarea_box" type='text' name='strin2'></textarea><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</body>
</html>
Declare the variable $schanName outside the if statement first then you can use it in if statement. It will display in the html also.
This is a scoping issue. Check variable scope for more details.
Related
I have an assignment that needs me to create a simple login page that asks for a username and password. Once entered, it checks a text file and if the username and password match the ones on file, it's supposed to display the words "Access Granted" with no other content on the page.
How do I make it so my form shows up normally on load, and then when a unsuccessful login attempt is made, it displays "Access Denied" on the same page, but when a successful login attempt is made, "Access Granted" is displayed along with no other content?
Here is my code:
<?php
$fs = fopen('includes/users.txt', 'r');
$contents = fread($fs, filesize('includes/users.txt'));
$words = explode('||>><<||', $contents);
$msg = "";
if(isset($_POST['Submit']))
{
foreach($words as $word)
{
$names = explode(",", $word);
for($x = 0; $x < sizeof($names); $x++)
{
if($x == 0)
{
$username = $names[$x];
}
else
{
$password = $names[$x];
}
}
if($_POST['user'] == $username && $_POST['pass'] == $password)
{
$msg = "<p>Access Granted!</p>";
break;
}
else
{
$msg = "<p>Access Denied!</p>";
break;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Insecure</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div>
<form method="post">
<input placeholder="Username" type="text" name="user"><br>
<input placeholder="Password" type="password" name="pass"><br><br>
<input type="submit" value="Log In" name="Submit">
<input type="reset">
</form><br><br>
</div>
<?php echo $msg; ?>
</body>
</html>
Echo the $msg variable immediately it is declared in your if and else statements, rather than after your form.
To ensure nothing else is printed to the screen after $msg is echoed, a crude way to do this will be with “die()”.
This way, the form won’t show up because the script has been killed after echoing $msg in either the if or else statement.
<?php
$fs = fopen('includes/users.txt', 'r');
$contents = fread($fs, filesize('includes/users.txt'));
$words = explode('||>><<||', $contents);
$msg = "";
if(isset($_POST['Submit']))
{
foreach($words as $word)
{
$names = explode(",", $word);
for($x = 0; $x < sizeof($names); $x++)
{
if($x == 0)
{
$username = $names[$x];
}
else
{
$password = $names[$x];
}
}
if($_POST['user'] == $username && $_POST['pass'] == $password)
{
$msg = "<p>Access Granted!</p>";
break;
}
else
{
$msg = "<p>Access Denied!</p>";
break;
}
//Print the $msg variable and kill the script
die($msg);
}
}
?>
Your HTML becomes:
<form method="post">
<input placeholder="Username" type="text" name="user"><br>
<input placeholder="Password" type="password" name="pass"><br><br>
<input type="submit" value="Log In" name="Submit">
<input type="reset">
</form>
You can use Die(""); or Exit("")
Like this :
Die("Access granted");
The die kills the whole page and you can set a Message to it !
For better Risults :
die("<div class='YOUR CLASSES'>Your message</div>");
Exit is really die.
exit("MESSAGE");
exit("<div class='YOUR CLASSES'>Your message</div>");
I'm new to PHP and I'm trying to create an easy form that has multiple steps. For each step, a validation of the input is happening before the user is directed to the next page. If the validation fails, the user should stay on the same page and an error message should be displayed. In the end, all entries that the user has made should be displayed in an overview page.
What I have been doing to solve this, is to use a boolean for each page and only once this is true, the user can go to the next page. This is not working as expected unfortunately and I guess it has something to do with sessions in PHP... I also guess that there's a nicer way to do this. I would appreciate some help!
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
session_start();
$_SESSION['$entryOne'] = "";
$_SESSION['$entryOneErr'] = $_SESSION['$emptyFieldErr'] = "";
$_SESSION['entryOneIsValid'] = false;
$_SESSION['$entryTwo'] = "";
$_SESSION['$entryTwoErr'] = "";
$_SESSION['entryTwoIsValid'] = false;
// Validation for first page
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryOne'])) {
if (!empty($_POST["entryOne"])) {
// Check for special characters
$_SESSION['$entryOne'] = removeWhitespaces($_POST["entryOne"]);
$_SESSION['$entryOneErr'] = testForIllegalCharError($_SESSION['$entryOne'], $_SESSION['$entryOneErr']);
// If error text is empty set first page to valid
if(empty($_SESSION['$entryOneErr'])){
$_SESSION['$entryOneIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
// Validation for second page
} else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryTwo'])) {
if (!empty($_POST["entryTwo"])) {
// Check for special characters
$_SESSION['$entryTwo'] = removeWhitespaces($_POST["entryTwo"]);
$_SESSION['$entryTwoErr'] = testForIllegalCharError($_SESSION['$entryTwo'], $_SESSION['$entryTwoErr']);
// If error text is empty set second page to valid
if(empty($_SESSION['$entryTwoErr'])){
$_SESSION['$entryTwoIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
}
//Remove whitespaces at beginning and end of an entry
function removeWhitespaces($data) {
$data = trim($data);
return $data;
}
//Check that no special characters were entered. If so, set error
function testForIllegalCharError($wish, $error){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar,$wish)) {
$error = "Special characters are not allowed";
} else {
$error = "";
}
return $error;
}
?>
<?php if (isset($_POST['submitEntryOne']) && $_SESSION['$entryOneIsValid'] && !$_SESSION['$entryTwoIsValid']): ?>
<h2>Second page</h2>
<p>Entry from first Page: <?php echo $_SESSION['$entryOne'];?></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Entry Two: <input type="text" name="entryTwo" value="<?php echo $_SESSION['$entryTwo'];?>">
<span class="error"><?php echo $_SESSION['$entryTwoErr'];?></span>
<br><br>
<input type="submit" name="submitEntryTwo" value="Next">
</form>
<?php elseif (isset($_POST['submitEntryTwo']) && $_SESSION['$entryTwoIsValid']): ?>
<h2>Overview</h2>
<p>First entry: <?php echo $_SESSION['$entryOne'];?></p>
<p>Second Entry: <?php echo $_SESSION['$entryTwo'];?></p>
<?php else: ?>
<h2>First page</h2>
<span class="error"><?php echo $_SESSION['$emptyFieldErr'];?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
First entry: <input type="text" name="entryOne" value="<?php echo $_SESSION['$entryOne'];?>">
<span class="error"> <?php echo $_SESSION['$entryOneErr'];?></span>
<br><br>
<input type="submit" name="submitEntryOne" value="Next">
</form>
<?php endif; ?>
</body>
</html>
You are setting your session variables to "" at the top of your script.
Check if your variable is set before setting to blank.
Check if Session Variable is Set First
<?php
//If variable is set, use it. Otherwise, set to null.
// This will carry the variable session to session.
$entryOne = isset($_REQUEST['entryOne']) ? $_REQUEST['entryOne'] : null;
if($entryOne) {
doSomething();
}
?>
Tips
Then you can use <?= notation to also echo the variable.
Do this $_SESSION['variable'] instead of $_SESSION['$variable'] (you'll spare yourself some variable mistakes).
<h2>Second page</h2>
<p>Entry from first Page: <?= $entryOne ?></p>
Example Script
This could be dramatically improved, but for a quick pass:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Check that no special characters were entered. If so, set error
function hasIllegalChar($input){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar, $input)) {
return true;
}
return false;
}
session_start();
// Destroy session and redirect if reset form link is pressed.
if(isset($_GET['resetForm']) && $_GET['resetForm'] == "yes")
{
echo "SESSION DESTROY";
session_destroy();
header("Location: ?");
}
// Session
$page = isset($_SESSION['page']) ? $_SESSION['page'] : 1;
$errors = [];
// Value history.
$valueOne = isset($_SESSION['valueOne']) ? $_SESSION['valueOne'] : null;
$valueTwo = isset($_SESSION['valueTwo']) ? $_SESSION['valueTwo'] : null;
// Clean inputs here
$fieldOne = isset($_REQUEST['fieldOne']) ? trim($_REQUEST['fieldOne']) : null;
$fieldTwo = isset($_REQUEST['fieldTwo']) ? trim($_REQUEST['fieldTwo']) : null;
// First form
if ($page == 1) {
// If field two is submitted:
if ($fieldOne) {
//Validate inputs
if(hasIllegalChar($fieldOne)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueOne = $_SESSION['valueOne'] = $fieldOne;
$page = $_SESSION['page'] = 2;
}
}
}
// Second form
else if ($page == 2) {
// If field two is submitted:
if ($fieldTwo) {
//Validate inputs
if(hasIllegalChar($fieldTwo)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueTwo = $_SESSION['valueTwo'] = $fieldTwo;
$page = $_SESSION['page'] = 3;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
// troubleshoot
if (true) {
echo "<pre>";
var_dump($_REQUEST);
var_dump($_SESSION);
echo "</pre>";
}
echo "<h1>Page " . $page . '</h1>';
if (count($errors) > 0) {
$errorMsg = implode('<br/>',$errors);
echo '<div class="error">Some errors occurred:<br/>' . $errorMsg . '</div>';
}
?>
<?php if ($page == 3): ?>
<h2>Overview</h2>
<p>First entry: <?= $valueOne;?></p>
<p>Second Entry: <?= $valueTwo;?></p>
Reset
<?php elseif ($page == 2): ?>
<p>Entry from first Page: <?= $valueOne; ?></p>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
Entry Two: <input type="text" name="fieldTwo" value="<?= $fieldTwo ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php else: ?>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
<br><br>
Entry One: <input type="text" name="fieldOne" value="<?= $fieldOne; ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php endif; ?>
</body>
<html>
You can run the following command to test out the page without using a fancy tool like WAMP or LAMP.
php -S localhost:8000 index.php
You can now access in the browser at http://localhost:8000.
I am new to php and working on a hangman game. I have a home.php that takes you to the homepage and their is a login form that the user must submit a username and a password. If the username and password match with the one I have set, it will redirect to hangman.php. I want some advice if the way I have written the script is correct or not. Also, I am getting a 500 error after the user logs in. I don't know why. I will paste the code down below.
Update: I have added the code for hangman.php
home.php
<?php
// starting a new session
session_start();
if(isset($_POST['uname'], $_POST['psw'])){
$uname= "my_admin";
$psw = "password";
if($_POST['uname'] == $uname && $_POST['psw'] == $psw) {
$_SESSION["uname"] = "my_admin";
$_SESSION["psw"] = "password";
# array holds errors
$errors = array();
# validation starts here
if(empty($_POST['uname'])){
$errors['uname1'] = "Your name cannot be empty";
}
# check strlength
if(strlen($_POST['uname']) < 6){
$errors['uname2'] = "Must be longer than 6 characters";
}
# check username
if ($_POST['uname'] !== "my_admin"){
$errors['uname3'] = "You are not the admin";
}
if($_POST['uname'] == "my_admin" && $_POST['psw'] == "password"){
header('Location:hangman.php');
exit();
}else{
$errors['uname4'] = "Please try again";
}
if(empty($_POST['psw'])){
$errors['psw1'] = "Your password cannot be empty";
}
if(strlen($_POST['psw']) < 6){
$errors['psw2'] = "Must be longer than 6 characters";
}
if($_POST['psw'] !== "password"){
$errors['ps3'] = "AH AH AH thats not it";
}else{
header('Location:hangman.php');
exit();
}
if(count($errors) == 0){
# redirect to the game page
header('Location:hangman.php');
exit();
}
}
}
?>
form for my script to run against
<div class="container">
</p>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname">
<p>
<?php if(isset($errors['uname1']))
echo $errors['uname1']; ?>
</p>
<p>
<?php if(isset($errors['uname2']))
echo $errors['uname2']; ?>
</p>
<p>
<?php if(isset($errors['uname3']))
echo $errors['uname3']; ?>
</p>
<p>
<?php if(isset($errors['uname4']))
echo $errors['uname4']; ?>
</p>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw">
<p>
<?php if(isset($errors['psw1'])) echo $errors['psw1']; ?>
</p>
<p>
<?php if(isset($errors['psw2'])) echo $errors['psw2']; ?>
</p>
<?php if(isset($errors['psw3'])) echo $errors['psw3']; ?>
</p>
<button name="check" type="submit" value="submit">Login</button>
</div>
</form>
hangman.php
<?php
require_once 'hangedman.php';
$words = array('VIETNAM', 'PEOPLE', 'PYTHON');
$numwords = 0;
function printPage($image, $guesstemplate, $which, $guessed, $wrong) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
<link rel="stylesheet" type="text/css" href="home.css">
</head>
</html>
<body>
<h1 style='color: red'>Hangman Game</h1>
<br />
<pre style='color: red'>$image</pre>
<br />
<p style='color:red'><strong>Word to guess: $guesstemplate</strong></p>
<p style='color:red'>Letters used in guesses so far: $guessed</p>
<form method="post" action="$script">
<input type="hidden" name="wrong" value="$wrong" />
<input type="hidden" name="lettersguessed" value="$guessed" />
<input type="hidden" name="word" value="$which" />
<fieldset>
<legend style='color: red'>Your next guess</legend>
<input type="text" name="letter" autofocus />
<input type="submit" value="Guess" />
</fieldset>
</form>
</body>
ENDPAGE;
}
function loadWords() {
global $words;
global $numwords;
$input = fopen("./words.txt", "r");
while (true) {
$str = fgets($input);
if (!$str) break;
$words[] = rtrim($str);
$numwords++;
}
fclose($input);
}
function startGame() {
global $words;
global $numwords;
global $hang;
$which = rand(0, $numwords - 1);
$word = $words[$which];
$len = strlen($word);
$guesstemplate = str_repeat('_ ', $len);
$script = $_SERVER["PHP_SELF"];
printPage($hang[0], $guesstemplate, $which, "", 0);
}
function killPlayer($word) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>You lost!</h1>
<p>The word you were trying to guess was <em>$word</em>.</p>
</body>
</html>
ENDPAGE;
}
function congratulateWinner($word) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>You win!</h1>
<p>Congratulations! You guessed that the word was <em>$word</em>.</p>
</body>
</html>
ENDPAGE;
}
function matchLetters($word, $guessedLetters) {
$len = strlen($word);
$guesstemplate = str_repeat("_ ", $len);
for ($i = 0; $i < $len; $i++) {
$ch = $word[$i];
if (strstr($guessedLetters, $ch)) {
$pos = 2 * $i;
$guesstemplate[$pos] = $ch;
}
}
return $guesstemplate;
}
function handleGuess() {
global $words;
global $hang;
$which = $_POST["word"];
$word = $words[$which];
$wrong = $_POST["wrong"];
$lettersguessed = $_POST["lettersguessed"];
$guess = $_POST["letter"];
$letter = strtoupper($guess[0]);
if(!strstr($word, $letter)) {
$wrong++;
}
$lettersguessed = $lettersguessed . $letter;
$guesstemplate = matchLetters($word, $lettersguessed);
if (!strstr($guesstemplate, "_")) {
congratulateWinner($word);
} else if ($wrong >= 6) {
killPlayer($word);
} else {
printPage($hang[$wrong], $guesstemplate, $which, $lettersguessed, $wrong);
}
}
//header("Content-type: text/plain");
loadWords();
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "POST") {
handleGuess();
} else {
startGame();
}
?>
I'm having some trouble displaying my errors on this login form.
The login works but I can't figure out how to display those errors.
I just need to display them between the login field and the footer. I suppose the problem should be the last part of the foreach that should go true the error array.
<!DOCTYPE html>
<html lang="en">
<body>
<?php
include ('includes/header.php');
?>
<div class="nav">
<?php
include ('includes/menu.php');
$error= logInData();
?>
</div>
<section role="main">
<div class="logIn">
<h3>Intranet Login</h3>
</div>
<form action="" method="post">
<fieldset>
<legend>Student Log in</legend>
<div>
<label for="username">Enter username: </label>
<input type='text' id="userN" name="userN" value = "<?php if (isset($error['usern'])){echo $error['usern'];} ?>">
</div>
<div>
<label for="password">Enter password: </label>
<input type='password' id="pass" name="pass" value = "">
</div>
<div>
<p class="red"><?php if (isset($error['both'])) {
echo $error['both'];
} ?></p>
</div>
<div>
<input type="submit" name="submit" value="Log-In">
</div>
</fieldset>
</form>
</section>
<?php
function logInData (){
$error = array();
$validated = array();
$clean = array();
$pass = false;
if (isset($_POST['submit']) && $pass == true) {
$inputPass = ($_POST['pass']);
$trimPass = trim($inputPass);
$inputUsern = ($_POST['userN']);
$trimUsern = trim($inputUsern);
if(!empty($trimPass)){
if (!ctype_alpha($trimPass)) {
$error['passw'] = 'No special characters allowed on password';
$pass = false;
}else{
if(empty($trimPass)){
$error['passw'] = 'password field empty';
$pass = false;
}else{
$clean['passw'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
if(!empty($trimUsern)){
if (!ctype_alpha($trimUsern)) {
$error['userN'] = 'No special characters allowed on username';
$pass = false;
}else{
if(empty($trimPass)){
$error['userN'] = 'username field empty';
$pass = false;
}else{
$clean['userN'] = $trimUsern;
$pass = true;
}
}
}if ($pass == true) {
return $clean;
}else {
return $error;
}
$dir = '/home/sbau01/public_www/php/fma/data';
if (is_dir($dir)){
$handleDir = opendir('/home/sbau01/public_www/php/fma/data');
$path = "/home/sbau01/public_www/php/fma/data/data.txt";
if(is_file($path)){
$handle = fopen($path, 'r');
while(!feof($handle)){
$dataRow = fgets($handle);
if(!empty($dataRow)){
$separate = explode(' ',$dataRow);
$storedUsern = trim($separate[3]);
$storedPassword = trim($separate[4]);;
if (($clean['userN'] == $storedUsern) && ($clean['passw'] && $storedPassword)){
$match = true;
header('location: intranet.php');
}else{
$error['match']='<span >Username/Password is incorrect!!</span>';
$pass = false;
}
}
}fclose($handle);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}closedir($HandleDir);
}else{
$error['data']='<span >Data not found</span>';
$pass = false;
}
}else {
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
}
}
?>
<footer>
<?php include ('includes/footer.php');?>
</footer>
</body>
</html>
Its a simple brackets error:
$errmsg = '';
foreach($error as $key => $value){
echo "ERROR: $value<br />\n";
}
The part above is in the else condition of if (isset($_POST['submit']) && $pass == true) {
Thats why this will never execute. Simply remove the bracket above this part and add it after the foreach.
Saving Passwords in text files is NOT a great idea!
In line 101 you have probably an little mistake:
You just check if there are the variables, you dont check if they are equal ($clean['passw'] && $storedPassword)){
A couple of issues identified.
Do you have display errors turned on? https://stackoverflow.com/a/21429652/1246494
You are calling $error= logInData(); at the top, but have your function logInData() { ... } created down below.
I think what you want to do it put the whole function in an include file at the top like:
include ('includes/header.php');
include ('includes/logInFunction.php');
You then want to call logInData(); down in the body.
Another issue is your function puts data in an array and echos data. If you are going to have $error= logInData(); at the top of your page try moving this out of your function and into your body where you want to output the errors.
if(count($error) > 0)
{
foreach($error as $key => $value)
{
echo "ERROR: $value<br />\n";
}
}
I am trying to check the form on this page and if everything is entered correct I want send the $name, $sport, $beoefenaar and $text to the page http://localhost/051R4-verwerk.php. But the variables aren't being sent to that page.
<!DOCTYPE HTML>
<html>
<head>
<title>Inzendopdracht 051R4</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" type="text/css" media="all" />
</head>
<body>
<a href='viewguestbook.php'>View Guestbook</a>
<?php
// define variables and set to empty values
$nameErr = $sportErr = $beoefenaarErr = $textErr = "";
$name = $sport = $beoefenaar = $text ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = true;
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$valid = false;
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["sport"])) {
$sportErr = "Sport is required";
$valid = false;
} else {
$sport = test_input($_POST["sport"]);
}
if (empty($_POST["text"])) {
$textErr = "Comment is required";
$valid = false;
} else {
$text = test_input($_POST["text"]);
}
if (empty($_POST["beoefenaar"])) {
$beoefenaarErr = "Comment is required";
} else {
$beoefenaar = test_input($_POST["beoefenaar"]);
}
if($valid){
header("location: http://localhost/051R4-verwerk.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Laat hier u bericht achter</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Sport: <select name="sport">
<option valeu="">
<option valeu="Tennis">Tennis
<option valeu="Voetbal">Voetbal
<option valeu="Running">Running
<option valeu="Tafeltenis">Tafeltenis
<option valeu="Squash">Squash
<option valeu="Wielrennen">Wielrennen
<option valeu="Boksen">Boksen
</select>
<span class="error">* <?php echo $sportErr;?></span>
<br><br>
Beoefenaar:
<INPUT TYPE="radio" name="beoefenaar" value="0" checked>Nee
<INPUT TYPE="radio" name="beoefenaar" value="1">Ja
<br><br>
<textarea name="text" placeholder="Schrijf hier u bericht*" /></textarea>
<span class="error"> <?php echo $textErr;?></span>
<br><br>
<input type="submit" value="Verstuur"/>
</form>
</body>
</html>
The issue is that you aren't including your second PHP file. You are redirecting to the second PHP file. This means that your are instructing the browser to load up a new page with a new HTTP request. PHP can't store variables between calls, so when this new request comes in all previous variables (and history) are lost. Each page executes completely separate from every other page.
Instead, the simplest way to accomplish what you are trying to accomplish is with sessions. This allows you to store information on a user between script executions. PHP will automatically create cookies for you and manage the session information. You just have to get your data into the session, and then get it back out of the session in your second script. In your first script that could look something like this:
if($valid){
$_SESSION['name'] = $name;
$_SESSION['sport'] = $sport;
/// and more
header("location: http://localhost/051R4-verwerk.php");
}
Then in your receiving script:
$name = isset( $_SESSION['name'] ) ? $_SESSION['name'] : '';
$sport = isset( $_SESSION['sport'] ) ? $_SESSION['sport'] : '';
This will only work if the two scripts are hosted by the same server and on the same domain. There are lots of tutorials out there about using sessions. You will actually still have to validate the data again in your second script, because a user can go directly to it without any information in the session.
Your second option would be to include the second script instead of redirecting to it, in which case your variables will actually be available, but you will also have to adjust the way your first page works. Maybe something like:
if($valid){
include "051R4-verwerk.php";
exit;
}