Use MongoDB with PHP - javascript

We assigned me a new project to realize in order to manage candidacies of customers !
3 tasks will be realized :
authentification of the users
import data concerning the candidacy in the form of file .xls/.xlsx thanks to the upload of files.
Display the results in json format
I thus chose to realize it in HTML / CSS, Javascript / JQuery, PHP as well as a basebasis NoSql MongoDB.
On one hand, the users will be inserted in base(basis) in a manual way by the style:
db.users.insert({"name": "Laurence", "password": hex_md5("test")});
Do not ask me why they will be inserted in this way, it is the person in charge who so decided :(
The problem already is that I did not find in a more secure way, to insert passwords that other than with the function hex_md5 ().
Thus if already you could help me on this point, it would be already good ! :)
On the other hand, to communicate my database with PHP, I use the class MongoDB\Driver\Manager.
Already of the evil to be able to implement and to use this kind of classes, seen that the syntax is a little bit different from the PDO:/
I try through a page of authentification, to verify if the seized fields correspond well to the values in database to be able to connect, but top I already surround :/
If somebody could give me a blow onto these points, it would be top! :D
And if somebody would have some documentation to propose, it is always good to set seen that I can't find any other record of it :/
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="../js/login.js"></script>
<link rel="stylesheet" href="../css/login.css">
</head>
<body>
<?php
include('../index.php');
?>
<form method="post" action="../templates/checkLogin.php">
<div class="container">
<div class="card card-container">
<img id="profile-img" class="profile-img-card" src="../img/avatar.png" />
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin">
<span id="formIdentity" class="formIdentity"></span>
<input type="text" id="identity" name="identity" class="form-control" placeholder="Your identity" autofocus>
<input type="password" id="password" name="password" class="form-control" placeholder="Your password">
<button class="btn btn-lg btn-primary btn-block btn-signin" type="submit" id="submitBtn" onclick="checkForm(this)">Sign in</button>
</form><!-- /form -->
<a href="../templates/forgotPassword.php" class="forgot-password">
Forgot password ?
</a>
</div><!-- /card-container -->
</div><!-- /container -->
</form>
</body>
</html>
<?php
$manager = new MongoDB\Driver\Manager();
$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],
];
$query = new MongoDB\Driver\Query(array(), $options);
$cursor = $manager->executeQuery('candidates.users', $query);
foreach ($cursor as $document)
{
if($document->name === $_POST['identity'] &&
password_verify($_POST['password'], $document->name))
{
echo "User ".htmlspecialchars($_POST['identity']). "connected !";
}
else
{
echo "Unknown user !";
}
}
?>
enter image description here
enter image description here

Related

Show Pop up message after form validation in javascript

I am new in javascript and currently I am creating an enrolment form where it will validate the cellphone where it only accepts 11 characters and numbers. the only problem is that everytime I click on submit, instead of the message popping up, it completely refreshes my tab. Is there any way to fix this?
Form Code:
<!doctype html>
<html lang="en">
<head>
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="Homepage.html"><img src="USTLogo.png" width="30" height="30" alt="">School</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="Homepage.html">HOME<span class="sr-only">(current)</span></a>
</li>
</ul>
</div>
</nav>
<title>Enrollment Form</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- CSS -->
<link href = "design.css" rel = "stylesheet" type="text/css"/>
<script src="JAVASCRIPT.js" type="text/jsx"></script>
</head>
<body>
<h1 class="display-1">Enrollment Form</h1>
<div class="container">
<div class="row">
<!-- empty space on the left side -->
<div class="col-lg-3"></div>
<!-- Main Content -->
<div class="col-lg-6">
<div id ="ui">
<form id = "form" class="form-group">
<div class="row">
<div class="col-lg-8">
<label >Cellphone Number</label>
<input id = "Cp_Number" type="text" class="form-control" placeholder="Enter Cellphone Number..." required>
</div>
<div class="col-lg-4">
<label >Age</label>
<input id = "Age" type="text" class="form-control" placeholder="Enter your age..." required>
</div>
<br>
<div class="row">
<div class="col-lg-6">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
<div class="col-lg-6">
Cancel
</div>
</div >
</form>
</div>
</div>
<!-- empty space on the right side -->
<div class="col-lg-3"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Note: I will be removing most of the content in the form and will only include the fields where it needs validation
JS code:
const Cp_num = documet.getElementById('Cp_Number')
const age = document.getElementById('Age')
const form = document.getElementById('form')
form.addEventListener('submit', (e) =>{
var isValid = true;
e.preventDefault();
if(isNaN(Cp_num) || Cp_num.value == null || Cp_num.value == ''){
alert ("Your Cellphone number is invalid!")
isValid == false;
}
if (Cp_num >=12){
alert ("Your Cellphone number is invalid!")
isValid == false;
}
if(isNaN(age) || age.value == null || age.value == ''){
alert ("Your Age is invalid!")
isValid == false;
}
if (isValid == true){
popUp();
}
})
Stop using your custom javascript in the head tag. Because, of this the scripts loads before the contents and doesn't find the form element in the DOM before initialization. So, use any custom javascript inside the body tag and below all the html elements. But remember to include any other dependencies before your custom scripts. Hope it solves the problem.
What's happening here is that your script tag is in your head:
<script src="JAVASCRIPT.js" type="text/jsx"></script>
And for that reason, your HTML hasn't been loaded completely, so a "form" element with the id of "form" does not exist, thus, you get an error (check your console in your browser).
This is why your e.preventDefault() method doesn't work. Because again, your HTML hasn't been loaded yet.
You have two options:
Put the script tag at the bottom of your body:
Very self-explanatory, put the script tag at the end of your body, so your whole HTML loads first, and then your JavaScript file.
Use the "defer" attribute in your script tag:
I won't explain what the defer does in depth here, but if you want some quick answer, it basically waits for your HTML to fully load before using any of the JavaScript code.
So you can try this:
<script src="JAVASCRIPT.js" type="text/jsx" defer></script>
(By the way, this method does not require you to move the script tag out of your HTML head)
You can learn more about defer here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer
(EDIT): By further inspection of the code, I found that you were using the "type" parameter in your script tag. You don't need this, and this is causing you the problem of your script tag not being used:
So from:
<script src="JAVASCRIPT.js" type="text/jsx"></script>
do:
<script src="JAVASCRIPT.js" defer></script>
(Another gotcha) You have a typo on the first "document" that you were selecting:
const Cp_num = documet.getElementById('Cp_Number')
"documet" is not defined, you have to change it to:
const Cp_num = document.getElementById('Cp_Number')

