Php code symbols escaped after execution (Sublime editor) - php

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.

Related

PHP Session Issue when trying to create a login and register system

I am currently in the process of developing a browser based game in php to test myself, and unfortunately I am having trouble with sessions. The pages seem to all just go blank if i set session include in the header, but then it doesn't redirect to membersarea.php when a user logs in using the form (form works i think). I may be doing all this wrong
header.php
<?php
include 'inc/conf.php';
?>
<!DOCTYPE html>
<head>
<title>Mineshaft Online | Free to play Browser MMORPG</title>
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<?php
if(isset($_SESSION['username'])) {
?>
<div class="navigation">
<ul>
<li>Dashboard</li>
<li>Mineshaft</li>
<li>Smeltery</li>
<li>Blacksmith</li>
<li>Settings</li>
<li>Logout</li>
</ul>
</div>
<?php
} else {
?>
<div class="navigation">
<ul>
<li>Home</li>
<li>Login</li>
<li>Register</li>
</ul>
</div>
<?php
}
?>
<div class="main-content">
and here is the login.php
<?php
include 'inc/conf.php';
include 'header.php';
if(isset($_POST['submit'])){
// Escape special characters in a string
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// If username and password are not empty
if ($username != "" && $password != ""){
// Query database to find user with matching username and password
$query = "select count(*) as cntUser from users where username='".$username."' and password='".$password."'";
$result = mysqli_query($conn, $query); // Store query result
$row = mysqli_fetch_array($result); // Fetch row as associative array
$count = $row['cntUser']; // Get number of rows
if($count > 0){
$_SESSION['username'] = $username;
header('location: membersarea.php');
} else {
echo "Error! Invalid username and password.";
}
}
}
?>
<form method="post" action="">
<div id="div_login">
<h1>Login</h1>
<div>
<input type="text" class="textbox" id="username" name="username" placeholder="Username" />
</div>
<div>
<input type="password" class="textbox" id="password" name="password" placeholder="Password"/>
</div>
<div>
<input type="submit" value="Submit" name="submit" id="submit" />
</div>
</div>
</form>
Here is the 'inc/session.php' file
<?php
session_start();
if(!isset($_SESSION["username"])) {
header("Location: login.php");
exit();
}
?>
It sounds like the inc/session.php file isn't included at any point in your project. If you want to use sessions, all the scripts using them must start with the session_start() function, and that, before you start to write any html in your page.
That being said, I'm tempted to assume that you've made a little mistake, writing 'inc/session.php' instead of 'inc/config.php' file, which is indeed loaded in your scripts.
I see two things that you should check:
In your 'login.php' file, you include the 'inc/config.php' as well as the 'header.php' file (which already includes 'inc/config.php'). That might be a problem, because you will then start your sessions two times.
In your 'inc/config.php' file (again, assuming that this is the 'inc/session.php' that you wrote), you start the sessions, and immediately say "if the session 'username' doesn't exist, then we redirect to login.php", which would be a problem if you don't have your 'username' session created before... this would do a redirection loop and your web browser should stop and display a message explaining so.
Other than that, make sure that your server has the sessions activated, you could write a simple script (with nothing else in the file, to keep it simple) like this:
<?php session_start(); $_SESSION['test'] = 'it works!'; ?>
Run the script once, then change the same file to:
<?php session_start(); if(isset($_SESSION['test'])) { echo $_SESSION['test']; } else { echo 'The SESSION test has not been set'; } ?>
And see what your script say.

Taking mySQL database input from HTML form with PHP

