Is this php login system secure? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Is this login page secure, researching about sql-injection, is their a vulnerability if so how do I manage it?
I previously encrypted the users details into a file and stored it locally. I also use localhost, thinking about moving to a domain. Are there any issues with storing users details in a file?
Please disregard the html
<?php
session_start();
?>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="Username"value="">
<?php if ($_SERVER["REQUEST_METHOD"] == "POST"){
$user = $_REQUEST['Username'];
} ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="password" name="Password"value="">
<?php if ($_SERVER["REQUEST_METHOD"] == "POST"){
$password = $_REQUEST['Password'];
}
if (isset($_POST['submit'])) {
$file = $user.".txt";
if (file_exists($file)){
$contents = file_get_contents($file);
$ciphering = "AES-128-CTR";
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
$decryption_iv = '#secret#';
$decryption_key = "#key#";
$decryption= openssl_decrypt ($contents, $ciphering,
$decryption_key, $options, $decryption_iv);
if($decryption==$password){
echo("details match");
setcookie("username", $user,time()+2000);
$_SESSION["logged_in"] = true;
$_SESSION["username"] = $user;
header("Location:/login/new folder/findchat.php?username");
exit();
}
else{
echo('Complete im not a robot');
}
}
else{echo("pasword or username is not valid");}
}
?>
<input type="submit"value="submit"name="submit">
</body>
</html>
Apologies of my bad spelling, Thanks