Redirecting from a HTML button to a new page with JS

This is fairly simple, I'm trying to make the login button work, and redirect to a different file (placeholder.html) if what is in the email and password match the following:
Login: Admin
Password: Password123
I have yet to get the login button to work in the first place to redirect, and id like to keep it as a button element by using, the 'onlick=' with a function in js or an id for now.
Thank you so much for the help :)
Apologies if this is a little sloppy, one of my first times asking for help here haha
Here is what I had so far, which dent work fully:
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
<link href="style." rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class="login-page">
<div name="login" class="form">
<div class="title login" style="font-size: 25px; font-family: Roboto; padding-bottom: 25px;">
Login Form
</div>
<form class="login-form" action="login.php" method="post">
<input type="email_" placeholder="email"/>
<input type="password" placeholder="password"/>
<button id="login_button">login</button>
<p class="message" style="font-family: Roboto, sans-serif;">Not registered?
Create an account
</p>
</form>
</div>
</div>
</body>
<script type="text/javascript">
document.getElementById("login_button").onclick = function () {
location.href = "#placeholder";
};
</script>
</html>
Welcome to StackOverflow, there are a few things that I wanted to cover here as part of the answer.
The function is running onClick, the way you're using location.href is invalid though. You are redirecting to an anchor (it starts with a #), The way this is implemented in browsers is that it will redirect your scroll positioning to the top of the element with ID, if you had an element on your page with the ID of placeholder (and the page height was more than 100%) it would move the scroll position of the page, not redirect.
I believe you're looking for
location.href = "placeholder.html";
You wanted the user to be redirected based on the username and password that they enter, I will provide the solution below but before that, I wanted to say that this isn't secure, the username and password are visible inside the source code and if you planned to use this to hide important information it will not work because the code is visible to anyone who accesses the webpage, you should be using a server-side language such as NodeJS or PHP to hide that information, I assume that this is just for practise/learning though.
The first thing you'll want to do is get the username and password.
Your <input type="email_" placeholder="email"/> should be <input type="text" placeholder="email"/>. For some reason you put the type as what looks to be a typo email_ and not email but since you said the username was admin that is just text.
I would start by giving an ID to both the username and password elements.
<input type="email" id="username" placeholder="email"/>
<input type="password" id="password" placeholder="password"/>
Then inside your function you can change it to check and redirect like below
document.getElementById("login_button").onclick = function () {
const username = document.getElementById("username").value
const password = document.getElementById("password").value
if (username === 'Admin' && password === 'Password123') {
location.href = "placeholder.html";
}
};
That will also be case-sensitive.
There are a couple of ways that you could do this, here is a simple example:
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
<link href="style." rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class="login-page">
<div name="login" class="form">
<div class="title login" style="font-size: 25px; font-family: Roboto; padding-bottom: 25px;">
Login Form
</div>
<form class="login-form" action="login.php" method="post">
<input type="email_" placeholder="email"/>
<input type="password" placeholder="password"/>
<button id="login_button" onclick="login()">login</button>
<p class="message" style="font-family: Roboto, sans-serif;">Not registered?
Create an account
</p>
</form>
</div>
</div>
</body>
<script type="text/javascript">
function login() {
// Login logic here
if (loginSuccesful) {
window.location.href = "/placeholder.html";
}
}
</script>
</html>

access table from PHP database in Javascript

