PHP script unable to gather filename of calling html page - javascript

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'];

Related

Variable from posted form stops or continues with php code after pop up box (javascript)

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.

Accessing Through PHP a Posted Javascript Variable

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.

How can i show a webpage only for logged in users? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Currently I'm working on a little project for login page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users. i am using php and sql for this. i want also a logout and senf to the index but i can't find te solution. Here is my code.
<?php
require ('sql_connect.php');
if (isset($_POST['submit'])){
$username=mysql_escape_string($_POST['uname']);
$password=mysql_escape_string($_POST['pass']);
if (!$_POST['uname'] | !$_POST['pass'])
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('You did not complete all of the required fields')
window.location.href='index.html'
</SCRIPT>");
exit();
}
$sql= mysql_query("SELECT * FROM `login_users` WHERE `username` = '$username' AND `password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Succesfully!.')
window.location.href='homepage.html'
</SCRIPT>");
exit();
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Wrong username password combination.Please re-enter.')
window.location.href='index.html'
</SCRIPT>");
exit();
}
}
else{
}
?>
this is my control for the correct user and pass.
And here is the page i want to go if the user has logged in.
homepage.index:
<html>
<head>
</head>
<body>
<center><h1>Welcome user!</h1></center>
here some text and other stuff.
<h3>logout here<h3>
</body>
But now i can write www.mysite/homepage.index and i can go to this page without logging in. Can someone explain this?
Thank you.
Your question is part of many many available tutorials, did you try to google it first?
do not use mysql extension (using mysqli in example)
do not redirect via javascript, if you can do it via php
do not redirect to html files, when you need to work with php
do not store password as plain text (using php5.5+ function to crypt it in example)
do not select *
do not echo html code
use isset before getting value from $_POST, $_GET
Feel free to google everything to know the reasons.
<?php
class Connection //not sure what you have in sql_connect.php, I made this so the example is complete
{
static function getConnection(){
if(self::$connection === null)
self::$connection = new mysqli('127.0.0.1', 'root', '', 'so');
return self::$connection;
}
/** #var mysqli */
private static $connection;
}
<?php
class UserAuthenticator
{
function __construct(){
session_start(); //you need to start session when working with $_SESSION
}
function checkLogin(){
if(isset($_POST['submit'])){
$username = $this->getPostEscaped('uname');
$password = $this->getPost('pass'); //no need to escape through mysqli, we do not use it in query
if($username && $password){
$userData = Connection::getConnection()->query("SELECT password FROM login_users
WHERE username = '$username'")->fetch_assoc();
if($this->verifyPassword($password, $userData['password'])){
$this->login($username); //storing username for simplicity, but I do recommend to store id or some generated hash even better
$this->flash('Login succesfull.');
$this->redirect('homepage.php');
}else $this->flash('Wrong username / password combination. Please re-enter.');
}else $this->flash('You did not complete all of the required fields.');
$this->redirect('index.php');
}
}
function isLogged(){ //actual answer to the question - how to check the logged user
return isset($_SESSION['logged']);
}
function verifyPassword($password, $passwordHash){ //public so you can use it elsewhere
return password_verify($password, $passwordHash);
}
function getPasswordHash($password){ //public so you can use it elsewhere
return password_hash($password, PASSWORD_DEFAULT);
}
function showFlashMessages(){
if($flashMessages = $this->getFlashes()): ?>
<script language="JavaScript">
<?php foreach($flashMessages as $message): ?>
alert('<?= $message ?>');
<?php endforeach ?>
</script> <?php
endif;
unset($_SESSION['flashmessage']); //we need to remove messages, so they do not persist
}
function redirect($to = ''){ //you need to ensure you are not echoing any content before redirecting (that's a proper common way - learn it)
$url = 'http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header('Location: ' . $url .'/'. $to, true, 302);
header('Connection: close');
exit;
}
private function login($userId){ //actual answer to the question - how to store the logged user
$_SESSION['logged'] = $userId;
}
private function flash($message){ //do not repeat yourself
if(!isset($_SESSION['flashmessage']))
$_SESSION['flashmessage'] = array();
$_SESSION['flashmessage'][] = $message;
}
private function getFlashes(){
return isset($_SESSION['flashmessage'])? $_SESSION['flashmessage']: [];
}
private function getPost($name, $default = null){ //do not repeat yourself
return isset($_POST[$name])? $_POST[$name]: $default;
}
private function getPostEscaped($name, $default = null){ //do not repeat yourself
return ($value = $this->getPost($name))?
Connection::getConnection()->real_escape_string($value): $default;
}
}
$ua = new UserAuthenticator();
$ua->checkLogin();
$ua->showFlashMessages();
you need to store passwords with
$ua = new UserAuthenticator();
$password = $ua->getPasswordHash($plainTextPassword); //store this to database
in homepage.php you can check logged status with
$ua = new UserAuthenticator();
if(!$ua->isLogged()){ $ua->redirect('index.php'); } //redirect to login page if not logged in
not tested anything of this, so typo is possible - sorry :)
Lets say your login was succesfull. All you have to do is this:
Session_start();
$_SESSION['id']= $row['id']; (make sure you changed mysql_num_rows to fetch assoc aswell)
Then on your index page at the top you add an if statement that checks wether or not the session has been set. For that you first need to call another session_start()
Hope this steers you in the right direction if not ill update my answer

