This is the top of my php file - what I am trying to achieve is, if the user ends up on this page after a failed login attempt which posts here - a message should be displayed in javascript outlining such failed login attempt and then redirect them back to the previous page.
Why does this happen and what can be done to fix it so the message box is displayed? Alternatively on the previous page - how do i stop the redirect if the login attempt failed?
Thanks
<?php
include("Application.php");
include("Member.php");
include("ContactDetails.php");
include("LoginDetails.php");
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$value = null;
if(isset($_SESSION['url'])) {
$value = $_SESSION['url'];
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
}
if(isset($_POST['submit'])){
$username=$_POST["username"];
$password=$_POST["password"];
$loginDetails = logUserIn($username, $password);
if($loginDetails != null && $loginDetails->getUserid() > 0){
$contactDetails = getContactDetails($loginDetails->getUserid());
$member = new Member($contactDetails, $loginDetails);
//an array of applications belong to a paticular user
$applications = getApplicationsForMember($member);
printUserApplicationSelectionForm($applications);
}else{
//login attempt failed - tell the user and redirect
if($value != null){
$path = "http://localhost" . "$value";
header("Location: $path");
echo '<script type="text/javascript">alert("Login Attempt Failed!");</script>';
}
}
}
You change locations before echoing, so the alert script is never echoed:
header("Location: $path");
echo '<script type="text/javascript">alert("Login Attempt Failed!");
Switch those around and it should work.
if you send the location header, the browser won't load the response (your script) anymore from the current page but directly change to to the new location.
What you could do is to add something like &message=failedlogin to the path before sending the Location header and then display a message in the previous page. You could also store it in the session: $_SESSION['loginsuccess']=false; and then check for this value in the previous PHP page.
Related
I have an issue with php and javascript included.
Sedning form from data index.php to edit.php
this is my edit.php file:
<script>
function ConfirmNull() {
if (confirm("Are You Sure?")) {
}
else {
window.history.back();
}
}
</script>
<?php
session_start();
// connect to database
include("connection.php");
// update records
if (isset($_POST['update'])) {
$chk=$_POST['chk'];
$manyids=implode(",",$chk);
//$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$user = $_POST['user'];
// if time is NULL ask if you are sure
if ($time == "") {
echo "<script type='text/JavaScript'>
ConfirmNull();
</script>";
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
else {
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
}
?>
Right now if the value time variable is NULL it should run javascript with the question: are you sure?
If YES continue with SQL and update the db.
If Cancell stop the php code and run windows.history.back and do NOT run SQL.
Unfortunately its updating the db when i hit Cancel.
PHP's job is to generate the HTML that gets sent to the browser. As far as PHP is concerned, all your JavaScript is just text. It doesn't have any meaning until it gets to the browser. As such, all your PHP will run before any of your JavaScript.
So the proper place to put your check is in a form submit handler in index.php, before the browser even fetches edit.php:
document.querySelector('#myForm').addEventListener('submit', evt => {
if (evt.target.querySelector('[name="time"]').value === '') {
if (!confirm('Are you sure?')) evt.preventDefault();
}
});
And you really do need to fix your vulnerable database code. As a general rule, $ should never appear in an SQL query string.
I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.
Hi i am trying to implement notifications when certain event happens in PHP. Suppose a user is changing its password and after the form is submitted the action takes it to update.php, if the password was succesfully changed the page will redirect to change.php?err=1 where 1 has a noty notification which shows password changed succesfully. If there was some problem it redirects to change.php?err=2.
The code for updating password in update.php :-
$sql="UPDATE user_credentials SET password=? WHERE id=?";
$stmt = $result->prepare($sql);
$stmt->bind_param("si", $hash,$id);
if($stmt->execute()) {
header('Location: ../change.php?err=1');
}
else {
header('Location: ../change.php?err=2');
}
The below code for is for showing messages in change.php.
if(isset($_GET['err']))
{
$error_id = $_GET['err'];
if ($error_id == 1) {
echo "<script> noty({text: 'Password Changed Successfully',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
else
if ($error_id == 2) {
echo "<script> noty({text: 'Something went wrong',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
}
Now if the page is refereshed it will show the message again and again. I want to show the message only when it is redirected not on refreshes.
I thought of a workaround using sessions like this:-
if ($error_id == 1) {
if(!isset($_SESSION['notify'])) {
$_SESSION['notify'] = TRUE;
echo "<script> noty({text: 'Password Changed Successfully',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
}
But it stops the message on refreshes but it doesn't show when page is redirected.
I am just starting to learn php so please let me know what I am doing wrong or what else could be better way to solving this problem. Any help is highly appreciated.
Well in addition to
if(isset($_GET['err'])){}
you can add:
if(isset($_GET['err']) && $_SERVER['HTTP_REFERER'] == YOUR_PREV_PAGE){}
In your case it is update.php
This kind of functionality typically works best when you use an ajax call, that means: without refreshing the page.
You could call update.php in the background (see docs of the link pasted above), and decide in the callback of that ajax function what notification to show, based on the response of your update.php script.
EDIT: simple example
$.ajax({
url: "/update-password.php",
data: {
user: "some-user",
pass: "new-pass"
}
}).done(function(response) {
// Show notification, decide on contents based on response
});
Use SESSION instead of GET for error messages. Set an error at the time it's detected, prior to your header() call:
session_start();
$sql="UPDATE user_credentials SET password=? WHERE id=?";
$stmt = $result->prepare($sql);
$stmt->bind_param("si", $hash,$id);
if($stmt->execute()) {
$_SESSION['error'] = "You password was changed.";
header('Location: ../change.php');
}
else {
$_SESSION['error'] = "We could not change your password.";
header('Location: ../change.php');
}
In change.php (and in any other page were a message might be set), do something similar to this:
session_start();
if (strlen($_SESSION['error'])) {
echo $_SESSION['error'];
$_SESSION['error'] = false;
}
I've been staring at code too long however when I used a simple script to save a form with:
endif;
header('Location: http:/mysite.com/evo/codesaveindex.php');
?>
at the end the page redirected back to itself just fine, however now I have a longer script here I can't quite figure out where or how to code my redirect:
<?php
session_start();
$directory = 'users/'.$_SESSION['username'].'/';
//here you can even check if user selected 'Delete' option:
if($_POST['Action'] == "DELETE"){
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete))
echo $file_to_delete." deleted.";
else
echo "Error deleting file ".$file_to_delete;
}
if($_POST['Action'] == "SAVE"){
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
}
?>
may be you should use querystring variable while redirecting.
if($_POST['Action'] == "DELETE") {
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete)) {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=1&file='.$file_to_delete);
} else {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=0& file='.$file_to_delete);
}
}
In codesaveindex.php:
if(isset($_GET['deleted'])&& $_GET['deleted']==1) {
echo $file_to_delete." deleted.";
} elseif(isset($_GET['deleted'])&& $_GET['deleted']==0) {
echo "Error deleting file ".$file_to_delete;
}
You can't redirect if the page after html has been outputted.
You need to either use output buffering or redirect using javascript,
or organise it so that the redirect happens before the html is shown.
i have a class written for such thing, should be very easy to use class.route.php
simply do this where you want to redirect: route::redirect('page', http_status);
I'm trying to have the mail.php script identify the page that called the script, and return the user to that page and if the form didn't validate, was empty, etc. When I click on submit, it just 404's.
<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "email#email.com";
/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$email_address = $_REQUEST['email'];
$comments = $_REQUEST['comment'];
$fname = $_REQUEST['first-name'];
$lname = $_REQUEST['last-name'];
$filename = debug_backtrace();
$page = $filename[0]['file'];
/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
return true;
}
else {
return false;
}
}
// If the user tries to access this script directly, redirect them to the feedback form,
if (!isset($_REQUEST['email_address'])) {
header( "Location: $page" );
}
// If the form fields are empty, redirect to the error page.
elseif (empty($email_address) || empty($comments) || empty($fname)) {
echo "<script type=\"text/javascript\">window.alert('Please fill in the required fields.');
window.location.href = $page;</script>";
exit;
}
// If email injection is detected, redirect to the error page.
elseif (isInjected($email_address)){
echo "<script type=\"text/javascript\">window.alert('Please, Try Again.');
window.location.href = $page;</script>";
exit;
}
// If we passed all previous tests, send the email then redirect to the thank you page.
else {
mail("$webmaster_email", "Feedback Form Results", $comments, "From: $email_address");
echo "<script type=\"text/javascript\">window.alert('Thank You for contacting us!');
window.location.href = $page;</script>";
exit;
}
?>
No need for debug_backtrace(). To get the referring page, you could replace this:
$filename = debug_backtrace();
$page = $filename[0]['file'];
With this:
$page = $_SERVER['HTTP_REFERER'];
However, $_SERVER['HTTP_REFERER'] is unreliable according to the PHP docs:
This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
So another solution is to add an additional field in the referring form and retrieve it in the PHP script e.g.
<input name="referrer" type="hidden" value="<?php echo $_SERVER['PHP_SELF'];?>"/>
Then:
$page = $_REQUEST['referrer'];