How i block part of the content for unprivileged users - javascript

I am doing a web in where I want to prevent an user to access a content before he or she fulfill some predefined goal.
For example, I want to prevent an user to go to certain place of my page until they go to another place before. Like to prevent someone without the proper level to access that part of the web.
I want to avoid the use of password if possible.
I am going to use it in several parts of my webpage.
Thanks for your help.

You can use php session to do this. on your page that you want to restrict access to could have the following code:
<?php
session_start() // this starts the php session
if($_SESSION['auth'] !== 'true') // this checks if the session variable "auth"
// is not true
{
header("Location: /homepage.php"); // if "auth" is not true, it will redirect
// back to your home page. you can switch
// out "/homepage.html" with whatever your
// actual page is.
}
?>
<html>
<body>Rest of html content...
and the home page would look something like this:
<?php
session_start(); // starts the session
$buttonClicked=$_POST['access']; // checks to see if the button has been clicked
if($buttonClicked) {
$_SESSION['auth'] = 'true'; // sets the session variable auth to true so user
// can have access to other page
header("Location: /otherpage.php"); // sends the user to the other page
}
?>
<html>
<body>
<form method="post" action="homepage.php">
<input type="submit" value="Go to other page" name="access" />
</form>
</body>
</html>
When the user clicks the html button it will send them to the "otherpage.php" and they will be able to get in. both pages need to be .php not .html though.

