Stop Upload to SQL database if permission is not granted - php

I need to stop data being uploaded to the database when permissions are not granted. Is there a way to kill the session and only permit my script to upload data if permission has been granted.
PAGE 1:
<?php
session_start();
$_SESSION['user']='studentadmin';
?>
<!DOCTYPE html>
<html>
<head>
<style >
body {background-color: rgb(255,66,69);}
h3{font-size: 250%};
h4{font-size: xx-small;}
</style>
<title>Student Examinations 2017 </title>
<body>
<font style="font-family: Arial;";
<h4>Chichester Secondary School</h2>
<div align="center">
<h3>End of Year Examinations 2017</h1>
<i><p>Using the form below please submit examination results for the end of the academic year.</p></i>
<i><p>This years results are represented with the new government grading system. '9-1' rather than 'A*-G' </i></p>
<form action="MySQL.php" method="POST"><br>
<b> <br> Student: </b><br>
<br> First Name <br>
<input type="text" name="fname"><br/>
Last Name <br>
<input type="text" name="lname"><br/>
<br>
<br><b>Exam Board: <br></b><br>
<input type="radio" name = "examboard" value="AQA" checked> AQA
<input type="radio" name = "examboard" value="EdExcel" checked> EdExcel <br><br>
<b><br>Subject Grades: </b><br>
<br>
English<br>
<select name="Grade">
<option value="-">-</option>
<option value="9">9</option>
<option value="8">8</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br>
Maths<br>
<select name="Grade2">
<option value="-">-</option>
<option value="9">9</option>
<option value="8">8</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br>
Science<br>
<select name="Grade3">
<option value="-">-</option>
<option value="9">9</option>
<option value="8">8</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br>
<br> Additional Comments <br>
<textarea name ="additionalcomments" rows="2" cols="30"></textarea><br/>
<input type="submit" name="submit">
<input type="reset" name="reset">
<br>
</head>
</form>
</body>
</html>
PAGE 2:
<?php
session_start();
if (isset($_SESSION ['user'])) {
echo "Student record successfully created by user: " .$_SESSION['user'];
unset($_SESSION['user']);
} else {
echo 'You do not have permission to access this page. ';
}
?>
<?php
$DB_HOST = "localhost";
$DB_USERNAME = "admin";
$DB_PASSWORD = "chichester";
$DB_NAME = "results";
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$examboard = $_POST["examboard"];
$grade = $_POST["Grade"];
$grade2 = $_POST["Grade2"];
$grade3 = $_POST["Grade3"];
$additionalcomments = $_POST["additionalcomments"];
$conn = new mysqli($DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);
$sql = "INSERT INTO studentresults (name,lastname,examboard,additionalcomments,grade, grade2, grade3) VALUES ('$fname','$lname','$examboard','$additionalcomments','$grade','$grade2','$grade3')";
if ($conn->query($sql) === TRUE) {
}
$conn->close();
?>
<html>
<head>
<style >
body {background-color: rgb(255,66,69);}
h3{font-size: 500%};
h4{font-size: x-large;}
</style>
<title>Results </title>
<body>
<font style="font-family: Arial;";

When someone "doesn't have permission" this is what you do:
echo 'You do not have permission to access this page. ';
You simply tell them they don't have permission. But you continue to execute the code anyway. If you want the script to stop processing, something like the exit command would accomplish that:
exit('do not have permission to access this page. ');
Also of note... You're outputting a message indicating that a record was successfully inserted before you actually insert anything into the database. That's... optimistic. You should really only be indicating success to the user if the operation is successful. If the operation fails in some way, your users are going to be very confused.

This is how you start your code:
<?php
session_start();
$_SESSION['user']='studentadmin';
?>
Here you assume that studentadmin has logged in and you stored that as user. It is incorrect practice. Somehow you need to make sure that your admin is valid instead of assuming it.
Later you have this:
session_start();
if (isset($_SESSION ['user'])) {
echo "Student record successfully created by user: " .$_SESSION['user'];
unset($_SESSION['user']);
} else {
echo 'You do not have permission to access this page. ';
}
As David already pointed out, here, if there is no $_SESSION['user'], then you just echo a message and continue anyway. His suggestion of using exit is needed here, but only if you remove the part where you assign a value to $_SESSION['user'] anyway. However, damage is already done, users are already considered to be studentadmin. May I suggest that you should use a different key from now on, like $_SESSION['username'], so old, invalid $_SESSION['user'] values will not allow things which should not be allowed? But this will only work if you have a proper login screen where people enter their credentials, which are in turn validated and you only store $_SESSION['username'] if the credentials were valid.

