javascript — реализация необходимого входа в систему с помощью jQuery File Upload

Мне нужно предложение о самом простом способе ввести требуемый логин пользователя для загрузки файла jQuery. На главной странице сайта пользователи авторизуются с помощью электронного адреса и пароля. Затем мы используем $_SESSION[email] весь сайт, чтобы разрешить или запретить доступ к страницам в зависимости от того, вошел ли пользователь в систему.

До сих пор это работало нормально на всех страницах PHP, и ниже приведен пример используемого кода:

<?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 } ?>

Форма входа ниже, если вам нужно это увидеть:

<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;"><a href="nonadmin_user_forgot_password.php" target="_blank" title="Reset Your Lost Password">Forgot Password?</a></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 /><a href="/includes/register-user.php" title="Register with us!" target="_self">Sign Up</a> is <em>quick</em> and <em>easy</em>!</span></div></td>

</table>
</form>

Это файл PHP для входа в систему:

<?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.";
}

?>

И это Логин 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>

Я попробовал несколько методов, и все они потерпели неудачу. Я попытался использовать стандартный код (верхний образец кода), который использовался на всех других страницах в верхней части jQuery File Upload index.html, и это не пойдет.

Я также попытался добавить этот стандартный код (верхний образец кода) в jQuery File Upload UploadHandler.php, где строка @session начинается …

protected function get_user_id() { //
@session_start();
return session_id();
}

…и снова это не сработало. Теперь все могут открыть страницу загрузки файлов jQuery и начать загружать файлы, что не очень хорошо. Я думаю, что, может быть, мне нужно отказаться от отображения всей страницы, если пользователь не вошел в систему, и просто показать страницу … и затем, если в этот момент нажата кнопка загрузки файла, произойдет сбой загрузки, если они не вошли в систему?

Если у вас есть предложение, как заблокировать всю страницу на основе логина, дайте мне знать. Если у вас есть предложение о том, как заблокировать загрузку файла на основе логина, дайте мне знать. Если у вас есть какие-либо предложения по какому-либо вопросу, дайте мне знать, что я весь слух, и заранее благодарю за любую помощь, которую вы можете оказать!

0

Решение

Почему бы просто не проверить, если

if(isset($_SESSION['email']))

и если это так, выполнить скрипт загрузки файла, если нет, не запускать скрипт и вернуть ошибку

if(!isset($_SESSION['email']))
{ actual upload script }
else
{ echo "I dont think so hombre" }
1

Другие решения

Других решений пока нет …