I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>
<?php
include 'connect.php';
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user- scalable=no"/>
</head>
<title>Test Sign Up</title>
<body>
<header>
<h1>Test Sign Up</h1>
</header>
<div class="contactform">
<form action="testinsert.php" method ="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter
your name here" required>
<label for="testsentence">Test Sentence:</label>
<input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>
<label for="course">Course:</label>
<select id="course" name="course">
<?php
$query = "SELECT CourseID FROM Course";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo "<option>" . $row['CourseID'] . "<option>";
}
mysqli_close($conn);
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<p></p>
View Courses
<p></p>
Return to home page
</body>
</html>
Testinsert.php -
<?php
include 'connect.php';
$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';
$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";
if (mysqli_query($conn, $sql)) {
echo "<p></p>New record added successfully";
echo '<p></p>Return to home page';
} else {
echo "<p></p>Error adding record";
echo '<p></p>Return to home page';
}
mysql_close($conn);
?>
You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
echo "<option>{$row['CourseID']}</option>";
}
The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
echo "<option>{$row['CourseID']}</option>";
}
About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:
Warning
Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];
You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.
Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.

Random Number Resets

My random number generates on page load, but seems to reset when the user clicks the "Guess" button. I still have a lot of building to go with this, but at the end I want the user to be able to make multiple guesses to guess the random number. I want it to generate when the page first comes up and stay the same until correctly guessed. I'm not sure what I'm doing wrong and just starting this program. If you answer, please also explain, as I'm trying to learn what I'm doing. Thank you!
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>PHP Homework 2</title>
<link rel="stylesheet" href="styles/styles.css">
</head>
<body>
<section id="main">
<h1>Play the Guessing Game!</h1>
<section id="left">
<h2>Take a Guess!</h2>
<form action="mine.php" method="post">
<div id="guessBox">
<label id="guessLB">Your Guess:</label>
<input id="guessTB" class="num" type="number" name="guessTB" max="1000" min="1">
</input>
</div>
<input type="submit" id="guessButton" name="guessBTN" value="Guess" />
</form>
</section>
<section id="right">
<h2>Game Stats</h2>
<?php
if(isset($_POST['guessTB']))
{
$randomNum = $_POST['guessTB'];
}
else
{
$randomNum = rand(1,100);
}
echo "<p>Random Number: $randomNum</p>";
?>
</section>
</section>
</body>
</html>
UPDATE: My HTML has remained the same, and I'm posting my new PHP code. But I used a session and wrote some more. However, I've come across two problems:
1) If I refresh the page, I get an error that says that the first instance of $randomNum below the session_start(); is unidentified.
2) It seems that it remembers my very last guess in the game. If I close out the page and reopen it, I immediately get one of the messages that my guess was too high or too low, even before making a guess. Any advice is appreciated!
<?php
session_start();
$randomNum = $_SESSION['randomNum'];
$guess = $_POST['guessTB'];
if(!isset($_SESSION['randomNum']))
{
$_SESSION['randomNum'] = rand(1,1000);
}
else
{
if($guess < $randomNum)
{
echo "<p>Your Guess is Too Low! Try Again!</p>";
}
else if($guess > $randomNum)
{
echo "<p>Your Guess is Too High! Try Again!</p>";
}
else
{
echo "<p>You Won!</p>";
$_SESSION = array();
session_destroy();
}
}
echo "<p>Guess: $guess</p>";
echo "<p>Random Number: $randomNum</p>";
?>
What you can do is use sessions. On every load check if you set it in the session and if it's not set, generate new number and set it, then check what the user input and compare the two numbers. This could also be done with cookies. Another thing you can do is use js. On load store the generated number in some js variable and don't use a form. On button click get the value of the input field and compare with the one you store in the variable.

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"

How do you return login form errors to the same page using PHP?