Related

PHP and SQL - How can I make this ID into a variable?

I am making a PHP website, and I want my user ID to load into the tickets table when you order a ticket. There is a webpage where you can select the ticket, the amount, and the ID is already given as a label.
The first code adds the data to my database
function best(){
global $db, $errors;
// receive all input values from the form
$ticket = e($_POST['tickety']);
$aantall = e($_POST['aantal']);
$usidd = e($_POST['usid']);
// form validation: ensure that the form is correctly filled
if (empty($ticket)) {
array_push($errors, "Ticket is verplicht");
}
if (empty($aantall)) {
array_push($errors, "Aantal is verplicht");
}
// order ticket if there are no errors in the form
if (count($errors) == 0) {
$con = new PDO("mysql: host=localhost; dbname=website", "root", "");
mysqli_query($db, $query);
$_SESSION['success'] = "Ticket besteld";
header('location: index.php');
$query = "INSERT INTO tickety (ticket, aantal, userid)
VALUES('$ticket', '$aantall', '$usidd')";
mysqli_query($db, $query);
}
}
This code defines the input fields
<form method="post" action="ticketpag.php">
<?php echo display_error(); ?>
<div class="input_group">
ID
</br>
<input type='hidden' name='usid'>
<h4><?php
echo $_SESSION['user']['id'];
?></h4>
</input>
Ticket
</br>
<select name='tickety'>
<?php
$query = "SELECT * FROM `stok`";
$result = mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<option>".$row['naam']."</option>";
}
?>
</select>
</br>
Aantal
</br>
<select name="aantal">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
</select>
</div>
<div class="input-group">
<button type="submit" class="btn" name="bestel_btn"> Bestellen</button>
Terug
</div>
</form>
Add $_SESSION['user']['id']; to an input field instead of a label and it should work.
Example:
<input type="hidden" name="usid" id="usid" value="<?php echo $_SESSION['user']['id'];?>" />
Hidden fields are not shown to a user.
Addition:
But, as #mickmackusa mentioned, sending existing SESSION data using a POST request is a bad-practise. Instead test and see what happens when you echo $_SESSION['user']['id'] inside of best(). You should not be using POST to deliver existing SESSION data.

How do I use PHP to query my SQL database using SELECT tag in html

Basically I'd like to use the choices which the user has selected from a different select tags, and in essence store these as variables which I can then use to query my database in SQL.
My HTML code is here:
<div id ="search_elements">
<img src="UniSelect.jpeg">
<select>
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select>
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
</div>
And the type of php i would be looking to use would be:
//$con=mysqli_connect("localhost","adam","YjM3ZTYwOTQ5OWRmYWZh","adam_...");
//if (mysqli_connect_errno())
// {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
// }
// Perform queries
//$sql=mysqli_query($con,"SELECT CONTENT FROM Blog WHERE ID = 01");
//$result=mysqli_fetch_assoc($sql);
//echo $result['CONTENT'];
//mysqli_close($con);
To make it clear once more, I want to use the different values which the user selects, upon clicking a search button, have these query results shown in a table.
This solution a little differs from yours because you have no provided your form, submit button, etc. but in general, after a few changes, it should work too:
<form method="post" action="">
<img src="UniSelect.jpeg">
<select name="university">
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select name="rent_price">
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
<input type="submit" value="Submit form">
</form>
And now, to get values of these (something like this and I recommend to place it above your form):
if (!empty($_POST)) {
// Checking connection in here
$university_id = mysqli_real_escape_string($con, $_POST['university']);
$rent_price = mysqli_real_escape_string($con, $_POST['rent_price']);
$sql = mysqli_query($con, "SELECT * FROM university WHERE name = '".$university_id."'");
$result = mysqli_fetch_assoc($sql);
// Same thing goes for rent price
}

