I'm new to php and wanted to make a simple php script to check a form of my html site.
To answer the questions:
I have a file, that's the Name of the User and I want to check if the password that is in there (line 1) is the same as the one in the "password" field on my site. And when it's like this it should open a site.
Maybe a check if the file exists would be nice :D
This is my php-file, it's named "check.php":
<?php
$f = fopen($_POST["name"], "r");
$theData = fgets($f);
if ($_POST["pw"] == $theData) {
$ch = curl_init("site.com");
curl_exec($ch);
}
fclose($f);
?>
This is my html-file:
<h2>Check</h2>
<form action="check.php" method='post'>
<b>Name: </b><input name="name" type="text" value="Name"> <br>
<b>Password: </b><input name="pw" type="text" value="Passwort"> <br>
<input type="submit" value="Check">
<input type="reset" value="Reset">
</form>
I hope one can help me ^^
I've tried a lot of things now, nothing really worked.
To process a form fields you should do like this in your check.php file(simplest one)
if(isset($_POST['submit']))
{
$name = $_PSOT['name'];
$password = $_POST['password'];
if($name == 'admin' && $password == 'admin')
{
header('Location:admin.php');exit;
}else{
echo 'Wrong user name or password';
}
}
may be you are asking to do like this
if(isset($_POST['submit']))
{
$name = $_PSOT['name'];
$password = $_POST['password'];
$file_type = '.txt';
$path = 'path to folder/'.$name.$file_type;
if(file_exists($path))
{
$user_pass = fopen($path, "r");
$flag = 0;
while(!feof($user_pass))
{
$p = fgets($user_pass);
if($password == $p)
{
$flag = 1;
}
}
fclose($user_pass);
if($flag == 1)
{
header('Location:to your page link/weblink');exit;
}else{
echo 'Wrong password';
}
}else{
echo 'User does not exists';
}
}
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 tried this but it doesn't works.
HTML:
<form id="login" method="post">
<input type="text" name="login"><br>
<input type="password" name="pass">
<input type="submit">
</form>
PHP
$login = "citybank";
$pass = array("ticket3", "ticket2", "ticket1");
if(isset($_POST["login"])){
if($_POST["login"] == $login and $_POST["pass"] == $pass){
echo 'You are logged';
echo "
<script>
var post = document.querySelector('#login');
post.style.display = 'none';
</script>
";
}else{
echo "You are not logged.";
}
}
I think i have a problem with my array.
I dont know if its right the way i am using.
Thanks
First of all you have syntax error here:
$pass = array("ticket3", "ticket2, "ticket1"); // missing "
Also you searched for value in array, so you should use in_array():
<form id="login" method="post">
<input type="text" name="login"><br>
<input type="password" name="pass">
<input type="submit">
</form>
<?php
$login = "citybank";
$pass = array("ticket3", "ticket2", "ticket1");
if(isset($_POST["login"])){
if($_POST["login"] == $login and in_array($_POST["pass"], $pass)){
echo 'You are logged';
echo "
<script>
var post = document.querySelector('#login');
post.style.display = 'none';
</script>
";
}else{
echo "You are not logged.";
}
}
?>
Warning: Never, ever implement login logic like that, if it is for test it's OK, but on production environment is FORBIDDEN!
Here is example of login system which is secured.
You can use in_array() function to solve your issue.
But you should use database to store password.
php
$login = "citybank";
$pass = array("ticket3", "ticket2", "ticket1");
if(isset($_POST["login"])){
if($_POST["login"] == $login && in_array($_POST["pass"], $pass)){
echo 'You are logged';
echo "
<script>
var post = document.querySelector('#login');
post.style.display = 'none';
</script>
";
}else{
echo "You are not logged.";
}
}
<?php
$login = "citybank";
$pass = array("ticket3", "ticket2", "ticket1");
if(isset($_POST["login"]))
{
$count=0;
if($_POST["login"] == $login)
{
for($i=0;$i<3;$i++)
{
if($_POST["pass"] == $pass[$i])
{
{
$count=1;
echo 'You are logged';
echo "
<script>
var post = document.querySelector('#login');
post.style.display = 'none';
</script>
";
break;
}
}
}
if($count==0)
{
echo "You are not logged.";
}
}
}
?>
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";
}
}
For my application, there are three levels of users:
top level (00)
mid "district" level
lower level
The interface built allows users to create messages that will be distributed to a mobile app.
I had it working fine, but was then later tasked to add the mid-level. Now, even though the messages appear to update properly, I am encountering an issue that, instead of displaying "Message Updated" and the form after a message is submitted, I am receiving the "You do not have permission to access this page" message.
This does NOT occur with the mid/district level, only the lower and upper levels. Some reason, for these two, it is not properly reading $_SESSION['store'] after the form is submitted (though it works as expected when the page is loaded normally, not via POST).
I would greatly appreciate any guidance:
<?php
session_start();
function format($input) {
$input = trim($input);
$input = stripcslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$con = new PDO("sqlite:managers.db");
$store = $_SESSION['store'];
$stores;
$file;
$district;
$file = "messages/" . $store . ".txt";
if(!file_exists($file)) {
$temp = fopen($file, "w"); // create file
fclose($temp);
}
if(strpos("d", $store) == 0) {
$district = true;
$sql = "SELECT district FROM managers WHERE store = '$store'";
$statement = $con->query($sql);
$row = $statement->fetch();
$storesArray = explode(",", $row[0]);
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$newMessage = format($_POST['message']);
$writer = fopen($file, "w");
fwrite($writer, $newMessage);
fclose($writer);
if($district) {
foreach($storesArray as $store) {
$fileName = "messages/d" . $store . ".txt";
if(!file_exists($fileName)) {
$temp = fopen($fileName, "w"); // create file
fclose($temp);
}
$writer = fopen($fileName, "w");
fwrite($writer, $newMessage);
fclose($writer);
}
}
}
$handler = fopen($file, "r");
$currentMessage = fread($handler, filesize($file));
fclose($handler);
?>
// some code omitted //
<?php
if($store == "" || $store == null) {
echo "<p>You do not have permission to view this page</p>";
} else {
echo "<h2>Manage Messages"; if($store == "00") {
echo "<a href='admin.php'><input type='button' id='adminBack' value='Back' /></a></h2>";
} else {
echo "<a href='adminUI.php'><input type='button' id='adminBack' value='Back' /></a></h2>";
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h2>Message Updated!</h2>";
}
echo "<form class='admin' class='col-md-6' method='post' action='manageMessages.php'>
<div class='form-group'>
<label for='message'> Message: </label>
<textarea class='form-control' id='message' name='message' >$currentMessage</textarea>
<input type='submit' value='Post Message' />
</div>
</form>";
}
?>
</div>
<!-- end page specific content -->
The login page that sets the session:
<?php
session_start();
function format($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
};
$store; $pass; $valid;
echo "<script>function redirect() {
location.assign('manageMessages.php');
}
function adminRedirect() {
location.assign('admin.php');
}</script>";
if($_GET['logout']) {
session_unset();
session_destroy();
}
if($_SERVER['REQUEST_METHOD'] == "POST") {
if(!empty($_POST['store']) && !empty($_POST['pass'])) {
$store = format($_POST['store']);
$pass = format($_POST['pass']);
$con = new PDO("sqlite:managers.db");
$sql = "SELECT *FROM managers WHERE store = '$store' AND password = '$pass'";
$statement = $con->query($sql);
$rows = $statement->fetchAll();
$count = count($rows);
if($count != 1) {
$valid = false;
} else {
$valid = true;
}
}
else {
$valid = false;
}
}
?>
// excess code //
<?php
$location;
if($valid) {
$_SESSION['store'] = $store;
if($store == "00") {
echo "<script>setTimeout(adminRedirect(), 1);</script>";
} else {
echo "<script>setTimeout(redirect(), 1);</script>";
} } elseif ($valid === false) {
echo "<h3>Please enter a valid store/password combination!</h3>";
}
?>
<h2>Admin Login</h2>
<form class="admin" method="post" action="adminUI.php">
<div class="form-group">
<label for="store">Store Number: </label>
<input type="text" class="form-control" name="store" id="store" />
<label for="pass">Password:</label>
<input type="text" class="form-control" name="pass" id="pass" />
<input type="submit" value="Login" />
</div>
</form>
Your $store variable is being overwritten by your foreach:
foreach($storesArray as $store)
You must use a different name for that foreach, something like:
foreach($storesArray as $store2)
I am using this script : https://github.com/claviska/simple-php-captcha
To make a captcha in php.
I have this codes :
session_start();
include_once 'simple-php-captcha.php';
$_SESSION = array();
$_SESSION['captcha'] = simple_php_captcha();
$code = $_SESSION['captcha']['code'];
if (isset($_POST['username'])&&isset($_POST['password'])) {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($_POST['captcha'])&&!empty($_POST['captcha'])) {
$captcha = $_POST['captcha'];
if ($captcha == $code) {
echo "Login";
} else {
$errors[] = "Capcha is Not True.";
}
} else {
$errors[] = "Enter capcha.";
}
} else {
$errors[] = "Enter all.";
}
}
And HTML form :
<form accept="" method="POST">
username: <input type="text" name="username">
password: <input type="password" name="password">
captcha: <input type="text" name="captcha">
<img src="<?php echo $_SESSION['captcha']['image_src']; ?>">
<input type="submit" class="Button" value="submit">
</form>
BUT
The problem is that every time i enter the captcha and submit the form, the newer captcha will be generated and the form allways return NOT TRUE CAPTCHA pm.
For example i open the page, and the captcha for example is : 52111,
(i enter it correct) then i submit, then i see error that the captcha is incorrect, because the newer captcha generated is another one like : 48852.
I mean every time the page generate a newer one , How can i fix this problem??
You should save old captcha value, before check the form:
session_start();
if (!isset($_SESSION['captcha']) {
$_SESSION['captcha'] = simple_php_captcha();
}
$code = $_SESSION['captcha']['code'];
include_once 'simple-php-captcha.php';
if (isset($_POST['username'])&&isset($_POST['password'])) {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($_POST['captcha'])&&!empty($_POST['captcha'])) {
$captcha = $_POST['captcha'];
if ($captcha == $code) {
echo "Login";
} else {
$errors[] = "Capcha is Not True.";
}
unlink($_SESSION['captcha'])
} else {
$errors[] = "Enter capcha.";
}
} else {
$errors[] = "Enter all.";
}
}
add with JS some query string with current date in the chapacha so the image is deleted from the browser cahce:
$('img').prop('src',+"<?php echo $_SESSION['captcha']['image_src']; ?>?_="+new Date().valueOf())