I'm relatively new to PHP and have exhausted the internet trying to find an answer to this problem. I've looked at countless examples but people seem to very different login systems to mine and I have trouble deciphering it.
Here is my code so far:
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Video for Education Log In</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="logo">
videoedu.edu </div>
<div id="menu">
<ul>
<li>Create Account</li>
<li>About Us</li>
</ul>
</div>
</div>
<br><br><br><br>
<div id="page">
<div id="content">
<h2>Video for Education helps you connect and share with the videos in your life.</h2>
<h3>Upload Share Create Using video for your education purposes. Lecturers Welcome
Upload Share Create Using video for your education purposes. Lecturers Welcome
Upload Share Create Using video for your education purposes. Lecturers Welcome</h3>
<div class= "form">
<form name="login" method="post" action="checklogin.php">
Username: <input type="text" name="myusername" id="myusername" class="textb"/><br />
Password : <input type="password" name="mypassword" id="mypassword" class="textb"/><br />
<br>
<input type="submit" name="login" value="Login" id="login" class="texta" />
</form>
</div>
</div>
</div>
</div>
</body>
</html>
checklogin.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "test";
$tbl_name = "members";
mysql_connect("$host", "$username", "$password")or die("Cannot connect.");
mysql_select_db("$db_name")or die("Cannot select DB.");
$myusername=$_POST["myusername"];
$mypassword=$_POST["mypassword"];
if ($myusername&&$mypassword)
{
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else
{
echo "Wrong Username or Password";
}
}
else
echo "You have left one or more fields blank.";
?>
login_success.php
<?
session_start();
if( !isset( $_SESSION['myusername'] ) ){
header("location:account.html");
}
echo "Welcome, ".$_SESSION['myusername']." - You are now logged in.<br>";
echo "<a href=logout.php>Logout</a>"
?>
<html>
<body>
</body>
</html>
logout.php
<?php
session_start();
session_destroy();
echo "You have been logged out, <a href='index.php'>click here</a> to return."
?>
I have tried inserting this into index.html and changing the file name to index.php.
$submit = $_POST["login"];
if($submit)
{
}
...but it just constantly displays one of the errors ('Wrong username or password') down the bottom of the page at all times.
I want it so that if the user enters a wrong username or password, or leaves a required field blank, the error will pop up on the same page, instead of going to a new ugly, blank PHP page with the error message in the top left-hand corner.
In checklogin.php, instead of echoing an error, use this:
die(header("location:index.html?loginFailed=true&reason=password"));
or something similar, and in your index.html page, just have PHP generate the HTML message, something like this:
<input type="submit" name="login" value="Login" id="login" class="texta" /><br /><br />
<?php $reasons = array("password" => "Wrong Username or Password", "blank" => "You have left one or more fields blank."); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>
</form>
Also, make sure to die() or exit() when you use header to redirect the page, otherwise the rest of your script continues to run.
What you can do is, redirect back to your page if data is invalid. Put errors into session and display them on page:
e.g.:
<?php if(isset($_SESSION['Login.Error']) { echo $_SESSION['Login.Error'];
unset($_SESSION['Login.Error']); } ?>
<form ....
and your error will be visible on page.
In your PHP
$_SESSION["Login.Error"] = 'Invalid credentials';//redirect back to your login page
In checklogin.php, if the user enters a wrong username or password, use the code like this:
echo "<script language=\"JavaScript\">\n";
echo "alert('Username or Password was incorrect!');\n";
echo "window.location='login.php'";
echo "</script>";
It will pop up the error message at the same page (login page), instead of going to a blank PHP page.
You would want to make your index.html page a PHP page, and have the form submit to itself, i.e. to index.php. In this way, you your index page can do the login check for the form values and display the output of the page appropriately, or use headers to redirect if everything validates.
It's hard to tell the effect that your attempt may have had without seeing it in the full context, but the gist of the situation is you need the form to submit to itself and handle it's login processing.
It looks like you want/need to integrate it with jQuery or some other Javascript/AJAX library
to make things more presentable. jQuery has an plugin for form validation that's is very easy to integrate to your project (obviously jQuery library is minimum requirement).
jQuery site and
jQuery validation plugin.
You may also consider using a PHP Framework like CodeIgniter which is also has a very helpful form validation library. CodeIgniter is scary at the beginning (like all MVC based programming library/framework) but it's worth it. you can watch some tutorials on netTuts+ they've created a series of tutorials called CodeIgniter From Scratch, is not from the latest version but is easy to adapt.

Categories