Here is a quick example to your question:
index.php redirects the user to login.php if a specified $_SESSION variable does not exist.
login.php contains a basic account/password form. login.php use AJAX to call checkLogin.php to check whether the account/password are correct.
checkLogin.php checks whether the account/password are correct by comparing the user inputs with the data in database(mySQL in this example).
If the account/password are correct, checkLogin.php initiate $_SESSION["account"] and redirect the user back to index.php.
index.php
<?php
session_set_cookie_params(0);
session_start();
ob_start();
// Redirect to login.php if $_SESSION["account"] is not set
$url = "login.php";
if(isset($_SESSION["account"])!=true)
{
header('Location: '.$url);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<!-- Your secret contents here-->
<h1>Hello, your name is:</h1>
<?php echo $_SESSION["account"]; ?>
</body>
login.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function AjaxCheck()
{
if(document.getElementById("account").value==""){
document.getElementById("div_message").innerHTML = "You are not logged in.";
return;
};
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText.match("redirect")){
window.location.href = "index.php";
}
else{document.getElementById("div_message").innerHTML=xmlhttp.responseText;}
}
}
// Use HTTP get to send user input account/password to checkLogin.php
xmlhttp.open("GET","checkLogin.php?account="+document.getElementById("account"). value+"&password="+document.getElementById("password").value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<p>Account: </p>
<input type="text" name="account" id = "account"/>
<p>Password: </p>
<input type="password" name="password" id = "password" />
<br>
<a class="btn btn-primary" onClick = "AjaxCheck()">Login</a>
</form>
<div id = "div_message" >
div_message text
</div>
</body>
checkLogin.php
<?php
session_set_cookie_params(0);
session_start();
// NOTE: In real world, you should do some sanitization first
$account=$_GET["account"];
$password=$_GET["password"];
checkIfLogin();
function checkIfLogin(){
$con = mysql_connect("localhost","YourDatabaseAccount","YourDatabasePassword");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_select_db("YourDB", $con);
$result = mysql_query("SELECT * FROM `YourTable` WHERE `Account` = '".$GLOBALS['account']."' " );
$row = mysql_fetch_array($result);
if($row==NULL){echo "This account does not exist"; mysql_close($con); return;}
if(strcmp($row['Password'],SHA1($GLOBALS['password']))==0){
$_SESSION['account'] = $GLOBALS['account'];
echo "redirect" ;
}
else{echo "Incorrect Password" ;}
mysql_close($con);
}
?>
Notes
The above example codes "work" but should be consider "dirty", just a quick example.
I know you want the answer as simple as possible, but an example with account/password should get you to know the feel how session or cookies work. You can implement the way you like later.
You may find these sites/topics useful:
AJAX
PHP 5 Sessions
PHP 5 Complete Form Example
PHP 5 Form Validation
basic SQL, and things about general Database and SQL.
P.S. Actually you don't need AJAX to achieve your goal, but why not learn more? :)
Edit: Just in case that you don't have a database available, here is a simple checkLogin.php which only allows user "John" with password "123" to pass.
<?php
session_set_cookie_params(0);
session_start();
$account=$_GET["account"];
$password=$_GET["password"];
checkIfLogin();
function checkIfLogin(){
if(strcmp($GLOBALS['account'],"John")!=0){
echo "Invalid Account";
}else if(strcmp($GLOBALS['password'],"123")!=0){
echo "Incorrect Password";
}
else{
$_SESSION['account'] = $GLOBALS['account'];
echo "redirect" ;
}
}
?>

Related

How to call javascript function from form in a php echo?

what the bellow code does is making sure the user isn't allowed to submit a comment unless he's signed in by using $_SESSION['login_user'] supervariable. But it's giving me an error. I think the problem is because I'm calling a javascript function in onsumbit="return(checkUser())". There's something wrong there but I don't know why.
I have the following code:
<script type="text/javascript">
// notice the quotes around the ?php tag
function checkUser() {
<?php
if(isset($_SESSION['login_user'])){
$isExist = true;
}
?>
else{
$isExist= false;
alert( "Please register first!" );
}
var htmlString="<?php echo $isExist; ?>";
return isExist;
}
</script>
...
...
<?php
echo "<form method='POST' onsubmit="return(checkUser());" action='".setComments($connection, $res['post_id'])."'>
//echo "<form method='POST' action='".setComments($connection, $res['post_id'])."'>
<input type='hidden' name='uid' value='".$_SESSION['login_user']."'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'> </textarea><br>
<button type='submit' name='commentSubmit'>Comment</button>
</form>";
getComments($connection, $res['post_id']);
?>
....
If this is not the right method to stop the user from submitting a comment, then what could be another method?
In addition to what #RonaldT said, you need to understand that the PHP code is executed on the server before being sent to the browser. So checking for $_SESSION['login_user'] inside a Javascript function is kind of silly, since it will always be the same until the user refreshes the page (only then will PHP re-check the value).
So your function can be simplified like this:
<script type="text/javascript">
// on page load, define a global variable using PHP
var isLoggedIn = <?php echo isset($_SESSION['login_user']) ? "true" : "false"; ?>;
function checkUser() {
// check that global variable every time checkUser() is called in Javascript
if (!isLoggedIn) {
alert( "Please register first!" );
}
return isLoggedIn;
}
</script>
Keep in mind that this kind of "security" is extremely easy to fool (any user can just open their browser console, type isLoggedIn = true; and voila), so be sure to check on the server as well when the form is submitted.
Or better yet: if a user is not allowed to do something, don't give them the opportunity. Why display the form at all if the user will not be allowed to submit it anyway?
<?php
if (!isset($_SESSION['login_user'])) {
echo "Please register to add a comment";
} else {
echo "<form [...everything else...] /form>";
}
getComments($connection, $res['post_id']);
?>

Creating a simple Password login without the password hardcoded [PHP,Javascript,MySQL]

I'm trying to create a simple login promt on my local website. I already tried with Javascript, but I don't want the password to be hardcoded. The Users get the password by mail so there is no registration form needed. I searched on the Internet and I think it should work with PHP and Javascript. This is what i've come up with:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter password',' ');
while (testV < 3) {
if (!pass1)
window.open('Website.html',"_self");
if (pass1.toLowerCase() == "password") {
alert('Correct!');
window.open('./test/sitetwo.html',"_self");
break;
}
testV+=1;
var pass1 =
prompt('Wrong Password','Try again');
}
if (pass1.toLowerCase()!="password" & testV ==3)
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
Does anyone of you know how to code this? Thank you for your help.
Login prompt is just one of possible approaches to hide information on your website. You have to decide first what are you trying to hide. For instance, if you if are providing some paid information to your clients - you can send the information itself by mail (instead of password). If you want to hide some part of site from other people - you can just give it weird url, like site.com/jkhgdsdkgf
Creating login backend with php and database obviously requires your php, mysql (or other database) and server administration skills and completely depends on details of your task, so it's hard to provide a useful advice here.
In my opinion, you should use a database to store all your credentials (like username, password, etc..)
If you don't know how to do it, you should know that if you want to run your php code, you need a php server and somewhere to put your db.
Here is how to set up a php server with Apache
https://www.ultraedit.com/support/tutorials-power-tips/uestudio/local-php-mysql-dev-environment.html
Here is how to set up a db with PhpMyAdmin
https://www.siteground.com/tutorials/phpmyadmin/create-populate-tables/
You need a login.php (where you log in), a test.php page (then you put in it whatever you want) and a check_User.php page (where to control if the credentials are correct).
Login.php
<html>
<head> <title>Login</title> </head>
<body>
<form action="check_User.php" method="post" id="login_form">
<label><b>Username</b></label>
<!-- USERNAME -->
<input type="text" placeholder="Enter Username" name="username" required>
<!-- PASSWORD -->
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<!-- LOGIN -->
<button type="submit">Login</button>
</form>
<body>
</html>
check_User.php
<?php
session_start();
$_POST["username"] = htmlspecialchars($_POST["username"]);
$_POST["password"] = htmlspecialchars($_POST["password"]);
$link = mysqli_connect("your_host", "your_db_username", "your_db_password", "your_db_name");
$query = "SELECT username, password
FROM your_db_name
WHERE username = \"".$_POST["username"]."\" AND password = \"".$_POST["password"]."\"
";
mysqli_query($link, $query);
$rows = array();
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
$rows[] = $row;
/* correct match */
if(mysqli_affected_rows($link) == 1)
{
$_SESSION["username"] = $_POST["username"];
$_SESSION["password"] = $_POST["password"];
}
if(isset($_SESSION["username"]) && isset( $_SESSION["password"]))
header("Location:test.php");
else {
alert("Wrong username or password");
}
?>
test.php
<?php
session_start();
// not logged in, not showing this page
if((!isset($_SESSION["username"]) || !isset( $_SESSION["password"]))
header("Location:login.php");
?>
<html>
....whatever you want this page to do
</html>

How to pass table data from PHP to javascript to display it in the html form onclick of a submit button

I've a form where i have 4 buttons which are used for "insert, update, delete and retrieve" operations for a table. I can fill in the fields and click any button and respective operations take place. The DB operations takes place in PHP. But when the data is being displayed, it goes to a separate page. I want the table data to be displayed in the same page. I know it's possible using javascript or something but I'm pretty new to this coding. So im getting very confused. Have been trying for the past 3 days. Nothing worked out. If anyone could teach me clearly.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<h2>SELECT THE OPERATION YOU WANT TO PERFORM<h2>
<form method="post" action="open.php">
Id: <input type="text" name="Id" />
Name: <Input type="text" name="Name" />
BloodGroup: <input type="text" name="BloodGroup" /><br /><br />
<input type="submit" name="insert" value="Insert" />
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
<input type="submit" name="retrieve" value="retrieve" />
</form>
</body>
</html>
PHP:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'DB';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_error())
{
die("couldn't connect" . $conn->connect_error());
}
$id = $_POST['Id'];
$name = $_POST['Name'];
$blood = $_POST['BloodGroup'];
if(isset($_POST['insert'])){
$insert = "Insert into ins(Id, name, BloodGroup) values ('$id','$name', '$blood')" ;
if($conn->query($insert) === TRUE) {
echo ("Input data entered successfully");
} else {
echo ("Input data failed to be entered" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['update'])) {
$update = "update ins set Name='".$name."', BloodGroup='".$blood."' where Id='".$id."'";
mysql_query($update);
if($conn->query($update) === TRUE) {
echo ("Data updated successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
} elseif(isset($_POST['delete'])) {
$id = $_POST['Id'];
$delete = "delete from ins where Id='".$id."'";
if($conn->query($delete) === TRUE) {
echo ("Data deleted successfully");
} else {
echo ("Data cant be updated" . $conn->error());
}
$conn->close();
}
else {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM ins WHERE Id = ".$id;
if ($result=mysqli_query($conn,$retrieve))
{
while ($row=mysqli_fetch_row($result))
{
echo '<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>
<tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
</tr>
</table>';
}
mysqli_free_result($result);
}}
$conn->close();
?>
You can do it by using two method.
First: Create two file one for display your work another for operation.
when you submit your form it will go on operation page and when after opration is complete you have to set page location to working page like this.
header('location:working page.php');
Second: by using Ajax.
The easiest way to do this is that you should use ajax for this. On clicking each of the buttons send the action to separate files or methods. Retrieve whatever comes depending on the type of which action was submitted and successfully update the page.
For eg: If you are retrieving then on click of retrieve you send it to some page where you retrieve the details and return it to the page and just update it. It's pretty easy if you do some google on this. Make sure all your button actions go to proper respective page.
Hope this was helpful.
As you mentioned this is one example here: for retrieving(I expect you know how to call another file using ajax and return values.)
$.ajax({
url: 'retrieve.php',
type: 'post',
data: { id: id, name: name, blood_group: blood_group },
success: function(your_success_variable) {
Here your_success_variable can be an array or json whatever you wish to send from the other file back just don't forget to return
$('#blood_group').value(your_success_variable['blood_group]);
}
});
When the user clicks a SUBMIT-button, your FORM is submitted to open.php on your server. The browser is then taken to that page; displaying the output of your PHP script.
If you don't want to redirect the user, use AJAX in JavaScript as suggested above. There's a nice example at: How to make an AJAX call without jQuery?
The neatest way is to use jQuery, but it's more pedagogical to follow the plain JavaScript example. Essentially, you change your <input type="submit"> to <input type="button">, and add onClick="performAction('insert');" to each button (with the action string according to each operation). The function performAction(act) is declared in JavaScript in your HTML page, and creates an (asychronous!) AJAX call to your open.php script.
Right now you're submitting the FORM as POST-data. The AJAX call will have to pass the data as (URL-encoded!) GET-data, so performAction(act) appends the FORM data onto the call to open.php. (I presume it's possible to call AJAX with POST-data, and do all this in a more elegant way, but this will work. Hopefully a nice learning example.)
function performAction (act) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
alert('Request OK, result was: ' + xmlhttp.responseText);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
var GET_encoded_params = "action=" + act
+ "&Id=" + encodeURIComponent(document.forms[0].Id.value)
+ "&Name=" + encodeURIComponent(document.forms[0].Name.value)
+ "&BloodGroup=" + encodeURIComponent(document.forms[0].BloodGroup.value);
xmlhttp.open("GET", "open.php?" + GET_encoded_params, true);
xmlhttp.send();
}
Note that your PHP script might have to "get" the GET-data slightly different than you're getting the POST-data now, but that should be a minor change. You will also need to get the desired action (insert, update, delete, retrieve) from the new action parameter.
Code was borrowed from How to make an AJAX call without jQuery? and modified without actually testing. Beware of typos :) and have fun!
retrieve button can be placed in a new form where action will be on the same page or empty right now you have placed in a form where action is open.php so every action is performing on that particular page.This will definitely help you if any error occurs let me know.
else if(isset($_POST['retrieve'])) {
$id = $_POST['Id'];
$retrieve = "SELECT * FROM `ins` WHERE `Id` = '".$id."';
if ($result=mysqli_query($conn,$retrieve))
{
while ($row=mysqli_fetch_row($result))
{?>
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>
<tr>
<td><?php echo $row[0];?></td>
<td><?php echo$row[1];?></td>
<td><?php echo$row[2];?></td>
</tr>
</table>
<?php }
mysqli_free_result($result);
}}?>
In your code you are directly printing the echo statement in the while loop.Just use a variable $msg which will store all the contents.So your code will be
<?php
$msg="";
$msg.= '<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Blood Group</td>
</tr>';
while ($row=mysqli_fetch_row($result))
{
$msg.=' <tr>
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
</tr>;'
}
$msg.='</table>';
?>
After this in your html just echo the variable $msg
so your html code will be
<body>
<h1></h1>
<form>...</form>
<?php echo $msg;?>
</body>

Why my AJAX code is unable to get data from php?

I'm trying to see whether a particular name I entered is on the list or not. And I want the response in XML. I've tried whatever I could but not getting the result. (I'm using firefox by the way).
HTML
<html>
<head>
<script type="text/javascript" src="javer.js"></script>
</head>
<body>
<h1>Testing ajax!</h1>
<form onsubmit="changer('inputing')">
enter name <input type="text" id="inputing" />
<input type="submit" />
</form>
<p id="ch">enter name to check</p>
</body>
</html>
JAVASCRIPT
function changer(a) {
var mo = new XMLHttpRequest();
var qry = document.getElementById(a).value;
mo.onreadystatechange = function() {
if(mo.readyState == 4 && mo.status == 200) {
var res = mo.responseXML;
document.getElementById("ch").innerHTML = res.firstChild.nodeValue;
}
}
mo.open("GET", "appr.php?name=" + qry, true);
mo.send(null);
}
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo "<cover>";
$b = array("sam", "norton", "maya", "sijosh", "noor", "timothy");
$c = $_GET["name"];
if(in_array($c, $b)) {
echo "he is here";
}
else { echo "sorry... we dont know him"; }
echo "</cover>";
?>
You probably don't see what is happening as the form gets submitted the non-ajax / regular way as well.
You can avoid that by using for example:
<form action='' onsubmit="changer('inputing'); return false;">
Although ideally you would get rid of the inline javascript altogether and handle everything in a javascript event handler.
Well at last I figured it out! There were two problems. First one was that the page was getting refreshed every time I submit the form, as you guys said. I corrected it. The second problem was in the parsing of XML data. I transferred the XML to the variable 'res' but after that I had to get the 'documentElement' from the XML. So I added another variable 'xmlde'.
xmlde = res.documentElement;
Then,
document.getElementById("ch").innerHTML = xmlde.firstChild.nodeValue;
Problem was solved!

don't understand why i'm not changing my php variable with my script

I'm trying to teach myself how to use AJAX with PHP. However, I am unable to get my (likely broken) AJAX code to change the value of my $things variable. Instead, what happens is the index.php page gets reloaded and a brand new button gets added. Here is my code:
<?php
$things = 0;
?>
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<script>
function changeMe()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("changetest").innerHTML=xmlhttp.responseText;
}
}
var things = "<?php echo $things; ?>";
things++;
xmlhttp.open("GET","index.php?things="+things,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo "<p>Things = <span id=\"changetest\"" . $things . "</span></p>";
?>
<button type="button" onclick="changeMe()">Change Content</button>
</body>
</html>
Any clue as to where I'm messing up?
There are at least two problems I can see:
You are not using the variable you are sending back to the server $_GET['things'] anywhere. Instead you are always setting it to 0 so you will never see anything else;
You are posting to the original php file. That means that the response will be the complete html page, including the head, etc. You probably want a separate file to only send back what you really need.
An example of a separate php file would just be to echo out what was sent in:
<?php
echo 'I sent the number: ' . intval($_GET['things']);
And now you should make an ajax request to this file and not index.php.
You should remove the quotes around "<?php echo $things; ?>"; and make it var things = <?php echo "'".$things."'"; ?> instead.

Categories

Resources