mistake in post method - php

So mistake in POST, I tried sent the variable login thought load, but when I tried receive it in sea.php it is give me mistake.
js code :
$(document).on('click','#sea_submit', function () {
var login = $("input[name=log]").val();
if (login != "")
{
$("#din_content").load("sea.php", {login:login});
return false;
}
});
php code:
$login=stripslashes(strip_tags($_POST['login'])); //mistake here
// I tried and like that $login = $_POST['login'];
if ((isset($login)) && (!empty($login)))
{
$result=mysql_query("SELECT * FROM users WHERE Login='$login'",$db);
if (empty($result))
{
printf("The user with login=".$login." not found");
}
else
{
$row=mysql_fetch_result($result);
//code
}
}
Html code:
<form>
<div id="sea_cr_login">
<h2 class="sea_names">Login:</h2>
<div>
<div class="sea_labels">
<label class="sea_var">Login:</label>
<input class="sea_ch" name="log" type="text" maxlength="16" size="10">
</div>
</div>
</div>
<div class="cleaner"></div>
<div id="sea_sub">
<input type="submit" value="sea" id="sea_submit">
</div>
</form>

You have (prior to the OP's edit) mis-matched variable names. You're sending login_sch so you have to change this line:
$login=stripslashes(strip_tags($_POST['login_sch'])); //mistake here
Ideally you should change the line to use mysql_real_escape_string() as it is much more effective than the two nested functions you have now:
$login = mysql_real_escape_string($_POST['login']);
Your script is at risk for SQL Injection which needs to be fixed as soon as possible.
If you can, you should stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO, it's really not hard.
If you're set on building your own login system you should start with having the proper basics in place - Use the proper methods to hash passwords with PHP.

Related

How do I get my $_POST to recognize the values

$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
$_Get methods do not work because of how the login system is built and unsecured.I need mailuid value to bring them to their own profiles page after login.
Login Form since its's post method I should be able to grab the value on other pages and this one
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
Temporary check for the mailuid value. Supposed to grab the value form the login form a spit it back out, to check to see if it is recognized
<?php
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
?>
First I would clean this up:
$user = $_POST["mailuid"];
if (isset($_POST["mailuid"]))
{
$user = $_POST["mailuid"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
Instead it can be written more concise:
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
if( $user ){
echo "{$user} is your username";
} else {
echo "no username supplied";
}
I prefer Boolean false over NULL, null just means it doesn't exist. Boolean false lets you know you checked it and it didn't exist. Generally should should access $_POST as few times as you can. This is because you should never trust $_POST.
$_Get methods do not work because of how the login system is built and unsecured.
Post is no more secure than get, it's quite easy to post anything to the page even without visiting the site by using something like PostMan etc. Once you assign it to a local variable you know you have at least normalized the data, even if you haven't sanitized it yet.
Also don't forget to call session_start before trying to access $_SESSION. Because of the vagueness of the question, it could be that the form works fine, just the session data isn't being maintained because you haven't started the session yet.. etc....
Hope it helps.
Personally I would clean up the HTML part that makes the form as well, so instead of this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php
if (!isset($_SESSION['Id'])) {
echo'<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>';
} else if (isset($_SESSION['Id'])) {
echo '<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
}
?>
</section>
</div>
</div>
I would do something like this:
<div class="modal">
<div class = "modal-content">
<section class="section-default">
<h1>Login</h1>
<?php if (!isset($_SESSION['Id'])){ ?>
<form action="includes/login.inc.php" method="post">
<input type="text" name="mailuid" placeholder="Username/E-mail...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="login-submit">Login</button>
</form>
<?php }else{ ?>
<div class="signup12">
You Do not have an account? Sign Up
</div>
<div class="forgotpwd">
Forgot your password?
</div>';
<?php } ?>
</section>
</div>
</div>
See how much cleaner that is. Most of this is just readability issues. For example there is no need to check if isset($_SESSION['Id']) in the else if condition, because it's either set or not. This is one less place to maintain the session variable key, and it makes the code less convoluted.
As for the actual problem, as long as you are reaching the above code after submission of the form, it should work. So that leads me to believe that you have something wrong in the action.
You should get a clean page after going to includes/login.inc.php meaning there shouldn't be much in the way of HTML. One thing you can do that is real simple is just add at the top:
die(__LINE__.' of '.__FILE__);
$user = isset($_POST["mailuid"]) ? $_POST["mailuid"] : false;
//... other code
What this will do is die which kills PHP execution, but outputs the argument you passed in. In this case I'm just putting the line and file that the die is on, that way it's easier to find later. But the point is to see if you are even hitting the correct ending script or the forms action/endpoint.
I only suggest this because you are really vague in what it's current behaviour is
$_POST won't recognize the value mailuid from the login form on this page or others (profile page).
For example, this doesn't tell me if you are even hitting the right page. Now had you said something like "all it does is output no username supplied". Then I would at lest know that. As I said above it could be just an omission of sesion_start() which must be called before attempting to access any $_SESSION stuff. You should call it only once, at the top of each page that uses sessions.
Although it's not a solution, it was too much to post in a comment. I would really like to help you more, but there just isn't enough information to go on.

html entities in a PHP code

I have a homework and it's a webpage (log-in page) and the task is to enter and bypass the login forum, well the first thing I have looked into was the page's source and I found that if I want the username I should go to /page.phps directory and I did that. After entering that directory I was redirected to another page with this piece of code
<?php
$super_admin_access = false;
// Set our super-admin level user?
if (isset($_GET['user'])) {
$user = html_entity_decode($_GET['user']);
if ($user === "<root>") {
$super_admin_access = true;
}
}
?>
<div class="logo"><img src="../assets/images/challenge-priserv-logo.svg" alt="Nethub logo"></div>
<div class="login">
<form class="form" onsubmit="doLogin(); return false">
<div class="message message-error" id="login-error-msg" style="display: none">Denied!</div>
<div class="field">
<div class="label">Username</div>
<input type="text" name="username">
</div>
<div class="field">
<div class="label">Password</div>
<input type="password" name="password">
</div>
<!-- In case I forget, details are at page.phps -->
<div class="actions">
<input type="submit" value="Access server" class="btn">
</div>
</form>
</div>
I don't know if I understand the php code in the right way, but what I firstly though of was writing the "<root>" in a html entity format which become "<root>", especially that there was a hint saying
Did you see the comment in the source code suggesting you take a look at page.phps? Take a look. What does urldecode do? Can you do the opposite of urldecode?
So I tried to login using the username "<root>" or the encoded one "<root>" I tried removing the quota but no luck, I don't know if there is a password or something like that, I would appreciate any help given, thanks :).
Form's input's name is username, but it checks for user. To get access to the super-duper-mega admin powers, pass a query parameter in the url
http://yoururl/page.php?user=<root&gt
Seeing as this is a piece of homework I won't give a direct answer, but rather point you in the right direction.
You are definitely on the right track, but you seem to have gotten a little confused with how PHP handles strings.
Let me give you an example. We go to the page login.php?user=tom.
<?php
$user = $_GET['user'];
$desiredUsername = "tom";
if ($user === $desiredUsername) {
echo "You're in!";
}
Let's take a look at the check that if() is doing in this case.
$desiredUsername === "tom"; // true
$desiredUsername === "frank"; // false
$desiredUsername === "jonas"; // false
When you are setting the $user variable in your code, you are wrapping <root> with quotes like so.. "<root>". While the PHP code checks to see if $user === "<root>", the quotes in this case are actually just specifying that we want to see if $user contains the string <root>.
Test your method of using the encoded entities "<root>" with and without the quotes on either side and see what happens.
First it's must be $_GET['username'] NOT $_GET['user'] because input field name is is "username" not "user"

undefined index error while trying to get value returned from the link?

I know its a duplicate one but i'm getting this error while trying to fetch data passed from a link..I dont know how to resolve it.
here is my code:
add_package.php
echo "<td><a href='delete.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Delete</a></td>";
echo "<td><a href='edit_package.php?name3=" . $row['package_type']."&id3=".$row['p_id']."'>Update</a></td>";
here the delete link works perfectly but when i click update it takes to the edit_package page where i'm getting an undefined error..
code for edit_package.php:
<?php
include('db.php');
$id4 = $_GET['id3'];//update the page
$name4 = $_GET['name3'];//helps to update the package
echo $id4;
echo $name4;//getting values here correctly..
if(isset($_POST['submit']) )
{
$package=$_POST['package'];
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
$retvali=mysql_query($sql13,$conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
$retval = mysql_query( $sql, $conn );
?><script>alert("Updated Successsfully");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
else
{
?><script>alert("Already Exists");window.location ='http://localhost/demo/add_package.php';
</script><?php
}
}
else
{
?><script>alert("enter only letters and numbers")</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<form id="form-validation" action="edit_package.php" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
<div class="col-md-6">
<div class="block" style="height:500px;">
<div class="block-title">
<h2><strong>State the Package For Tour</strong></h2>
</div>
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="val_username">Update Package <span class="text-danger">*</span></label>
<div class="col-md-6">
<div class="input-group">
<input type="text" id="package" name="package" class="form-control" required >
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
</div>
<div class="form-group form-actions">
<div class="col-md-8 col-md-offset-4">
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</div>
</div>
</fieldset>
</form>
When i press update button i'm getting an undefined error i dont know why?..Thanks in advance
I'm attaching an image to it..
Try to change the <form>'s action URL to include your GET varaibles:
<form id="form-validation" action="edit_package.php?id3=<?php echo $_GET['id3']; ?>&name3=<?php echo $_GET['name3']; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" novalidate="novalidate">
PLEASE NOTE: This is extremely unsafe! You need to sanitize ALL user input before using it. My example above, dis-regards security, and simply is to demonstrate my point. GET and POST data, are user variables. A malicious user could put bad code in the URL (ie ?name3=<badcode>) and it would be printed on the page, well in the source code, which they could easily pop out of. Also, in SQL queries, you need to escape the data or use prepared statements.
You should not be using mysql functions, switch to MySQLi or PDO. MySQL has been killed for a while now..
These are just asking for you to get hacked:
$sql13="select package_type,id from tbl_package where package_type='".$package."'";
and..
$sql = "Update tbl_package set package_type='".$package."' where package_type='".$name4."' and p_id='".$id4."'";
You are vulnerable to SQL injections, would could easily allow a malicious attacker to add/edit/view/delete data in your database.
The problem is, you have $package (which is raw data from POST) and $id4 and $name4 (which is raw data from GET) in your SQL query.
You would use mysql_real_escape_string() on them, but you should be using mysqli or PDO anyways...
Example:
$name4 = mysql_real_escape_string($_GET['name3']);
It's confusing, I don't know what the GET variable is called name3 but you assign it the variable $name4.. Whoever (even you) comes along later on will be lost in your code.
Updated:
Try this code. I swapped your GET for POST in your php code, and passed the GET variables from your URL as hidden fields in your form.
<?php
include('db.php');
if(isset($_POST['submit']) )
{
$package = mysql_real_escape_string($_POST['package']);
$id4 = mysql_real_escape_string($_POST['id3']); // why is variable named id4 but its id3??
$name4 = mysql_real_escape_string($_POST['name3']); // why is variable $name4 but its name3??
if (ctype_alnum($package) && !empty($id4) && !empty($name4))
{
$sql13 = "SELECT package_type,id FROM tbl_package WHERE package_type='$package' LIMIT 1";
$retvali = mysql_query($sql13, $conn);
$num_rows1 = mysql_num_rows($retvali);
if ($num_rows1 == 0 || $num_rows1=="")
{
$sql = "Update tbl_package set package_type='$package' WHERE package_type = '$name4' AND p_id='$id4'";
$retval = mysql_query( $sql, $conn );
echo '<script>alert("Updated Successsfully");window.location = "http://localhost/demo/add_package.php";</script>';
} else {
echo '<script>alert("Already Exists"); window.location = "http://localhost/demo/add_package.php";</script>';
}
} else {
echo '<script>alert("enter only letters and numbers");</script>';
}
}
?>
<form action="edit_package.php" method="post" enctype="multipart/form-data" novalidate="novalidate">
<input type="hidden" name="id3" value="<?php echo htmlspecialchars($_GET['id3'], ENT_QUOTES | ENT_HTML5); ?>" />
<input type="hidden" name="name3" value="<?php echo htmlspecialchars($_GET['name3'], ENT_QUOTES | ENT_HTML5); ?>" />
Update Package: <input type="text" id="package" name="package" class="form-control" required >
<input type="submit" class="btn btn-info btn-primary " value="Update" name="submit">
</form>
I removed your HTML formatting from the form. You had div tags that didn't match up.. I can't see your whole code, but it looks like you have a bunch of div's that are messed up (ie: not closed where they should be). I also added mysql_real_escape_string() to the passed variables, and htmlspecialchars() to the GET variables echo'd in the hidden fields of your form. It's a start.
You might be able to make better sense of your code and troubleshoot errors, if you wrote your code a bit cleaner. Not trying to bash you :) Proper indentation, spacing, and formatting go a long way. It makes it easier on your eyes, and on yourself, in times like these..
I left your <script> tags because I assumed there was a reason your wanted to popup a message box.. I would just use header('Location: /path/to/where.php'); and pass your error message through a session variable or something, like an array of errors, which you get, clear, and show on the page the errors.

Php code symbols escaped after execution (Sublime editor)

I am aware that this might be a question with an obvious answer but I for a php-newbie it is SO not!
I am writing php code with Sublime inside a file together with html and after I execute the files my code changes. The <and > is written with its escaping characters. Help..please..
<?php
$username= trim($_POST['username']);
$pass= trim($_POST['pass']);
$userExist= trim($_POST['userExist']);
$passExist= trim($_POST['passExist']);
// print_r($username);
// print_r($pass);
$conn= mysqli_connect('localhost','neli','','yogies');
// if(!$conn){
// echo "No database";
// exit;
// }else {
// // echo "Done";
// // }
if(isset($username) && isset($pass)){
$usernameCheck = mysqli_query($conn, 'SELECT username FROM users WHERE username="'.$username.'"');
// print_r('SELECT username FROM users WHERE username="'.$username.'"');
if( $usernameCheck && $usernameCheck->num_rows ){
$check= 1;
} else {
$check=0;
}
}
if($check==0){
$userToEnter =$username;
$userToEnter = mysqli_real_escape_string($conn, $userToEnter);
$passToEnter = $pass;
$passToEnter = mysqli_real_escape_string($conn, $passToEnter);
$sql = 'INSERT INTO users (username,password) VALUES ("'.$userToEnter.'","'.$passToEnter.'")';
// print_r($sql);
if(mysqli_query($conn, $sql)){
session_start();
// print_r('here');
// print_r($_POST['url']);
$doc = new DOMDocument();
// html5 problems with tags
// libxml_use_internal_errors(true);
$doc->loadHTMLFile('header_nav.php');
// html5 problems with tags
// libxml_clear_errors();
$doc->getElementById('sign')->setAttribute('display','none');
$doc->getElementById('logout')->setAttribute('display','block');
$doc->saveHTMLFile('header_nav.php');
// header('Location: '.$_POST['url']);
}
}else{
print_r('Nope');
}
?>
<!DOCTYPE html>
<html class="wallpaper">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./styles/css.css">
<title><?php echo $pageTitile ?></title>
</head>
<body>
<header><div class="top">
<img src="./pictures/logo.png" height="80px" width="80px">
Log in
Log out
<nav><ul><li>Yoga Poses</li>
<li class="subList">
<span id="levels">Yoga Levels <img id="arrow" src="./pictures/arrow.png"></span>
<ul class="dropdown"><li>All levels</li>
<li>Level 1</li>
<li>Level 2</li>
<li>Level 3</li>
<li>Level 4</li>
</ul></li>
<li>Healthy and Delicious</li>
</ul></nav></div>
<div id="overlay">
<div id="background"></div>
<form id="loginForm" name="login" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<!-- <input type="hidden" name="url" value="<?php echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>"> -->
<fieldset id="bordered"><legend>Register:</legend>
<p>Username:<input type="text" name="username"></p>
<p>Password:<input type="password" name="pass"></p>
<p>Repeat pass:<input type="password" name="pass2"></p>
</fieldset><fieldset><legend>Log in:</legend>
<p>Username:<input type="text" name="userExist"></p>
<p>Password:<input type="password" name="passExist"></p>
</fieldset><div class="btns">
<button id="btnSubmit" class="btn" type="button" value="Submit">Submit</button>
<button class="btn" type="button" value="Cancel">Cancel</button>
</div>
</form>
</div>
</header>
</body>
</html>
It looks like this script is modifying itself, and using DOMDocument to do it. PHP scripts aren't valid HTML/XML, so DOMDocument mangles the code up - it's not Sublime's fault :)
The way to make the code do what you expect here is put the header HTML into a separate file (like header_nav.html), manipulate that instead, and then make your script output it to the user rather than save it.
But modifying a file with DOMDocument is probably way over the top for what you need, and there are other problems with that approach too. That file gets given to everyone, so as soon as one person logs in, everyone gets that header_nav. It also writes to disk when you only really need to change the code in memory and pass it to just that user.
Something much more simple would be to have two header html files (like header_logged_in.php and header_logged_out.php) and then make your header_nav.php just include('header_logged_in.php') if the user is logged in, or include('header_logged_out.php') if they're not.
Some other notes:
Never take something from $_POST and put it straight into an SQL query - you trim it, but that’s no safety at all. The safe way to do it is by using prepared statements. Have a look at PHP The Right Way on how to do that (the examples use PDO which is what I’m more familiar with, but mysqli is okay too if you prefer it).
If either $username or $pass are empty, then $check is never set, so you’d get a PHP strict error telling you that $check is undeclared. You could just add $check = 0 before the if ($check == 0)… line to solve that. Also, use true and false instead of 1 and 0, and === instead of == - though it's a matter of taste in this instance, if you do it elsewhere too then it'll bite you eventually.
It’s commented out, but a later line does header(“Location: “.$_POST[‘url’]) which is also kinda bad - anyone could put any URL into that and redirect your users to their site. It’d be better to build the URL yourself or use an array of valid URLs and point to the right key in the array or something.
You start the session, but you don’t put anything in it (like… whether the user is logged in, and what their username is).
Make sure the doc type is .php and not HTML.
Click the syntax highlighting menu and choose PHP, the language chosen is HTML, make sure PHP is checkmarked.
Otherwise:
To edit the preferences:
1) - Preferences ==> Browse Packages...
2) - Go to the HTML folder & Open "HTML.tmLanguage" with a text editor
3) - Find :
firstLineMatch
<string><!(?i:DOCTYPE)|<(?i:html)|<\?(?i:php)</string>
And replace it with :
firstLineMatch
<string><!(?i:DOCTYPE)|<(?i:html)</string>
4) - Restart Sublime Text.

