I am trying to implement a basic user registration RESTful api.
I have a html form registerform.html, deregisterform.html, users.php, register.php and deregister.php which are all pasted below.
When i visit the registerform.html in my browser, i can fill in the details and a POST request is received by the users.php script and a json response is echoed back showing the id number of the user thats just been added.
My problem is that when i use the deregister form, the users.php script should recive a DELETE request, but is actually getting a GET request. I've been looking for an answer to this problem but im not finding a solution.
registerform.html
<form action="users.php" method="POST">
Username: <input type="text" name="uname" /><br />
FirstName: <input type="text" name="fname" /><br />
Last Name: <input type="text" name="lname" /><br />
Date of Birth: <input type="date" name="dob" /><br />
Telephone: <input type="mob" name="tel" /><br />
Email: <input type="email" name="email1" /><br />
Confirm Email: <input type="email" name="email2" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name ="pass2" /><br />
<input type="submit" value="Register" name="sub" />
<br/>Already Registered? Login Here<br/>
</form>
deregisterform.html
<form action="users.php" method="DELETE">
Username: <input type="text" name="uname" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name ="pass2" /><br />
<input type="submit" value="Deregister" name="sub" />
</form>
register.php
<?php
if(isset($_POST['uname']) && isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['tel']) && isset($_POST['dob']) &&
isset($_POST['email1']) && isset($_POST['email2']) && isset($_POST['pass1']) && isset($_POST['pass2']))
{
//take values from http POST and trim whitespace
$uname = trim($_POST['uname']);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$tel = trim($_POST['tel']);
$dob = trim($_POST['dob']);
$email1 = trim($_POST['email1']);
$email2 = trim($_POST['email2']);
$pass1 = trim($_POST['pass1']);
$pass2 = trim($_POST['pass2']);
//validate the data from the form
if($um->isNameFormatted($uname))
{
if(!$um->isUserExists($uname)) //does user already exist with this username?
{
if($um->isNameFormatted($fname)) //first name formatted correctly
{
if($um->isNameFormatted($lname)) //last name formatted correctly
{
if($um->isDOBFormatted($dob))
{
if($email1 == $email2)
{
if($pass1 == $pass2)
{
if($um->isPasswordClean($pass1))
{
if($um->isTelephoneVerified($tel))
{
//everything is OKAY --- PROCEED WITH ADDING USER
$user = $um->registerUser($uname,$fname,$lname,$dob,$tel,$email1,$pass1);
if(isset($user))///
{
//successful registration
$response["error"] = false;
$response["id"] = $user;
echo json_encode($response);
}
}
}
}
}
}
}
}
}
}
}?>
deregister.php
<?php
if(isset($_POST['uname']) && isset($_POST['pass1'] && isset($_POST['pass2'])
{
$uname = $_POST['uname'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($um->isUserExists($uname))
{
if($pass1 == $pass2)
{
if(true)//$um->isPasswordFor($uname, $pass))
{
$um->deregisterUser($uname, $pass1);
$response["error"] = false;
$response["text"] = "User removed!";
echo json_encode($response);
}
else
{
$response["error"] = true;
$response["text"] = "Wrong username and password combination!";
echo json_encode($response);
}
}
else
{
$response["error"] = true;
$response["text"] = "Passwords don't match!";
echo json_encode($response);
}
}
else
{
$response["error"] = true;
$response["text"] = "User(".$uname.") not in database!";
echo json_encode($response);
}
}?>
users.php
<?php
error_reporting( -1 );
require('userManagement.php');
$um = new UserManagement();
$response = array("error" => FALSE);
//check if user logged in and authenticated
if(true)
{
echo "user logged in.";
echo $httpVerb = trim(strtoupper($_SERVER['REQUEST_METHOD']));
switch($httpVerb)
{
case "GET":
$response["error"] = false;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
case "PUT":
$response["error"] = false;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
case "POST":
include('register.php');
break;
case "DELETE":
include('deregister.php');
break;
default:
echo "http verb ".$httpVerb." is not supported for this resource.";
$response["error"] = true;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
}
}
else
{
echo "need to login first.";
}?>
Any ideas what i'm doing wrong?
You can't use DELETE as a form action.
From the specs, we have:
The method and formmethod content attributes are enumerated attributes
with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET method.
The keyword post, mapping to the state POST, indicating the HTTP POST method.
The invalid value default for these attributes is the GET state.
Related
This is my registration form I am using both javascript and php for validating form, javascript code works well in showing validation error messages however somethings wrong with php code,when javascript is disabled php code should show form validation error messages by refrshing page on form submit,but no error messages appear and no data is inserted. On clicking submit, page is reloaded but even form does not appear.
<?php
error_reporting('E_ALL ^ E_NOTICE');
if(isset($_POST['reg'])){
$fn = ucfirst($_POST['fname']);
$ln = ucfirst($_POST['lname']);
$un = $_POST['username'];
$em = $_POST['email'];
$pswd = $_POST['password'];
$d= date("Y-m-d");
if (strlen($fn) < 2 || strlen($fn) > 15) {
$error = "First name must be 2 to 15 characters long";
}
elseif (strlen($ln) < 2 || strlen($ln) > 15) {
$error = "Last name must be 2 to 15 characters long";
}
elseif($em==""){
$error = "Email cannot be empty";
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format";
}
elseif($pswd==""){
$error = "Fill your password";
}
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
}
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
?>
<form action="" method="post">
<input type="text" name="fname" id="fn" placeholder="First Name"/><br />
<input type="text" name="lname" id="ln" placeholder="Last Name"/><br />
<input type="text" name="username" id="un" placeholder="Username" class="username" /><br />
<input type="email" name="email" id="em" placeholder="Email"/> <br />
<input type="password" name="password" id="pswd" placeholder="Password"/><br />
<input type="password" name="password2" id="pswd2" placeholder="Confirm Password"/><br />
<input type="submit" id="submit" name="reg" value="Create an Account">
<center><div id="er"><?php echo $error ?></div></center>
</form>
You should echo $error not $er
<center><div id="er"><?php echo $error; ?></div></center>
You are doing a mistake:
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
You should use 'username' instead of ':username'. like this:
$stmt->execute(array('username'=>$un,'firstname'=>$fn,'lastname'=>$ln,'email'=>$em,'password'=>$pswd));
There are a few inconsistencies in your code.
At the beginnig you assign $_POST['email'] to $em, but later you validate against a variable named $email, which doesn't exist at this point.
$em = $_POST['email'];
.
.
.
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format"; //should maybe be $error
}
Then there is the password-validation:
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
$pswd2 has never been defined in your code.
$stmt ist defined in the else-block of your validation, but you use it for getting the row-count after the validation. So, if any of your if-statements is true, this will cause an error.
It would be better if you change that part of your code to this:
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
After all it seems like you haven't error reporting activatet.
Hey I have some trouble with my email subscription I'm trying to log into a textfile.
<!-- Signup Form -->
<form id="signup-form" action="form.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="submit" value="Sign Up" />
</form>
Here's my PHP code:
<?php
if(empty($_POST['submit']) === false) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
if(strpos($logcontents,$email)) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
}
?>
I keep getting Cannot POST /form.php eventho the php file is at that path, someone knows what I'm possibly doing wrong? I'm quit noob at this :(
First of all add name attribute to your submit button, as in POST you will not get the form value of "submit" and your code will never go further
<form id="signup-form" action="form.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="submit" name="submit" value="Sign Up" />
</form>
Now in your php code, you just need to check $_POST['submit'] in if condition and you have also done a typo, you have used a variable $fopen which is not defined, change that.
<?php
if($_POST['submit']) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
if(strpos($logcontents,$email)) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
}
?>
i am trying to make the user show when i click browse in phpmyadmin in localhost. i created a table called test. i am trying, when you sign up, it shows the user in the database and signs him or her up, but it does not using this code:
hoping.php:
<?php
$reg = #$_users['reg'];
$fn = "";
$ln = "";
$un = "";
$em = "";
$em2 = "";
$pswd = "";
$pswd2 = "";
$d = "";
$u_check = "";
$fn = strip_tags(#$_test['fname']);
$ln = strip_tags(#$_test['lname']);
$un = strip_tags(#$_test['username']);
$em = strip_tags(#$_users['email']);
$em2 = strip_tags(#$_users['email2']);
$pswd = strip_tags(#$_users['password']);
$pswd2 = strip_tags(#$_users['password2']);
$d = date("Y-m-d");
if ($reg) {
if ($em == $em2) {
$u_check = mysql_query("SELECT username FROM users WEHRE username='$un'");
$check = mysql_num_rows($u_check);
if ($check == 0) {
if ($fn && $ln && $un && $em && $em2 && $pswd && $pswd2) {
if ($pswd == $pswd2) {
if (strlen($un) > 25 || strlen($fn) > 25 || strlen($ln) > 25) {
echo "The maximum limit for username/first name/last name is 25 characters!";
} else {
if (strlen($pswd) > 30 || strlen($pswd) < 5) {
echo "Your password must be between 5 and 30 characters long!";
} else {
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = mysql_query("INSERT INTO users VALUES ('', '$un', '$fn', '$ln','$em', '$pswd', '$d','0')");
die("<h2>Welcome to communicate</h2>Login to your account to get started ...");
}
}
} else {
echo "Your passwords don't match!";
}
} else {
echo "Please fill in all of the fields";
}
} else {
echo "Username already taken ...";
}
} else {
echo "Your E-mails don't match!";
}
}
if (isset($_users["user_login"]) && isset($_users["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_users["user_login"]);
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_users["password _login"]);
}
?>
<div style="width: 800px; margin: 0px auto 0px auto;">
<table>
<tr>
<td width="60%" valign="top">
<h2>Already a member? Sign in below!</h2>
<form action="hoping.php" method="users">
<input type="text" name="username" size="25" placeholder="Username"/><br /><br />
<input type="text" name="Password2" size="25" placeholder="Password (again)"/><br /><br />
<input type="submit" name="reg" value="Sign Up!">
</form>
<td>
<td width="40%">
<h2>Sign Up Below!</h2>
<form action="hoping.php" method="users">
<input type="text" name="fname" size="25" placeholder="First Name" />
<p />
<input type="text" name="lname" size="25" placeholder="Last Name"/><br /><br />
<input type="text" name="username" size="25" placeholder="username"/><br /><br />
<input type="text" name="email" size="25" placeholder="Email Address"/><br /><br />
<input type="text" name="email2" size="25" placeholder="Email Address (again)"/><br /><br />
<input type="text" name="password" size="25" placeholder="Password"/><br /><br />
<input type="text" name="Password2" size="25" placeholder="Password (again)"/><br /><br />
<input type="submit" name="reg" value="Sign Up!">
</td>
</tr>
</table>
<?php include ("./connect.inc.php");
connect.inc.php
<?php
mysql_connect("localhost", "root", "") or die("Couldnt conocet to server");
mysql_select_db("test") or die("Could'nt select DB");
?>
Ok so here's the improved script. Please make sure you read all the comments and correct stuff where needed as this is NOT ready-to-use code!
Change your connect.inc.php to (please make sure you fill in all the nessesary information):
<?php
$dbhost = ""; //MySQL host (usually: localhost)
$dbuser = ""; //MySQL user
$dbpass = ""; //MySQL password
$dbname = ""; //MySQL database name
$pdo = new PDO("mysql:host=".$dbhost.";dbname=". $dbname, $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Change hoping.php to:
<?php
require "connect.inc.php";
/*
Using md5 to encrypt a password is not secure.
I've written a much more secure function for password encryption.
However this requires your database to have enough room for it.
For example: `password` VARCHAR(128) NOT NULL
If you need to alter your database to make the room, please
execute this command in phpMyAdmin (change password to whatever
the column name is in your users table):
ALTER TABLE `users` MODIFY COLUMN `password` VARCHAR(128);
If your database has the room for this, please set the following
variable to true. Otherwise leave it false to keep using md5.
*/
$secureCrypt = false;
if(isset($_POST['login'])){
$sql = "SELECT * FROM users WHERE username = :user";
$pre = $pdo->prepare($sql);
$pre->bindValue(":user", $_POST['Username']);
if($pre->execute()){
$data = $pre->fetch();
if($secureCrypt){
//Please correct 'column_name_here'.
//I was unable to do this for you because I lacked the column name
//where the passwords are stored.
if(crypt($_POST['Password'], $data['column_name_here']) == $data['column_name_here']){
echo "You have succesfully logged in!<br />";
} else {
echo "Invalid password!<br />";
}
} else {
if(md5($_POST['Password']) == $data['column_name_here']){
echo "You have succesfully logged in!<br />";
} else {
echo "Invalid password!<br />";
}
}
} else {
echo "\nMySQL returned error:\n";
print_r($pdo->errorInfo());
}
}
if(isset($_POST['register'])){
$error = false;
$error_text = "";
//Check names for illegal characters
// Allows A-Z, a-z, underscore( _ ), dots( . ), spaces and dashes( - )
function nameRegex($var){
if(!preg_match("/^[a-zA-Z_\. \-]+$/i", $var)){
return true;
} else {
return false;
}
}
//Check names for illegal characters
// Allows A-Z, a-z, underscore( _ ), dots( . ) and dashes( - )
function userRegex($var){
if(!preg_match("/^[0-9a-zA-Z_\-]+$/i", $var)){
return true;
} else {
return false;
}
}
//Check for valid mail address
function mailFilter($var){
if(filter_var($var, FILTER_VALIDATE_EMAIL) === false){
return true;
} else {
return false;
}
}
//Check if 2 values match
function matchValues($var1, $var2){
if($var1 != $var2){
return true;
} else {
return false;
}
}
//Check if username already exists
function checkUser($user){
$sql = "SELECT username FROM users WHERE username = :user";
$pre = $pdo->prepare($sql);
$pre->bindValue(":user",$user);
if($pre->execute()){
$count = $pre->rowCount();
if($count > 0){
return true;
} else {
return false;
}
} else {
echo "\nMySQL returned error:\n";
print_r($pdo->errorInfo());
}
}
//Check for correct size
function checkSize($var, $size){
if(strlen($var) > $size){
return true;
} else {
return false;
}
}
//Securely encrypt user passwords
function cryptPass($pass, $rounds = 9){
$salt = "";
$saltChars = array_merge(range('A','Z'), range('a','z'), range(0,9));
for($i=0;$i<22;$i++){
$salt .= $saltChars[array_rand($saltChars)];
}
return crypt($pass, sprintf('$2y$%02d$', $rounds) . $salt);
}
if(nameRegex($_POST['fname'])){
$error = true;
$error_text .= "Your First Name contains illegal characters!<br />";
}
if(nameRegex($_POST['lname'])){
$error = true;
$error_text .= "Your Last Name contains illegal characters!<br />";
}
if(userRegex($_POST['username'])){
$error = true;
$error_text .= "Your Username contains illegal characters!<br />";
}
if(mailFilter($_POST['email'])){
$error = true;
$error_text .= "Your Email Address does not appear to be valid!<br />";
}
if(mailFilter($_POST['email2'])){
$error = true;
$error_text .= "Your 2nd Email Address does not appear to be valid!<br />";
}
if(matchValues($_POST['email'], $_POST['email2'])){
$error = true;
$error_text .= "It appears both Email Addresses did not match!<br />";
}
if(matchValues($_POST['password'], $_POST['password2'])){
$error = true;
$error_text .= "It appears both Passwords did not match!<br />";
}
if(checkUser($_POST['username'])){
$error = true;
$error_text .= "The Username is already taken by another user!<br />";
}
if(checkSize($_POST['fname'], 25)){
$error = true;
$error_text .= "The First Name contains to many characters!<br />";
}
if(checkSize($_POST['lname'], 50)){
$error = true;
$error_text .= "The Last Name contains to many characters!<br />";
}
if(checkSize($_POST['username'], 16)){
$error = true;
$error_text .= "The Username contains to many characters!<br />";
}
if(checkSize($_POST['username'], 125)){
$error = true;
$error_text .= "The Email address contains to many characters!<br />";
}
if(!$error){
if($secureCrypt){
$hashPass = cryptPass($_POST['password']);
} else {
$hashPass = md5($_POST['password']);
}
$sql = "INSERT INTO users VALUES ('',':username',':fname',':lname',':email',':password',':date','0')";
$pre = $pdo->prepare($sql);
$pre->bindValue(":username",$_POST['username']);
$pre->bindValue(":fname",$_POST['fname']);
$pre->bindValue(":lname",$_POST['lname']);
$pre->bindValue(":email",$_POST['email']);
$pre->bindValue(":password",$_POST['password']);
$pre->bindValue(":date",date("Y-m-d"));
if($pre->execute()){
echo "You are succesfully registered. Welcome!";
} else {
echo "\nMySQL returned error:\n";
print_r($pdo->errorInfo());
}
} else {
echo "There are some problems with your registration.<br />";
echo "Please correct the following errors:<br /><br />";
echo $error_text;
echo "<br />";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login Page</title>
<style>
#div1 {
width: 800px;
margin: 0px auto 0px auto;
}
#td1 {
width: 60%;
vertical-align: top;
}
#td2 {
width: 40%;
}
</style>
</head>
<body>
<div id="div1">
<table>
<tr>
<td id="td1">
<h2>Already a member? Sign in below!</h2>
<form action="hoping.php" method="post" id="user_login" accept-charset="utf-8">
<input type="text" name="username" size="25" placeholder="Username"/><br /><br />
<input type="password" name="Password" size="25" placeholder="Password"/><br /><br />
<input type="submit" name="login" value="Login!">
</form>
</td>
<td id="td2">
<h2>Sign Up Below!</h2>
<form action="hoping.php" method="post" id="user_register" accept-charset="utf-8">
<input type="text" name="fname" size="25" placeholder="First Name" value="<?php echo $_POST['fname'] ?>" /><br /><br />
<input type="text" name="lname" size="25" placeholder="Last Name" value="<?php echo $_POST['lname'] ?>" /><br /><br />
<input type="text" name="username" size="25" placeholder="username" value="<?php echo $_POST['username'] ?>" /><br /><br />
<input type="text" name="email" size="25" placeholder="Email Address" value="<?php echo $_POST['email'] ?>" /><br /><br />
<input type="text" name="email2" size="25" placeholder="Email Address (again)" value="<?php echo $_POST['email2'] ?>" /><br /><br />
<input type="text" name="password" size="25" placeholder="Password"/><br /><br />
<input type="text" name="password2" size="25" placeholder="Password (again)"/><br /><br />
<input type="submit" name="register" value="Sign Up!">
</form>
</td>
</tr>
</table>
</div>
</body>
</html>
thanks for reading.
I have an issue getting an error to echo on the correct page after a form submit. When the form is submitted, it redirects to website.com/controllers/accountController.php. I would like it to refresh the current page, website.com/play.php?p=myaccount
Please note that the form is submitting, it is just printing the error on the redirected page instead of the page with the form.
Please take a look at my previous question (related, but different question altogether).
HTML form (myaccount.inc.php):
<div id="change-password">
<form class="clearfix" action="controllers/accountController.php" method="post">
<div><span class="he1">Change Password</span></div>
<div><label class="DEVON" for="password">Current Password:</label></div>
<input type="password" name="password" id="password" size="23" /><br />
<div><label class="DEVON" for="passwordnew1">New Password:</label></div>
<input type="password" name="passwordnew1" id="passwordnew1" size="23" /><br />
<div><label class="DEVON" for="passwordnew2">Confirm New Password:</label></div>
<input type="password" name="passwordnew2" id="passwordnew2" size="23" /><br />
<input type="submit" name="submit" value="Change Password" class="bt_changepass" />
</form>
</div>
PHP code (accountController.php):
<?php
// Checking whether the Password Change form has been submitted.
if(isset($_POST['submit'])=='Change Password')
{
echo "<br />";
// Get the data from the database.
$sql = $mysqli->query("SELECT * FROM ss_members WHERE usr = '".$_SESSION['usr']."' AND pass = '".md5($_POST['password'])."'");
$row = $sql->fetch_assoc();
// Will hold our errors
$err = array();
if($_POST['password'] == "" || $_POST['passwordnew1'] == "" || $_POST['passwordnew2'] == "")
{
$err[] = 'All the fields must be filled in!';
}
if(!$row['pass'] == md5($_POST['password']) && $_POST['passwordnew1'] != "" && $_POST['passwordnew2'] != "")
{
$err[] = 'Current password is not correct!';
}
if($_POST['passwordnew1'] <> $_POST['passwordnew2'])
{
$err[] = 'New passwords do not match!';
}
if(!count($err))
{
if($row['usr'])
{
// If everything is OK change password.
$stmt = $mysqli->prepare("UPDATE ss_members SET pass = md5(?) WHERE usr = {$_SESSION['usr']}");
$stmt->bind_param('s', $_POST['passwordnew1']);
$stmt->execute();
$stmt->close();
echo "Password has been sucessfully updated!<br />";
}
else
{
$err[]='Something broke!';
}
}
if($err)
{
// Save the error messages in the session.
foreach($err as $error)
{
echo $error . "<br />";
}
}
echo "<br />";
}
if(isset($_POST['submit'])=='Change Password') statment is wrong.
Because isset always return Boolean so your if won't execute ever.
OR
You can use it as
if(isset($_POST['submit']) && $_POST['submit'] =='Change Password')
if(isset($_POST['submit'])=='Change Password')
isset returns true of false when comparing it with the change password will return false
Regards.
if(isset($_POST['submit'])=='change Password')
this usage is not valid in php
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>" />
Username:<input type = "text" name ="user"> <br />
Password:<input type = "password" name = "pass"><br />
<input type = "submit" value ="View Logs!"><br />
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
//Problem here, I need to only allow the user to see logs
// after he or she has entered the correct info.
//Currently code just shows all, when the user hits View Logs
// without any credentials
if (($user == "php") && ($pass == "student"))
echo "Enjoy the Logs!";
else echo "<b>Access Denied!</b>";
?>
The problem is that your form is posting directly to log.txt and not processing any of your PHP after the form submission. You'll need to change the action to post to the PHP file itself and then use http_redirect to redirect the user to log.txt after checking the password.
Having said that it's still not going to be very secure though as anyone could get to log.txt by using a direct URL, so you'll need to do some kind of authorisation there. The best thing to do is probably to store log.txt somewhere that's not accessible by through HTTP and then load and display the file using readfile in place of your echo:
<form action="" method="post">
Username:<input type="text" name="user"/> <br />
Password:<input type="password" name="pass"/><br />
<input type="submit" value="View Logs!"/><br />
</form>
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if (($user == "php") && ($pass == "student")) {
echo '<pre>';
readfile('log.txt');
echo '</pre>';
}
else {
echo "<b>Access Denied!</b>";
}
?>
<?
if (
isset( $_POST['user'] )
&& isset( $_POST['pass'] )
) {
$user = $_POST['user'];
$pass = $_POST['pass'];
if (
($user == 'php')
&& ($pass == 'student')
) {
echo "Enjoy the Logs!";
readfile('log.txt');
}
else {
echo '<b>Access Denied!</b>';
}
} else {
?>
<form method="post">
Username:<input type="text" name="user"> <br />
Password:<input type="password" name="pass"><br />
<input type="submit" value="View Logs!"><br />
<?
}