Issue with Captcha system on PHP, AJAX Contact form

In 2011, I bought a PHP contact form from codecanyon that uses AJAX to process the form. After reporting my problem to them today, they responded saying that they no longer offer support for their 'old' product (so much for the life time support they generally offer as a rule) ... so they aren't going to help me hence this post on SO.
I would say that this isn't a normal issue but I think it's very important that it gets sorted out - here it is (this is my email to the seller but does explain the problem):
=================
I have an unusual issue with your AJAX Contact Form (you're going to have to read carefully and slowly).
Okay everything works 100% fine BUT ... let me explain (basically this has everything to do with the Captcha and verification of it)
My website has many pages with your online form on each of those pages.
Now I also have a listings page that has links going to all of those pages with forms.
EXAMPLE:
Lets say I am on a listings page (a page with a whole load of links going to other pages) and I right click on Link A to open page A in a new tab ... and then I also right click on Link B to open page B in a new tab. Right, so we have the listings page (that's still opened in front of me) and those 2 other pages that opened up in new tabs (Page A and Page B) ... as explained above, both those pages has your online form.
Now, I fill in both forms and click submit.
The first page that I right clicked to open in a new tab (Page A) - that form's Captcha doesn't work even when I've verified it correctly... however the form's Captcha on Page B does work (like it should). Why is it that the Captcha on Page A (the first page I opened) doesn't work?
I get the feeling that in the whole verification system, because Page B was opened up last, the verification is taking that page's captcha code into account, using that captcha for verification (throughout the session surfing on my website) thus making the Captcha on the first opened page (Page A) to not work.
So what I did as an experiment:
I restarted and did the same thing again, IE: I right clicked Link A to open page A in a new tab ... and then I also right click on Link B to open page B in a new tab.
I filled in Page B's Captcha code in Page A's Captcha verification field and what do you know - there's a match!
So this is my problem because I know when some people surf internet (I do this all the time and maybe you do too), they like to right click links to open them in new tabs so that they can get back to them later after browsing the listings page. So the person may have 6 tabs open in the browser and each of those pages has your online form. If the user wants to submit each of those forms, then he/she will experience the exact problem I am reporting above. They will be able to send through 1 form (the last page that was opened in a new tab) but the other page's Captchas won't work unless they refresh the page ... but most people won't think to do that - instead, they will think somethings wrong with the my website - which I am afraid of.
Is there a solution to this?
I'm not even sure if you've noticed this before?
I hoped I've explained the situation clearly and I'd really appreciate it if you could assist.
=================
Now back to you. What's causing this?
There are 3 files needed for the form to work / process etc (I'm not including the CSS file in this post not the html for the form as I don't think it's necessary).
1) process.php
2) image.php (this is for the captcha)
3) ajax.js
PROCESS.PHP
<?php if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$address = "email#example.com";
$bcc = "email#example.com";
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail
address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits
(numbers and no spaces).</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is
incorrect.</li>';
}
if($error != '') {
echo '<div class="error_title"><h6><span>Attention!
</span> Please correct the errors below and try again</h6>';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '<div class="close"></div>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
$e_subject = 'Booking / Enquiry';
$msg = '<html>
<body style="margin:0; padding:0;">
Name: '.$_POST['name'].'
Email: '.$_POST['email'].'
Contact Number: '.$_POST['phone'].'
Notes: '.$_POST['comments'].'
</body>
</html>';
$msg = wordwrap( $msg, 70 );
$headers = "From: $email\r\nBCC:{$bcc}\r\n" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= 'Content-Transfer-Encoding: 8bit'. "\n\r\n" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
echo "<div class='success'>";
echo "<h6>Your Enquiry has been Successfully submitted. </h6>";
echo '<div class="close"></div>';
echo "</div>";
} else {
echo 'ERROR!';
}
}
?>
*Please note that in the process.php code above, I removed a function that seems to validate the email address field - reason why I didn't include it in the code above is because it was heavy with code (would take up a lot of space) and I don't think it's necessary to include
IMAGE.PHP
<?php if (!isset($_SESSION)) session_start(); header("(anti-spam-
content-
type:) image/png");
$enc_num = rand(0, 9999);
$key_num = rand(0, 24);
$hash_string = substr(md5($enc_num), $key_num, 5); // Length of
String
$hash_md5 = md5($hash_string);
$_SESSION['verify'] = $hash_md5;
setcookie("verify", $hash_md5, time()+3600, "/");
session_write_close();
$bgs = array("../../img/1.png","../../img/2.png","../../img/3.png");
$background = array_rand($bgs, 1);
$img_handle = imagecreatefrompng($bgs[$background]);
$text_colour = imagecolorallocate($img_handle, 108, 127, 6);
$font_size = 5;
$size_array = getimagesize($bgs[$background]);
$img_w = $size_array[0];
$img_h = $size_array[1];
$horiz = round(($img_w/2)-
((strlen($hash_string)*imagefontwidth(5))/2),
1);
$vert = round(($img_h/2)-(imagefontheight($font_size)/2));
imagestring($img_handle, $font_size, $horiz, $vert, $hash_string,
$text_colour);
imagepng($img_handle);
imagedestroy($img_handle);
?>
AJAX.JS
jQuery(document).ready(function() {
$('.advertform').submit(function() {
var action = $(this).attr('action');
var form = this;
$('.submit', this).attr('disabled', 'disabled').after(
'<div class="loader"></div>').addClass("active");
$('.message', this).slideUp(750, function() {
$(this).hide();
$.post(action, {
name: $('.name', form).val(),
email: $('.email', form).val(),
phone: $('.phone', form).val(),
comments: $('.comments', form).val(),
verify: $('.verify', form).val()
},
function(data) {
$('.message', form).html(data);
$('.message', form).slideDown('slow');
$('.loader', form).fadeOut('fast', function() {
$(this).remove();
});
$('.submit',
form).removeAttr('disabled').removeClass("active");
});
});
return false;
});
$('.message').on('click', function(){
$('.message').slideUp();
});
});
Looking at the code above, can anyone spot what could be causing this problem? I'm assuming this can has to do with the javascript?
The comments are correct, the validation is failing on some forms because the session only holds the value of the last captcha generated therefore making captchas open in other tabs invalid because their value in the session was overwritten. Because of this, anyone using the same or similar code has this problem.
You can solve it fairly simply by changing the session to store an array of codes instead of just one.
In image.php, change:
$_SESSION['verify'] = $hash_md5;
to:
if (!isset($_SESSION['verify'])) $_SESSION['verify'] = array();
$_SESSION['verify'][$hash_md5] = $hash_md5; // *explantion for this array key later
You can also get rid of the cookie that gets set for the captcha, session storage should be fine.
Then in your form processor, change:
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.</li>';
}
to:
if(!array_key_exists($posted_verify, $session_verify)) {
$error .= '<li>The verification code you entered is incorrect.</li>';
}
This should allow you to have multiple forms open in multiple tabs and still be able to submit each one without getting the incorrect captcha error.
Also, another issue with this code is that it doesn't unset the session verify value after a successful post. This means a person could solve one captcha and submit your form an unlimited number of times re-using the old code as long as they don't access image.php again between submissions.
To fix this with the array version, you'll need to unset the session key after the captcha and form is processed.
unset($_SESSION['verify'][$posted_verify]); // remove code from session so it can't be reused
Hope that helps.
I have an idea. Store the captcha values in an array, and keep a counter; both stored in SESSION variables.
So in the form you put a hidden input, and set it to the index.
When we check for captcha, we compare $_SESSION['captcha'][$index] to $_POST['captcha'].
Any time you (the client) open a new window; $index is increased.
We pass that index to image.php through the url; example src="img.php?index=2"
Here is a concept; minimal code to accomplish this.
Open a couple of windows with this page. See what happens
img.php
<?php
session_start();
header("(anti-spam-content-type:) image/png");
$captcha_text = rand(0, 99999);
// we read a "index" from the URL, example: <img src="img.php?index=2">
$index = isset($_GET['index']) ? (int) $_GET['index'] : 0;
if( empty($_SESSION['captcha'])) {
$_SESSION['captcha'] = array();
}
$_SESSION['captcha'][$index] = $captcha_text;
// #see http://php.net/manual/en/function.imagestring.php , first example
$im = imagecreate(100, 30);
$bg = imagecolorallocate($im, 55, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, $captcha_text, $textcolor);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
index.php
<?php
session_start();
// we handle the POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_SESSION['captcha'])) {
if ($_SESSION['captcha'][ $_POST['index'] ] == $_POST['captcha']) {
echo '<h2>correct</h2>';
}
else {
echo '<h2>not correct</h2>';
}
echo '<a href="index.php">Back to form</form>';
// header('location: index.php');
exit;
}
// normal page, with form
if(isset($_SESSION['captcha_index'])) {// index
// set a new index
$_SESSION['captcha_index']++;
}
else {
$_SESSION['captcha_index'] = 0;
}
$captcha_index = $_SESSION['captcha_index'];
echo '
<img src="img.php?index=' . $captcha_index . '">
<form action="" method="post">
<input name="captcha">
<input name="index" type="hidden" value="' . $captcha_index . '">
<input type="submit" value="GO">
</form>
';
// we show what's happening. Obviously you don't want to print this after test phase
$captcha = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : array();
echo '
<br>print_r of $_SESSION[captcha]
<pre>' . print_r($captcha, true) . '<pre>
';
?>

Javascript not being executed

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.

Categories

Resources