Php not receiving values from html form

In the following code, data from html form is not received by php variables. The code directly executes if-else statement without waiting for input.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("fb");
$id=$_POST["email"];
$pwd=$_POST["password"];
$sql=mysql_query("SELECT* FROM admin WHERE id='$id' AND pass='$pwd'");
if($sql)
{
die ("Login");
}
else
{
die ("Failed");
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<!--<link rel="stylesheet" type="text/css" href="style.css" />!-->
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
I know this code is vulnerable to SQL injection but who care if its an home assignment. :)
The code directly executes if-else statement without waiting for input.
The reason being is that you have your entire code (HTML/PHP/SQL) inside one file with no conditional statement to control it.
Using your submit button's name element with if(isset($_POST['Login'])) will fix that.
Another option would be to use two seperate files. One with your form and the other with the PHP/SQL and setting action="handler.php" for your form's action.
<form method="POST"> is equivalent to <form method="POST" action=""> (self).
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("fb");
$id=$_POST["email"];
$pwd=$_POST["password"];
if(isset($_POST['Login'])){
$sql=mysql_query("SELECT * FROM admin WHERE id='$id' AND pass='$pwd'");
if($sql)
{
die ("Login");
}
else
{
die ("Failed");
}
} // brace for if(isset($_POST['submit']))
?>
The following links will help you later on.
For passwords, CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Plus, mysqli with prepared statements, or PDO with prepared statements.
Always use error reporting this will help you to debug code.
Plus, use or die(mysql_error()) to mysql_query() instead of just the way you have it now. It will signal the actual error, should there be any.
The code directly executes if-else statement without waiting for input.
Then tell it to do those action after input.
if($_POST) {
$id=$_POST["email"];
$pwd=$_POST["password"];
$sql=mysql_query("SELECT* FROM admin WHERE id='$id' AND pass='$pwd'");
if($sql)
{
die ("Login");
}
else
{
die ("Failed");
}
}
I know this code is vulnerable to SQL injection but who care if its an home assignment.
Never give up security just because of the nature of the project. You'll fall into a trap, and then it will bite you later on in life. Make sure you secure your application irregardless of the project.

Categories