I have created a login page that allows you to log in using username and password. However, it is currently so that you are always redirected to the "profile" page and there is then checked by PHP whether the login data are correct, because the data are on the DB.
Therefore I have the idea with a validate function directly on the loginpage to check if the data is correct and then I just create a session.
Does anyone have an idea how I can do this?
Here is the code:
<?php session_start();?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="bootstrap_style.css" rel="stylesheet" id="bootstrap-css"> <!-- maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <!-- //maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js or bootstrap.js-->
<script src="jquery.js"></script> <!-- //cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<!-- Icon -->
<div class="fadeIn first">
<img src="default_logo2.png" id="icon" alt="User Icon" onclick="window.open('url', '_blank');"/>
</div>
<!-- Login Form -->
<form action="searchpage.php" method="post" onsubmit="validateForm(event);">
<input type="text" id="login" class="fadeIn second" name="username" placeholder="username">
<input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
<input type="submit" class="fadeIn fourth" value="Log In">
</form>
<!-- Remind Passowrd -->
<div id="formFooter">
<a class="underlineHover" style="color:red" id="warning"></a>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function validateForm(event) {
var input_username = document.getElementById("login");
var input_password = document.getElementById("password");
if (input_username.value == '' || input_username.value.charAt(0) == ' ' || input_password.value == '') {
event.preventDefault();
document.getElementById("warning").innerHTML = "Fill empty fields!";
}
else {
return true;
}
}
</script>
with this I reach the DB:
$pdo = new PDO('mysql:host=localhost;dbname=ausleihe', 'root', '');
and that is the SELECT:
$login_session = "SELECT * FROM login WHERE username = '".$hereshouldbetheusernamefromform."' AND password = '".herethepasswordfromform."'";
If you need more code or have questions, ask me!
Thx
Client-side JavaScript cannot directly access a Host-side PHP program except through AJAX calls. Only the Host-side software has access to Host-side databases.

How can I show a DIV element without creating a new row?

I crated a small login form where I check the username in a external php file. After that I give back an error message or redirect to another site.
My problem is to show the error message. I want a short message above the login form if the username != „test“. In my script, the errormessage appears above the login form, but the login form jumps one row deeper.
Question 1:
How can a create a placeholder above the login form? So that the login form is fix?
Question 2:
Is it the right way to fill a JavaScrpt Variable in PHP as in my Code?
Thanks for your help!
< script >
var error_login;
if (error_login == 1) {
$('#errorText').show();
} else {
$('#errorText').hide();
} <
/script>
<?php
//debug
error_reporting(-1);
ini_set('display_errors', true);
session_start();
session_unset();
session_destroy();
?>
<!doctype html>
<html lang="de">
<head>
<title>Hello World</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<?php include ("login.php"); ?>
<div class="container">
<div id="errorText" class="row justify-content-center">
Login failed!
<!-- This should be a placeholder -->
</div>
<!-- Formular Beginn -->
<div class="row justify-content-center">
<div class="col-md-6">
<form class="form" role="form" method="post" action="?login=1" accept-charset="UTF-8" id="login">
<div class="input-group" id="frmGrpBenutzer">
<input type="password" class="form-control input-lg" id="user" name="user" placeholder="Username" required autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary btn-custom btn-lg" title="login" id="loginbtn"><span>Go</span></button>
</span>
</div>
</form>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
Here the login.php file:
<?php
session_start();
if(isset($_GET['login'])) {
$user = $_POST['user'];
if ($user == "test") {
$_SESSION['username'] = $user;
header('Location: site2.php');
} else {
echo "<script>
var error_login = 1;
</script>";
}
}
There are a few possibilities. The easiest would be to set your div with an opacity:0 or visibility:hidden this will make it still take space in the document flow.
Another option, could be to set it's position:absolute this will prevent it to take space inside your login form. Doing this will make it overlap tough, so there would need to be a padding or margin to offset the content of the form.
As for setting your javascript variable with PHP, that's one way to do it yes, but your script already defines error_login... Another way to do it, is use a holder HTML element, give it an id, and a data-* attribute. This will make it very easy to read the information from code:
$('button').click(function() {
console.log($('#login_status').data('login-error'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="login_status" data-login-error="1"></div>
<button>Click me to get result</button>
You could also add all the data you want into a JSON string as the div's content, and parse it once the page loaded.

How to convert contents saved from markdown back to html

I have rendered simplemde-markdown-editor in jsp page as
<article class="post">
<div class="form-style-2">
<form:form method="post" commandName="post">
<form:input cssClass="input-field" path="postTitle"/>
<form:textarea id="editor" path="postBody"/>
<input type="submit" value="Save Post"/>
</form:form>
</div>
</article>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
<script>
new SimpleMDE({
element: document.getElementById("editor"),
spellChecker: false,
});
</script>
all set perfectly working good, but when I browse saved contents of markdown I get same symbols as of
#### Unordered
* Lists are a piece of cake
* They even auto continue as you type
* A double enter will end them
* Tabs and shift-tabs work too
any help please.
Thanks
just use simplemde.markup(simplemde.value());

Categories

Resources