I am needing a suggestion on the easiest way to implement required user login for the jQuery File Upload. On the site home page users login with an email and password. We are then using $_SESSION[email] site wide to allow or disallow accessing of pages depending on whether or not the user is logged in.
So far this has worked fine on all PHP pages and below is the example of the code being used:
<?php
// at the top most of the page
session_start();
// Checking user login credentials
if(!isset($_SESSION['email'])){
// Alerting the user they must be logged in
echo "<script>alert('You must be logged in to access this page.')</script>";
// Sending the non-logged in user back to the home page
echo "<script>window.open('../index.php','_self')</script>";
}
// If the user is logged in let them see the page
else { ?>
// added to the very last line of the page
<?php } ?>
The login form is below in case you need to see that:
<form method="post" action="#">
<table width="90%" border="0" align="center" bgcolor="white">
<tr>
<td bgcolor="ffffff" colspan="2" align="center"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="password" id="password"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" name="login" id="login" value="Login"></td>
</tr>
<tr>
<td colspan="2" align="center"><h3 style="margin-top:7px;">Forgot Password?</h3></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2" align="center"><div style="padding-top:5px;"><span style="font-size:20px;">Don't have an account?<br />Sign Up is <em>quick</em> and <em>easy</em>!</span></div></td>
</table>
</form>
This is the Login PHP file:
<?php
session_start();
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");
// Let's get the mail and password from the Login Form
$email=$_POST['email1'];
$password= ($_POST['password1']);
// Let's see if the entered email is in the database and if it is retrieve the password
$result = mysqli_query($conn, "SELECT * FROM nonadmin_user_login WHERE email='$email'");
// Create variables for the database result, password and email
$data = mysqli_fetch_array($result);
$bcrypt_pass = $data['nonadmin_user_pass'];
$email_match = $data['email'];
// If the email and password match up
if (password_verify ($password, $bcrypt_pass) == 1 AND $email == $email_match) {
// Start a session bound to the email
$_SESSION['email']=$email;
// Alert the user of a successful login
echo "Successfully Logged in.";
// Make a variable for the date and time
$mysqltime = date ("Y-m-d H:i:s");
// Update the database to show the time of the user's last successful login
mysqli_query($conn, "UPDATE nonadmin_user_login SET last_login='$mysqltime' WHERE email ='".$email."' ") or die(mysqli_error($conn));
}
// Alert the user of a failed login
else{
echo "Email or Password is wrong please try again.";
}
?>
And this is the Login JS:
<script>
// Let's get this party started
$(document).ready(function(){
// Binding this to the login form submit button
$("#login").click(function(){
// Setting variables and binding them to the login form fields
var email = $("#email").val();
var password = $("#password").val();
// Checking if the email or password is empty
if( email =='' || password ==''){
$('input[type="text"],input[type="password"]');
$('input[type="text"],input[type="password"]');
// Alerting the user of empty email and/or password
alert("Please fill all fields.");
// If the fields are not empty
}else {
// Posting the entered email and password to log-me-in.php
$.post("log-me-in.php",{ email1: email, password1:password},
// Function to event handle incorrect email or password
function(data) {
// If the email is invalid
if(data=='Invalid Email.......') {
$('input[type="text"]');
$('input[type="password"]');
// Alert the user of invalid entry
alert(data);
// If email and/or password don't match the database query
}else if(data=='Email or Password is wrong please try again.'){
$('input[type="text"],input[type="password"]');
// Alert the user of invalid entry
alert(data);
// If nothing went wrong so far it's time to login and alert user of login success
} else if(data=='Successfully Logged in.'){
// Let's refresh the window so the sidebar signin block can swap to the logged in block
window.location=window.location;
$("form")[0].reset();
$('input[type="text"],input[type="password"]');
alert(data);
} else{
alert(data);
}
});
}
});
});</script>
I have tried several methods and all of them failed. I tried using the standard code (uppermost code sample box) used on all other pages at the top of the jQuery File Upload index.html and it's a no go.
I also tried to add this standard code (uppermost code sample box) to the jQuery File Upload UploadHandler.php where the #session start line of code is...
protected function get_user_id() { //
#session_start();
return session_id();
}
...and once again it did not work. The way it stands now anyone on earth can open the jQuery File Upload page and start loading files which is not okay. My thought is maybe I need to give up on not displaying the whole page if the user is not logged in and just let the page display... and then if the upload file button is clicked at that point fail the upload if they are not logged in?
If you have a suggestion how to block the whole page based on login let me know. If you have a suggestion on how to block the file upload based on login let me know. If you have any suggestions on anything at all let me know I am all ears and thanks in advance for any help you can lend!
Why not just check if
if(isset($_SESSION['email']))
is set and if so execute file upload script, if not, don't run the script and return an error
if(!isset($_SESSION['email']))
{ actual upload script }
else
{ echo "I dont think so hombre" }
Related
I have a form.
<form action="form.php" method="POST" name="form1" id="f1">
On this form is an input for a name.
<input type="text" class="form-control" id="n1" placeholder="Name" required>
The user inputs their name and clicks submit, the form.php then kicks in and this name is emailed to an email address.
$name = $_POST['n1'];
If this is successful the user is redirected to another page via;
header("Location: /anotherpage.html");
Up to this point everything works fine.
On this page is a HTML table with a table data cell;
<td id="table1"></td>
Q. What I am trying to do is when the user is redirected to this page the name they submit appears in the tables data cell.
I have tried a couple of things with no success.
On the HTML side;
value="<?php echo $name;?>" & value="<?php echo $_POST['n1'];?>" within the td tag.
<?php echo $name;?> & <?php echo $_POST['n1'];?> between the td tags.
& on the PHP side after the redirect header;
getElementById('n1').value = $name;
getElementById('n1').value = $_POST['n1'];
Is there a way of doing this?
Look forward to hearing from anyone
Kind Regards
You can send the name over the url using the header using PHP...
// check the submission of your form using the name set in the submit button...
if(isset($_POST['submit'])){
// DO NOT SKIP ON SANITIZING YOUR INPUTS!!!!!
// This example is very basic, I am not showing how to sanitize inputs
$fname = filter_var(strip_tags($_POST['fname'], FILTER_SANITIZE_STRING));
$lname = filter_var(strip_tags($_POST['lname'], FILTER_SANITIZE_STRING));
// do your email stuff
// after you have done all your other code, send the name
// key/value pair over the url using the header...
header("Location: someotherpage.html?fname=".fname ."&lname=".lname);
}
Once you have sent the values over the url to the someotherpage.html page you can use URLSearchParams to search the url for key parameters to get their paired value/s. window.location.search => The query string portion of the URL. This includes the question mark, and everything following. Use .get() to get the url's parameters using their key. Then you can assign them using javascript with the dataset attribute => element.dataset.fname = firstName.
let parameters = new URLSearchParams(window.location.search);
let firstName = parameters.get('fname');
let lastName = parameters.get('lname');
let div = document.getElementById('data');
div.dataset.fname = `${firstName} ${lastName}`;
Returns the following on someotherpage.html :
I have a site that is used by operators in the factory that don't log in so have zero permissions, as well as users in the office who have permissions.
What I need to do is, upon the click of a button that submits a note to the SQL database for a certain job and operation number, send a pop up or some kind of alert message to those that are logged in.
This could be in the form of simply opening a new tab or any method really.
What I've got so far is a cell that highlights the relevant job that has a note, but I want to provide an alert for when a new message is present, as opposed to the just old note displaying the highlighted cell.
Can anybody please provide some suggestions?
EDIT:
Sorry, here's the code on the operator's page, that requires no permissions to update the database.
<script type="text/javascript">
function saveNotes() {
var jobID = "<?php echo $_GET['jobID']; ?>";
var operation = "<?php echo $_GET['operation']; ?>";
var nnotes = document.getElementById('notes').value;
if (nnotes == 'null') nnotes = "";
sendAsync("editDatabase.php?sql=UPDATE+operations+SET+notes='"+nnotes+"'+WHERE+jobID="+jobID+"+AND+operation="+operation);
alert("Your note has been submitted")
}
</script>
<body>
<input method="post" onLoad="initialise();" class="onload auto notes" data-type="text" style="display:inline;" id="notes" value="<?php echo $row["notes"]; ?>" size="15" placeholder="Type a note..">
<button onClick="saveNotes();" style="font-size:25px;padding-left:15px;padding-right:15px;" alert="Your note has been sent" >SEND</button></td>
What I want is for an alert of some kind to pop up on a page titled 'home.html' for users with permission>1
I hope that helps..
I am currently working on a project for a web development class I am taking in which I have to create a registration page for a marketing product and add user details to a database. I've got the basic code working but, after speaking with my teacher, I need to add some form of data validation to the website. I have tried marking the input fields as required in HTML5 as well as using a separate JavaScript Validator but nothing works, if I submit the form, my PHP script process without the data being validated.
My goal is for the data to validated directly on the form, so that error messages appear on the form itself versus on a separate page. I currently have a check in my PHP code to query the database for an already existing email and kill the script and echo an error but it does so on another page.
Below is the code I have so far with the JavaScript validator in place. I am still learning PHP and HTML so I'm lost as to what else I can try. Can anyone help?
HTML CODE
<!DOCTYPE HTML>
<html>
<head>
<title>Registration</title>
<script src="scripts/gen_validatorv4.js" type="text/javascript"></script>
</head>
<body>
<div id="register">
<fieldset style="width:30%"><legend>Registration Form</legend> <!-- Give the table a width of 30% and a title of Registration Form -->
<table border="0"> <!-- Add border to table -->
<tr>
<form method="POST" action="registration.php" id="register"> <!-- Use POST to submit form data to registration.php -->
<td>First Name</td><td> <input type="text" name="firstname" ></td> <!-- Input field for First Name -->
</tr>
<tr>
<td>Last Name</td><td> <input type="text" name="lastname" ></td> <!-- Input field for Last Name -->
</tr>
<tr>
<td>Address 1</td><td> <input type="text" name="address1" ></td> <!-- Input field for Address 1 -->
</tr>
<tr>
<td>Address 2</td><td> <input type="text" name="address2"></td> <!-- Input field for Address 2 -->
</tr>
<tr>
<td>City</td><td> <input type="text" name="city" ></td> <!-- Input field for City -->
</tr>
<tr>
<td>State</td><td> <input type="text" name="state" ></td> <!-- Input field for State -->
</tr>
<tr>
<td>Zip Code</td><td> <input type="text" name="zipcode" ></td> <!-- Input field for Zip Code -->
</tr>
<tr>
<td>Phone Number</td><td> <input type="text" name="phonenumber" ></td> <!-- Input field for Phone Number -->
</tr>
<tr>
<td>Email</td><td> <input type="text" name="email" ></td> <!-- Input field for Email -->
</tr>
<tr>
<td>Sign up to marketing emails?</td><td> <input type="radio" name="marketingaccept" value="yes"></td> <!-- Radio button to be checked if user wants to sign up for marketing emails -->
</tr>
<td><input id="button" type="submit" name="submit" value="Register"></td> <!-- Submit button -->
</form>
<script type="text/javascript">
var frmvalidator = new Validator("register");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("firstname","req","Please provide your first name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("lastname","req","Please provide your last name");
frmvalidator.addValidation("address","req","Please provide your address");
</script>
</tr>
</table>
</fieldset>
</div>
</body>
</html>
PHP CODE
<?php
define('DB_HOST', 'localhost'); // Define database host
define('DB_NAME', 'andrewha_fhsuproject1'); // Define database name
define('DB_USER','*******'); // Define database username
define('DB_PASSWORD','********'); // Define database password
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to host or present an error if connection fails
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to database or present an error if connection fails
function newregister() // Create function newregister()
{
$firstname = trim($_POST['firstname']); // Grab data from the first name field and trim excess white space
$lastname = trim($_POST['lastname']); // Grab data from the last name field and trim excess white space
$address1 = trim($_POST['address1']); // Grab data from the address1 name field and trim excess white space
$address2 = trim($_POST['address2']); // Grab data from the address2 name field and trim excess white space
$city = trim($_POST['city']); // Grab data from the city field and trim excess white space
$state = trim($_POST['state']); // Grab data from the state field and trim excess white space
$zipcode = trim($_POST['zipcode']); // Grab data from the zipcode field and trim excess white space
$phonenumber = trim($_POST['phonenumber']); // Grab data from the phonenumber field and trim excess white space
$email = trim($_POST['email']); // Grab data from the email field and trim excess white space
$marketingaccept = $_POST['marketingaccept']; // Check to see whether the marketingaccept radio button is checked
$sql="SELECT email FROM RegisteredUsers WHERE email='".$email."'"; // Look through existing emails to prevent duplication
$resul=mysql_query($sql); // Perform above query
$num = mysql_num_rows($resul); // Check above query to see if any rows match
if ($num !=0){ // If a match is found...
die("Sorry, you can only register once!."); // ...the script is killed and an error is presented.
} else // If no match is found, the script continues.
$query = "INSERT INTO RegisteredUsers (firstname,lastname,address1,address2,city,state,zipcode,phonenumber,email,marketingaccept) VALUES ('$firstname','$lastname','$address1','$address2','$city','$state','$zipcode','$phonenumber','$email','$marketingaccept')"; // Create variable to insert Grabbed data to database table and corresponding columns
$data = mysql_query ($query)or die(mysql_error()); // Run above query or kill the script if an error is presented
if($data) // Verify $data was run
{
header('Location: thankyou.html'); // Redirect to thankyou.html
exit(); // End script
}
}
if(isset($_POST['submit'])) // Check to see if submit button was hit...
{
newregister(); // ...and go to newregister()
}
?>
I don't know if you underestimate or misunderstand the results of validation so forgive me if I am long winded here.
Your validation on the client is exactly that - it will only validate certain conditions are met on the client. Once the data is sent to the server, without validation/sanitization, you risk someone tampering and thrashing your database, or worse.
It would be possible for example to skip your client validation entirely and just enter an address in the address bar or via a script that would pretend to be a web browser sending data to your server.
The way your code is written above, the server will receive data and it can be engineered (rather easily) via a single input box to delete all the data in your database, or pending the server configuration, possible to destroy your server.
An article elsewhere on stackoverflow should help discuss this subject in greater detail. I just did a quick search and found this one: What's the best method for sanitizing user input with PHP? Read some of the answers.
Now... with regards to validating your form data, I recommend you use jquery. It is a javascript add on library (meaning its entirely written in javascript) but it is cross browser compatible (there are variations in how javascript in some browsers handles data so your plain javascript might or might not work on all browsers. However code written in jquery will work in all browsers).
The simplicity of validating your form data could be done by adding a
class="required"
in to each input tag in your form.
Then, with jquery, you could perform something like the following
// e will contain input field names of input tags that require but are missing data
var e=new Array();
// Get all input boxes with class "required", check the data input
// if the input length is less than one character in length, it
// will add the id tag to the "e" array.
$("input.required").each(function(){
if( $(this).val().length<1 )
{
e.push( $(this).prop("id") );
}
});
// If e array has more than zero elements, it means more than zero input
// input tags are missing data and thus an alert is shown
if( e.length>0 )
{
alert( "The following data fields are missing data:\n"+e.join(", ") );
}
I have a form, something like:
<form action="" method="post">
<label class="reg_label" for="name">Name:</label>
<input name="name" type="text" class="text_area" id="name"/>
.... etc...
</form>
To submit the form, the user must also first complete a CAPTCHA. This works great, and only allows form submission for perfect matches. Reloading the page will result in a new CAPTCHA. Pressing the "back" button will also display a new CAPTCHA.
When the user submits the form, it is verified via javascript, and that all works dandy, and then it is submitted (and emailed) via a separate php script:
<?php
include('connect_to_mysql.php');
$webMaster = 'my#email.com';
$name = mysqli_real_escape_string($db_conx, $_POST["name"]);
$phone = mysqli_real_escape_string($db_conx, $_POST["phone"]);
$email = mysqli_real_escape_string($db_conx, $_POST["email"]);
$message = mysqli_real_escape_string($db_conx, $_POST["message"]);
$emailSubject = 'Contact Form Submission';
$body = <<<EOD
Name: $name
Email: $email
Phone: $phone
Message:
$message
EOD;
$headers = "From: $email\r\n";
$success = mail($webMaster, $emailSubject, $body, $headers);
header('Location: ../thankyou.html');
?>
This all works as expected, and I am satisfied with the escape strings for now. The form catches non-emails, and the CAPTCHA works every time. But some clown just sent me 128 SIMULTANEOUS form submissions, and I am wondering how this individual did it.
Every field was filled out "9999.9". When I try it, I get errors for the name, phone number and email. I can't even submit the form with that data. Even if I could, I would only be able to send it once because of the CAPTCHA (PHP).
The only hole I can see, and it IS a hole (just tried it), is to type in the URL of the external script directly. So, a bad guy could write his own script, assign the variables (to POST) and then call my contact function 128 times.
While I'm working on righting that wrong, are there any other obvious gaping holes that someone could use for multiple form submissions like that, while bypassing the CAPTCHA (which is PHP)? Obviously just turn off JS to get around the validation.
I can post more code if needed, but just assume the JS is turned off, leaving only the PHP CAPTCHA check - which has nothing to do with the actual submission of the form, and changes on BOTH "back" and "reload" operations.
Thanks in advance.
CAPTCHA CODE
Captcha.php
<?php
session_start();
$rand = md5(rand(0,999));
$value = substr($rand, 10, 5);
$_SESSION['cap_key'] = $value;
... do some drawing stuff to make the CAPCHA, which is an IMAGE and cannot be read without some fancy character-recogntion code...
?>
Within the contact form file (called when form submitted)
<?php
session_start();
if ($_POST['submit'])
{
if ($_POST['captcha'] == $_SESSION['cap_key']) // Success
{
include('scripts/contact.php');
}else if($cap != 'Eq') // If wrong captcha entered
{
... reload page after sanitizing the inputs...
}
}
?>
But like I said, the CAPTCHA changes every reload of the page.
Thanks again.
I want to make a multi step registration form. When user enters his name it, it checks in the database whether that username exists or not, then it should go to 2nd step where he will enter new password and once submitted for that username an OTP will be sent to registered mobile number.
In 3rd step OTP confirm page should open and on giving correct entry the process should be completed. I have written a basic code to achieve this, but I want it to happen step by step, in one page itself.
For this functionality you have to work with ajax
for example when user enter username you can post request like this
.JS file
var username = $('#username_textfield_id').val();
$post('ajax.php',
{data:username}
).success(function(responce){
if(responce == 'available')
$('#password_field').css({display:'block'}); // password field will be hidden by default
else
alert(responce);
});
You can call above function on focus out of text field or you can put button. :-)
ajax.php file
<?php
$username = $_POST['data'];
/* check username in database */
if(username available )
echo "available";
else
echo "username already taken";
?>
as per this files you can make steps in form.
you form will be something like this
<input type="text" id="#username_textfield_id"> </br>
<input type="text" id="#password_field" style="display:none"></br>
make 4 small php files for each step. Each php should check if it is valid for rendering.
if(!user.hasEmail())
else if(user.hasEmail() & !user.haspassword())
include php1
else if(user.haspassword() && !user.hasAddress())
include php2
else if(user.hasAddress && !user.isconfirmed())
include php3