php form using array

I want to create a form using array that user can select a number and echoes the number's corresponding object name after submit. I don't know why this code does not work, could someone please teach me how to do it the right way :( Thank you so much for your time.
<form name="train" method="GET" action="test.php">
<select name="object">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="all">Show All</option>
</select>
<input type="submit" name="submit" id="submit" value="submit" size="10">
</form>
<?php
$train[0] = "pencil";
$train[1] = "macaron";
$train[2] = "notes";
$train[3] = "book";
$train[4] = "eraser";
$train[5] = "cake";
$train[6] = "laptop";
$train[7] = "mint";
$train[8] = "cup";
if ($_GET['submit']) {
$train = $_GET['obejct'];
echo "<p>I have $train!</p>";
}
?>
Thank you so much!
Looks like you're setting $train to the value of whatever the form passes for the "object" select field, and then echoing that. You would expect then to see a number between 0 and 8, or the word "all" print out, but your reference of the object key has the word "object" misspelled as "obejct", so my guess is you're getting nothing to print as the value of $train.
Either way, what you really want to do is print the value at the key in the $train array that corresponds with what was provided by the user. This means that once you've created your array, which functions as a map, you must select the item from the array that you want to print.
You also need to handle the "all" case or you will get an error.
Here's how it would look if you continue using the array option:
<form name="train" method="GET" action="test.php">
<select name="object">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="all">Show All</option>
</select>
<input type="submit" name="submit" id="submit" value="submit" size="10">
</form>
<?php
$train[0] = "pencil";
$train[1] = "macaron";
$train[2] = "notes";
$train[3] = "book";
$train[4] = "eraser";
$train[5] = "cake";
$train[6] = "laptop";
$train[7] = "mint";
$train[8] = "cup";
if ($_GET['submit']) {
if ($_GET['object'] != 'all') {
//Handle the non-all case
$value = $train[$_GET['object']]; //This references a key in your array, like $train[0]
echo "<p>I have $value!</p>";
} else {
//Handle the all case here
}
}
?>

how to display message on html page using php

I am doing project on marks management system. In the project i have a task of updating the marks of student.Suppose if the updation is successful i should display a message that it is successful otherwise
unsuccessful should be displayed. I am doing my project using php and html. The code is as follows.
update marks
user_id: <input type="text" name="userid"><br>
Branch<select name="Branch">
<option value="cse">CSE</option>
<option value="eee">EEE</option>
<option value="ece">ECE</option>
</select>
Marks<br><input type="text" name="marks" size="40"></br>
<select name="Subject">
<optgroup label="CSE">
<optgroup label="sem 4">
<option value="dbms">DBMS</option>
</optgroup>
<optgroup label="EEE">
</optgroup>
<optgroup label="ECE">
</optgroup>
</select>
Semester<select name="Semester">
<option value="sem 1">SEM 1</option>
<option value="sem 2">SEM 2</option>
<option value="sem 3">SEM 3</option>
<option value="sem 4">SEM 4</option>
<option value="sem 5">SEM 5</option>
<option value="sem 6">SEM 6</option>
<option value="sem 7">SEM 7</option>
</select>
<input id="button" type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>
The following one is php code
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function updatem()
{
session_start();
$marks=$_POST['marks'];
$branch=$_POST['Branch'];
$semester=$_POST['Semester'];
$subject=$_POST['Subject'];
$userid=$_POST['userid'];
if((!empty($_POST['userid']))
&&(!empty($_POST['marks']))
&&(!empty($_POST['Subject']))
&&(!empty($_POST['Semester']))
&&(!empty($_POST['Branch'])))
{
$query=mysql_query("UPDATE marks_list SET marks_obt=$marks
WHERE username_id=$userid
AND branch_id=(SELECT branch_id FROM branch WHERE branch_name='$branch') AND
semester_id=(SELECT semester_id FROM semester WHERE semester_name='$semester')
AND subject_code=(select subject_code FROM subcodes WHERE
branch_id=(SELECT branch_id FROM branch WHERE branch_name='$branch')
AND
semester_id=(SELECT semester_id FROM semester WHERE semester_name='$semester'))") or die("insertion unsuccessful".mysql_error());
header("Location: update_marks.html");
}
}
if(isset($_POST['submit']))
{
updatem();
}
?>
thanks in advance..
Add this code after your update query
if(mysql_affected_rows()>0)
{
$_SESSION['message']='This is your message';
}
Now in the file Where you want to display the value
Add this code
Important Note: Always start session at the top of the page.
session_start();
echo $_SESSION['message'];

using AJAX to return values in javascript to php all on the same page

hello all im back with another question on my project. i keep getting stuck for some reason! i only started using AJAX today so i hope you will forgive my ignorance! okay first of all i have a type button and when i click on it i want it to return a number (which is the amount of a particular item the customer wants to purchase) and the name of a item. the number is selected from a dropdownlist and the name of the book is got from a input type=" hidden". to get the number from the dropdown list to php i want to use AJAX which i have set up as a method in the header of my html page. the code for this method is shown below at the moment im trying to use ajax to return the number of the item to this same php page. here is the method.
function ajax_post(myform)
{
var hr = new XMLHttpRequest();
var url = "islandshop.php";
var index = myform.quantity1.selectedIndex;
var value = document.getElementById("quantity1").options[index].value;
var variable = "value="+value;
hr.open("post", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(variable);
document.getElementById("status").innerHTML = "processing data";
}
next is where when i press the button i want just the number from the dropdown list returned to me in php. but when i clcik on the button which is my add to cart button it returns the whole page "islandshop.php" to me. but with the value at the end of the page which is not all bad at least it is returning the value. here is my form where i call the ajax_post() method with my button.
<form method="post" action="" name="form1">
<span style="color:#000"> <label for="quantity">Quantity:</label></span>
<select name="quantity1" id="quantity1" onchange="">
<option value="1" selected>1</option><option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option><option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option><option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option><option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option><option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option><option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option><option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option><option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option><option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option><option value="29">29</option>
<option value="30">30</option>
</select>
<input type="hidden" name="book1" value="cape clear island: its peopleand landscape" />
<input type="button" value="Add To Cart" name="submit1" onclick="javascript:ajax_post(this.form)"></button>
</form>
which to me seems fine. and the last part is just php tags at the end of the islandshop.php page where i try and print the value and get a copy of the whole page back. so essentially i have my page shown twice in the browser. but with the value in the second version of the page.
<?php
if(isset($_SESSION['username']))
{
echo 'Thank you you selected '. $_POST['value'];
}
?>
i think i know why im getting the whole page back when i press the button as i have the hr.open() url as this page "islandshop.php. i read something about this and it said something about sending the values to the browser and then the browser sending the variable back to a .php page which would redirect them to the original page but it wasnt explained very well. so really my main goal is to just get the value from the dropdown list back to me from the server in php form so i can use the value to do stuff on this page! thanks again for the help hopefully i wont have to post so many questions after i figure this one out. even if anyone can direct me to a good book or article on AJAX i would be delighted! cheers
If you are posting back to the same page then you can do a conditional check to see if the $_POST['value'] is set or not. If it is then do an echo, if not then display the html.
<?php
if( isset($_SESSION['username']) && isset( $_POST['value'] ) )
{
echo 'Thank you you selected '. $_POST['value'];
}
else
{
?>
<form method="post" action="" name="form1">
<span style="color:#000">
<label for="quantity">Quantity:</label></span>
<select name="quantity1" id="quantity1" onchange="">
<option value="1" selected>1</option><option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option><option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option><option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option><option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option><option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option><option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option><option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option><option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option><option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option><option value="29">29</option>
<option value="30">30</option>
</select>
<input type="hidden" name="book1" value="cape clear island: its peopleand landscape" />
<input type="button" value="Add To Cart" name="submit1" onclick="javascript:ajax_post(this.form)"></button>
</form>
<?php } ?>
I strongly advise you to take a look at the jQuery: http://jquery.com/

Categories