Wow, this is awful. There's tons of vulnerabilities. Here's the ones that jump out at me at first glance:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
This is vulnerable to XSS, like this: http://example.com/badlogin.php/"><script>alert("xss")</script>
$file = $user.".txt";
if (file_exists($file)){
$contents = file_get_contents($file);
Trivial directory traversal.
$decryption= openssl_decrypt ($contents, $ciphering,
$decryption_key, $options, $decryption_iv);
if($decryption==$password){
You're supposed to hash passwords, not encrypt them.
About the only vulnerability you don't have is SQL injection, and that's because you don't use any SQL.

Related

Why is this post method not being retrieved? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Currently working on a messaging system for my site. I've created a JavaScript function to send post data, and a corresponding PHP file to insert the data. However, the data is not being sent to the database. I'm not sure if the error is in the JavaScript or the PHP file as there is no error log being created.
HTML:
<form action="javascript:sendPM();" name="pmForm" id="pmForm" method="post">
<input name="pm_send_id" id="pm_send_id" type="hidden" value="<?php echo $_SESSION['userID']; ?>" />
<input name="pm_send_name" id="pm_send_name" type="hidden" value="<?php echo $_SESSION['userName']; ?>" />
<input name="pm_receive_id" id="pm_receive_id" type="hidden" value="<?php echo $row['userID']; ?>" />
<input name="pm_receive_name" id="pm_receive_name" type="hidden" value="<?php echo $row['userName']; ?>" />
X
<h4>Send to <?php echo $row['userName']; ?></h4>
<div class="sectionheader"></div>
<div id="interaction"></div>
<br>
<p>Comment:</p>
<textarea name="pmTextArea" id="pmTextArea"></textarea>
<p>Select Video:</p>
<input name="pmSubmit" type="submit" value="Submit" />
</form>
JavaScript:
$('#pmForm').submit(function(){$('input[type=submit]', this).attr('disabled','disabled');});
function sendPM(){
var pmTextArea = $("pmTextArea");
var sendName = $("pm_send_name");
var sendID = $("pm_send_id");
var receiveName = $("pm_receive_name");
var receiveID = $("pm_receive_id");
var url = "messages.php";
if (pmTextArea.val() == ""){
$("#interaction").html('Comment field is empty.').show().fadeOut(5000);
}
else {
$.post(url,{ message: pmTextArea.val(), sendername: sendName.val(), senderid: sendID.val(), recname: receiveName.val(), recID: receiveID.val() }, function(data){
$("#interaction").html(data).show().fadeOut(5000);
document.pmForm.pmTextArea value='';
});
}
}
PHP:
<?php
session_start();
require_once 'class.channel.php';
require_once 'dbconfig.php';
$user_message = new USER();
if (isset($_POST['message'])) {
$to = ($_POST['recID']);
$from = ($_POST['senderid']);
$toName = ($_POST['sendername']);
$fromName = ($_POST['recname']);
$msg = htmlspecialchars($_POST['message']);
$stmt = $user_message->runQuery("INSERT INTO inbox(send_id, receive_id, timesent, comment) VALUES(?, ?, ?, ?)");
$stmt->bindValue(1,$from);
$stmt->bindValue(2,$to);
$stmt->bindValue(3,now());
$stmt->bindValue(4,$msg);
$stmt->execute();
}
?>
You need to use # to retrieve value using their id, which you are missing.
var pmTextArea = $("pmTextArea");
should be
var pmTextArea = $("#pmTextArea");
And yes, you need to correct, which #RyanHame pointed
document.pmForm.pmTextArea value='';
to
document.pmForm.pmTextArea.value='';

Login / directory creator [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
all.
I've got a big ask, and I have no idea how to go around it.
I want to make a login / signup form, which creates a directory on the server for each new user. This directory, somewhat obviously, must not be publicly accessible by other users, and must automatically copy / make it's index.php file and subdirectories.
I'm afraid that I won't have much luck, as I've never made any form of encrypted login before, let alone a fancy automated one like this.
No code as of yet. Any help appreciated!
Well you need two things:
1st of all a system that you can create the directory and the files:
1 php (if you don't mind) file to create files:
Example code:
<form action="function-create-new-file.php" method="post">
WHAT IS THE NAME OF YOUR PAGE
<input name="file_name" type="text" />
<br />
KIND OF FILE YOU WISH TO CREATE
<select name="file_ext">
<option value=".php" selected>php</option>
<option value=".html">php</option>
</select>
<br /><br /><br />
<input type="submit" class="btn" name="submit" value="Add Page" />
</form>
This file will create your files and you should include this one to process it:
<?php
if(isset($_POST['submit'])) //has the form been submitted?
{
$file_directory = "./test/"; //the directory you want to store the new file in
$file_name = strip_tags($_POST['file_name']);//the file's name, stripped of any dangerous tags
$file_ext = strip_tags($_POST['file_ext']); //the file's extension, stripped of any dangerous tags
$file = $file_directory.$file_name.$file_ext; //this is the entire filename
$create_file = fopen($file, "w+"); //create the new file
if(!$create_file)
{
die("ERROR, NOT POSSIBLE TO COMPLETE YOUR DESIRED INSTRUCTION");
}
$chmod = chmod($file, 0755); //set the appropriate permissions.
//attempt to set the permissions
if(!$chmod)
{
//error changing the file's permissions
echo("ERROR IN THE PERMISSIONS FOR THIS ACTION, PLEASE CHMOD 0755 THIS FILE AND FOLDERS");
echo "<br /><br /><br /><br /><br /><br /><br />";
include ("footer.php");
}
//defenition of the new page contante self created
if (fwrite
($create_file, "this is the content of your new page!") === FALSE)
{
echo "ERROR IN FILE: ($file)\n";
}
fclose($create_file);
//tell the user that the file has been created successfully
echo "The file was created! Take a look ate your file here - <a href='$file' target='_blank'>$file</a>";
exit; //exit the script
}
else{ //the form hasn't been submitted!
header("Location: function-create-new-file.php"); //redirect the user back to the add file page
exit; //exit the script
}
?>
Now second, you need to create a directory:
<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0777, true)) {
die('Failed to create folders...');
}
// ...
?>
Please check also this link: How to Create a Directory
Now you need to create the login system for the users. You can do that once again in PHP.
<?php
session_start();
function encode_5t_base64($str)
{
for($i=0; $i<5;$i++)
{
$str=strrev(base64_encode($str));
}
return $str;
}
function jh_password_protection($pass_string)
{
$pass_string = encode_5t_base64($pass_string);
$pass_string = md5($pass_string);
$pass_string = sha1($pass_string);
return $pass_string;
}
function registerUser($user,$pass1,$pass2)
{
$errorText = '';
if ($pass1 != $pass2) $errorText = "Password must be the same";
elseif (strlen($pass1) < 6) $errorText = "Password too short";
$pfile = fopen("some/path/to/store/member/password.php","a+");
rewind($pfile);
while (!feof($pfile))
{
$line = fgets($pfile);
$tmp = explode(':', $line);
if ($tmp[0] == $user)
{
$errorText = "That user already exists"; // check it you made duplicated members
break;
}
}
if ($errorText == '')
{
$userpass = jh_password_protection($pass1);
fwrite($pfile, "\r\n$user:$userpass");
}
fclose($pfile);
return $errorText;
}
function loginUser($user,$pass)
{
$errorText = '';
$validUser = false;
$pfile = fopen("path/to/your/user/page.php","r");
rewind($pfile);
while (!feof($pfile)) {
$line = fgets($pfile);
$tmp = explode(':', $line);
if ($tmp[0] == $user)
{
if (trim($tmp[1]) == trim(jh_password_protection($pass)))
{
$validUser= true;
$_SESSION['userName'] = $user;
}
break;
}
}
fclose($pfile);
if ($validUser != true)
$errorText = "That went wrong"; // failed login message
if ($validUser == true) $_SESSION['validUser'] = true;
else $_SESSION['validUser'] = false;
return $errorText;
}
function logoutUser()
{
unset($_SESSION['validUser']);
unset($_SESSION['userName']);
}
function checkUser()
{
if ((!isset($_SESSION['validUser'])) || ($_SESSION['validUser'] != true))
{
header('Location: path/to/your/user/page.php'); // Your user location
exit();
}
}
?>
Now lets make the login system, first step, create a login page as you desire and place this code under content type tag:
<meta http-equiv="Pragma" content="no-cache">
Sample login system form:
<?php
if ($error == '') {
echo "Welcome";
echo "<a href='./path/to/your/member/area/'>Proceed</a>";
}
else echo " $error ";
?>
<?php if ($error != '') {?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<br/><br/>
<label>USERNAME</label>
<br/><br/>
<input name="username" type="text">
<br/><br/>
<label>PASSWORD</label>
<br/><br/>
<input name="password" type="password">
<br/><br/>
<input value="LOGIN" name="submitBtn" type="submit">
</form>
<?php }
if (isset($_POST['submitBtn'])){
?>
at the top of your page just include this:
<?php
require_once('file/that/operates/the/login.php');
$error = 'wow that was wrong';
if (isset($_POST['submitBtn'])){
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$error = loginUser($username,$password);}
?>
I think i didnt forgot nothing here, but let me know if that helps.
IMO storing the data in a database instead of files would be cleaner and easier.
However if you really need to go with separate folders here's a solution:
Create a simple login/signup form.
On signup, create the user folder in a parent folder you will name for example uploads.
Then you just have to configure your server (you can achieve this with .htaccess) so that every request to the uploads folder gets redirected to a controller (for example index.php)
In index.php, check that the user is logged in and that the folder he's trying to access belongs to him. If it does, render the requested file, if not, render an error message.
in your php file that handles the register function
after a success registration you should add
mkdir("yourtargetpath/" . $username, 0700);

Get var from a PHP page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm having a problem with my PHP. I would like to send data from my page to another page. But it's all in PHP. I need to take an input value and a combobox value. And I don't know how to do it.
Here's my PHP :
<?php
session_start();
$q = intval($_GET['q']);
$db = mysql_connect('localhost', 'root', 'root');
mysql_select_db('Projet',$db);
$sql2 = "select IDControle, NomControle from Controle WHERE IDUser='".$_SESSION['id']."'";
$req2 = mysql_query($sql2) or die('Erreur SQL !<br>'.$sql2.'<br>'.mysql_error());
echo'<select id="controleChoix" name="controleChoix">';
while ($data2 = mysql_fetch_array($req2)){
echo '<option value="'.$data2['IDControle'].'">'.$data2['NomControle'].'</option>';
}
echo '</select>';
echo '<input type="hidden" name="selected_text" id="selected_text" value="" />';
$sql = "select ID, Nom, Prenom from User where Groupe ='".$q."'";
$req = mysql_query($sql) or die('Erreur SQL 2!<br>'.$sql.'<br>'.mysql_error());
echo '<ul class="list-group">';
while ($data = mysql_fetch_array($req)){
echo '<li class="list-group-item"><strong>Nom</strong> : '.$data['Nom'].' <br> <strong>Prénom</strong> : '.$data['Prenom'].'<br>';
echo '<input type="text" name="note" id="note"/> ';
echo '<a class="label label-success" href="ajouterNote.php?var1='.$data2['IDControle'].'&var2='.$data['ID'].'&var3='.$test.'"><i class="fa fa-fw fa-check"></i></a></li>';
}
echo '</ul>';
echo '<a class="btn btn-primary" href="#">Ajouter toutes les notes</i></a></li>';
?>
I need to send the input note.value, the select controleChoix.value and the intval q that I've received from another page.
As you already seem to use SESSIONS, you could easily transfer your data from one page to another using these $_SESSION variables.
https://secure.php.net/manual/en/book.session.php
edit: Please keep in mind that this isn't secure at all. The values can easily be changed by the user. Using this you might want to validate the values first, before using.

How can i show a webpage only for logged in users? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Currently I'm working on a little project for login page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users. i am using php and sql for this. i want also a logout and senf to the index but i can't find te solution. Here is my code.
<?php
require ('sql_connect.php');
if (isset($_POST['submit'])){
$username=mysql_escape_string($_POST['uname']);
$password=mysql_escape_string($_POST['pass']);
if (!$_POST['uname'] | !$_POST['pass'])
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('You did not complete all of the required fields')
window.location.href='index.html'
</SCRIPT>");
exit();
}
$sql= mysql_query("SELECT * FROM `login_users` WHERE `username` = '$username' AND `password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Succesfully!.')
window.location.href='homepage.html'
</SCRIPT>");
exit();
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Wrong username password combination.Please re-enter.')
window.location.href='index.html'
</SCRIPT>");
exit();
}
}
else{
}
?>
this is my control for the correct user and pass.
And here is the page i want to go if the user has logged in.
homepage.index:
<html>
<head>
</head>
<body>
<center><h1>Welcome user!</h1></center>
here some text and other stuff.
<h3>logout here<h3>
</body>
But now i can write www.mysite/homepage.index and i can go to this page without logging in. Can someone explain this?
Thank you.
Your question is part of many many available tutorials, did you try to google it first?
do not use mysql extension (using mysqli in example)
do not redirect via javascript, if you can do it via php
do not redirect to html files, when you need to work with php
do not store password as plain text (using php5.5+ function to crypt it in example)
do not select *
do not echo html code
use isset before getting value from $_POST, $_GET
Feel free to google everything to know the reasons.
<?php
class Connection //not sure what you have in sql_connect.php, I made this so the example is complete
{
static function getConnection(){
if(self::$connection === null)
self::$connection = new mysqli('127.0.0.1', 'root', '', 'so');
return self::$connection;
}
/** #var mysqli */
private static $connection;
}
<?php
class UserAuthenticator
{
function __construct(){
session_start(); //you need to start session when working with $_SESSION
}
function checkLogin(){
if(isset($_POST['submit'])){
$username = $this->getPostEscaped('uname');
$password = $this->getPost('pass'); //no need to escape through mysqli, we do not use it in query
if($username && $password){
$userData = Connection::getConnection()->query("SELECT password FROM login_users
WHERE username = '$username'")->fetch_assoc();
if($this->verifyPassword($password, $userData['password'])){
$this->login($username); //storing username for simplicity, but I do recommend to store id or some generated hash even better
$this->flash('Login succesfull.');
$this->redirect('homepage.php');
}else $this->flash('Wrong username / password combination. Please re-enter.');
}else $this->flash('You did not complete all of the required fields.');
$this->redirect('index.php');
}
}
function isLogged(){ //actual answer to the question - how to check the logged user
return isset($_SESSION['logged']);
}
function verifyPassword($password, $passwordHash){ //public so you can use it elsewhere
return password_verify($password, $passwordHash);
}
function getPasswordHash($password){ //public so you can use it elsewhere
return password_hash($password, PASSWORD_DEFAULT);
}
function showFlashMessages(){
if($flashMessages = $this->getFlashes()): ?>
<script language="JavaScript">
<?php foreach($flashMessages as $message): ?>
alert('<?= $message ?>');
<?php endforeach ?>
</script> <?php
endif;
unset($_SESSION['flashmessage']); //we need to remove messages, so they do not persist
}
function redirect($to = ''){ //you need to ensure you are not echoing any content before redirecting (that's a proper common way - learn it)
$url = 'http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header('Location: ' . $url .'/'. $to, true, 302);
header('Connection: close');
exit;
}
private function login($userId){ //actual answer to the question - how to store the logged user
$_SESSION['logged'] = $userId;
}
private function flash($message){ //do not repeat yourself
if(!isset($_SESSION['flashmessage']))
$_SESSION['flashmessage'] = array();
$_SESSION['flashmessage'][] = $message;
}
private function getFlashes(){
return isset($_SESSION['flashmessage'])? $_SESSION['flashmessage']: [];
}
private function getPost($name, $default = null){ //do not repeat yourself
return isset($_POST[$name])? $_POST[$name]: $default;
}
private function getPostEscaped($name, $default = null){ //do not repeat yourself
return ($value = $this->getPost($name))?
Connection::getConnection()->real_escape_string($value): $default;
}
}
$ua = new UserAuthenticator();
$ua->checkLogin();
$ua->showFlashMessages();
you need to store passwords with
$ua = new UserAuthenticator();
$password = $ua->getPasswordHash($plainTextPassword); //store this to database
in homepage.php you can check logged status with
$ua = new UserAuthenticator();
if(!$ua->isLogged()){ $ua->redirect('index.php'); } //redirect to login page if not logged in
not tested anything of this, so typo is possible - sorry :)
Lets say your login was succesfull. All you have to do is this:
Session_start();
$_SESSION['id']= $row['id']; (make sure you changed mysql_num_rows to fetch assoc aswell)
Then on your index page at the top you add an if statement that checks wether or not the session has been set. For that you first need to call another session_start()
Hope this steers you in the right direction if not ill update my answer

PHP Mysql Insert Into not working, no error given no data posted to DB, earlier the same page was working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have problem regarding noted above. My code in php is as under:
$con = mysql_connect(xxxx,xxx,xxx) or die(mysql_error());
mysql_select_db(xxx) or die(mysql_error());
if (count($_POST) > 0) echo "form submitted";
if(isset($submit))
{
$name = $_POST['std_name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$user_type = "student";
if(mysql_query("insert into login (user_id, user_pass, User_type) values ('$email','$pass','$user_type'", $con))
{
echo "<p class='success_msg'>Congrats! your registration has successfully been done.</p>";
echo mysql_error();
}
else
{
echo mysql_error();
}
Earlier this code was working well and the values were being entered into database. but suddenly it is not working and not even giving any error. any help in the regard will be highly appreciated, please.
$submit is not set in the code sample
You are missing a closing bracket at the end of your query
Read about 'SQL injection', your code is vulnerable
Here's what might help...
Connect to your MySQL database via PHPMyAdmin or via SSH.
Once connected, type the query manually (so, INSERT INTO login() etc) — if it works, then it's a bug further up your code. If this is the case, you need to show us more.
OK, so I've applied a nice PDO version down below.
$host = "localhost";
$port = 3306;
$dbname = "myDatabase";
$user = "myUser";
$pass = "myPass";
$db = new PDO("mysql:host=" . $host . ";port=" . $port . ";dbname=" . $dbname, $user, $pass);
echo (count($_POST) > 0) ? echo "form submitted" : "";
if(isset($submit))
{
$name = $_POST['std_name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$user_type = "student";
$query = $db->prepare("INSERT INTO login(`user_id`, `user_pass`, `User_type`) VALUES (:email, :pass, :utype");
$binds = array(
":email" => $email,
":pass" => $pass,
":utype" => $user_type
);
if($query->execute($binds))
{
echo "<p class='success_msg'>Congrats! your registration has successfully been done.</p>";
}else{
echo "\nPDO::errorInfo():\n";
print_r($db->errorInfo());
}
}
Read the PDO documentation here.

Categories

Resources