html entities in a PHP code - php

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"

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.

check if current page url contains certain words

I'm trying to find a way to make it so that you can check if your current page url contains things like 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 the problem is this format could literally go on forever and at any random time I would need to make it so that one of the numbers doesn't display.
Currently I'm using a system like this to gather the current page URL.
$d = explode('?', $_SERVER['REQUEST_URI'], 2);
echo 'http://' . $_SERVER['HTTP_HOST'] . $d[0];
However I'm unfamiliar how we could simply check the URL for certain parts and then redirect it back to the index page.
EDIT: This is my current code (Note I'm using laravel).
if (strpos($d, '19') !== false) {
header( 'Location: http://example.com' ) ;
} else { ?>
<form class="form-horizontal" role="form" method="POST">
{{ csrf_field() }}
#if( strlen( $link->password ) )
<p class="bg-warning" style="padding: 8px;">Enter password to continue</p>
<input type="password" name="password" class="form-control" style="margin-bottom:1.5rem;">
#endif
<button type="submit" class="btn btn-primary">{{ $link->text }}</button>
</form>
<?php } ?>
Sorry for the messy code, Just trying to figure out how I can achieve this without having numerous strpos and actually have it echo out the form as right now it does not.
if you get data from url and page is like this test.php?id=1 you directly access the data using $_GET method and process them. In my case i access the dirctly $_GET["id"], its return value 1. so you directly compare value.
Thanks.
You're in luck, that feature is literally built-in to php!
<?php
echo $_GET['id']; //fetches whatever is after the id= (and before the next '&') example.com?id=WhateverComesHere
?>

mistake in post method

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.

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.

Codeigniter form on same page as results

I am using codeigniter and the tutorial from here. I have made a basic blog tool which works fine. However as it stands to add a new post you have to go to a separate page 'create.php' to get to the form. I would like to try and put the form on the same page as the page that will be updated i.e. 'index.php'. If I try to do this at the moment the form simply refreshes and does submit the data.
model
function insert_post($data){
$this->db->insert('posts', $data);
return;
}
Current View (admin/create.php)
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
View I would like the form to be on (index.php)
<?php
echo '<p>Welcome '.$username.'! All posts available for edit or deletion is listed below.</p><br/>';
echo anchor('admin/create','Create New Post');
$count = count($post['id']);
for ($i=0;$i<$count;$i++)
{
echo '<div class="postDiv">';
echo '<h4>'.$post['title'][$i];
echo '<p>'.$post['summary'][$i].'</p>';
echo '<p>'.$post['content'][$i].'</p>';
//echo anchor('blog/view/'.$post['id'][$i],' [view]');
echo anchor('admin/edit/'.$post['id'][$i],' [edit]');
echo anchor('admin/delete/'.$post['id'][$i],' [delete]</h4>');
echo '</div>';
}
?>
Controller
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $_POST;
$this->posts->insert_post($data);
redirect('admin');
}
}
This was straight forward when I used normal php but with codeigniter I am getting lost with the MVC stuff. I know this is probably a fairly basic question so please either explain your answer or give me a link to something which will explain what I need to do as I want to learn from this. I have read the codeigniter docs on validation but I dont think thats my problem?
What you are trying to do is called embedding a view. I will try to explain how but you should also check some links which might prove to be more in depth:
http://net.tutsplus.com/tutorials/php/an-introduction-to-views-templating-in-codeigniter/
Codeigniter: Best way to structure partial views
The crux of what you need to do is change the link on index.php from:
echo anchor('admin/create','Create New Post');
to
$this->load->view('admin/create');
Now this should work, but to help you on the MVC front, it helps to explain why doing it this way is wrong. The idea of MVC is to seperate the functions in your application into their distinct roles. Most people will frown at putting business logic into views unless it is very minimal. The way that we could improve upon your code is to load the view in the controller, and set it to variable.
At the bottom of the codeigniter docs for views it shows how to load into a variable:
http://ellislab.com/codeigniter/user-guide/general/views.html
if the third parameter of load->view is set to true then the function will return your view as a string instead of outputting it to the browser
$data['input_form'] = $this->load->view('admin/create', $data, true);
then in the view that you want to load that form all you need to do is echo input_form
<?php echo $input_form;?>
So that should solve your problem but there are also a few more things you can do in your view file that will improve the readability of your code.
Instead of using a count() and for loop you can use foreach which makes everything much easier
<?php foreach ($post as $post_item):?>
<div>
<h4><?php echo $post_item['title'];?></h4>
</div>
<?php endforeach;?>
It also helps to break your view files up and have more tags. It might seems like it is extra bloat, but when you have larger view files it will be very cumbersome to continue using as many echo's as you have
just add one method uri_string() in your form action, uri_string will take same url of page put in action you can submit form to same page
<?php echo validation_errors(); ?>
<h4>Create A New Post Below</h4>
<form action="<?=uri_string()?>" method="post" >
<p>Title:</p>
<input type="text" name="title" size="50"/><br/>
<p>Summary:</p>
<textarea name="summary" rows="2" cols="50"></textarea><br/>
<p>Post Content:</p>
<textarea name="content" rows="6" cols="50"></textarea><br/>
<input type="submit" value="Save" />
<?php echo anchor('admin','Cancel'); ?>
</form>
in controller little chagnes
function create(){
$data['userId'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('summary','summary','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run()==FALSE)
{
$this->load->view('template/admin_html_head',$data);
$this->load->view('admin/create',$data);
$this->load->view('template/html_tail',$data);
} else {
$data = $this->input->post();
$this->posts->insert_post($data);
redirect('admin');
}
}
Use session library
check this another stackoverflow thread to know how to use session
In order to use session library, u need to configure encryption_key in config.php
To do that, check this out

Categories