Javascript alert and php header - php

I got a little problem. When I got my PHP script without header it's fine, I am getting javascript alert box. But when I use header before alert it's not working. It's redirecting me like it should, but it's not showing any box. Could someone help me?
if ( $pkt < 1 OR $user_id == 0) {
header("Location: http://dunno.com/file.php");
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('$message');
</SCRIPT>";
mysql_close();
}
And here's the one which work (but without heading)
if ( $pkt < 1 OR $user_id == 0) {
$message = 'This is a message.';
echo "<SCRIPT> //showing me
alert('$message');
</SCRIPT>";
mysql_close();
}
I would be thankful for help :)
#edit Maybe is there any command to make alert wait until whole browser load? (if it's the problem)

Maybe try redirect using JavaScript.
if ( $pkt < 1 OR $user_id == 0) {
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('$message')
window.location.replace('url of the page');
</SCRIPT>";
mysql_close();
}

I know this is a old post, but here is how I made it in a similar example. This example checks if the administrator has logged in from a specific IP address, if it returns false it should redirect the user back to the login page and show an error message.
User has logged in page:
if ($_SERVER['REMOTE_ADDR'] == "ip address"){
$admin = True;
}else{
session_start();
$_SESSION['errorMessage'] = "WARNING: You dont have access to this area.";
header("Location: login.php");
}
login.php:
session_start();
if(isset($_SESSION['errorMessage'])){
echo "<script type='text/javascript'>
alert('" . $_SESSION['errorMessage'] . "');
</script>";
//to not make the error message appear again after refresh:
session_unset($_SESSION['errorMessage']);
}

this is a redirect:
header("Location: http://dunno.com/file.php");
the code below wont work

Your error is in the structure of your code. PHP, even in OOP is procedural and will run each line one after the other. So the way you've structured your code means the page is redirected before your echo. A better method is to use the javascript alert box to redirect your page using:
var prompt=window.confirm("message here. \r\n"+"Do you want to redirect?");
if(prompt)document.location.href='http://dunno.com/file.php');

Aaroniker is correct with the redirect comment. One way to make it work would be to send the message with a session variable and then add the message creation to the next page like so.
session_start();
if ( $pkt < 1 OR $user_id == 0) {
$_SESSION['message']= "this is a message";
header("Location: http://dunno.com/file.php");
On file.php:
session_start();
echo "<SCRIPT> //not showing me this
alert($_SESSION['message']);
</SCRIPT>";
mysql_close();
}
Another option would be to pass them with you header. Like so:
if ( $pkt < 1 OR $user_id == 0) {
$message= "this is a message";
header("Location: http://dunno.com/file.php?message=" . $message . ");
Then on file.php:
echo "<SCRIPT> //not showing me this
alert($_GET['message']);
</SCRIPT>";
mysql_close();
}

Use $_SERVER 'php_self'. It will allow you to create script on same page where you want alert. In this way you won't have to add header.
Here's an example:
<form name="login" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" accept-charset="utf-8" class="form_class">
<ul>
<li>
<label for="usermail">Username</label>
<input type="text" name="username" placeholder="Enter username" required>
</li>
<li>
<label for="password">Password </label>
<input type="password" name="password" placeholder="Enter your password" required>
</li>
<li id="custom">
<input type="submit" value="Sign In">
</li>
</ul>
</form>
$sqluname="root";
$sqlpword="hrhk";
$database="registration";
$server="127.0.0.1";
$db_handle=mysql_connect($server,$sqluname,$sqlpword,$database);
$db_found = mysql_select_db($database, $db_handle);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uname = $_POST["username"];
$pword = $_POST["password"];
$ulength=strlen($uname);
$plength=strlen($pword);
if($ulength > 5){
$sqlquery="SELECT * FROM members WHERE username='$uname' AND password='$pword'";
$result=mysql_query($sqlquery);
$num_rows=mysql_num_rows($result);
if ($num_rows >0) {
echo "<script>alert('Logged In');</script>";
session_start();
$_SESSION['sid']=$uname;
header("location:Yahoo/yahoo.php");
}
else{
echo "<script>alert('Wrong Username or Password!');</script>";
}
}
else{
echo"<script>alert('Username should be greater than 5 characters.');</script>";
}
}
?>

The below header function will run a 302 redirect by default and redirect the client to http://dunno.com/file.php so any code after the code begin processed after the header function will not be seen as the client is redirected from the page this code is on.
header("Location: http://dunno.com/file.php");
Please read up further on the header function here: http://www.php.net/manual/en/function.header.php
You could make you program sleep/wait for a few seconds(lets say 10 seconds for this example) before redirecting if you need the message to display like so:
if ( $pkt < 1 OR $user_id == 0)
{
$message = 'This is a message.';
echo "<SCRIPT> //not showing me this
alert('".$message."');
</SCRIPT>";
sleep(10);
mysql_close();
header("Location: http://dunno.com/file.php");
}

Related

Echo success message after submitted form but before redirect and exit

Don't know how long i have worked on this, but nothing looks to be working. All i want to do is output a success message before it redirects and exits.
This is what i got to check for success/fail to the database
$sql = ("INSERT INTO test3 (test1, betvalue, bookmaker, status, aktiv) VALUES ('$bettype', '$betvalue', '$bookmaker', '$status', '$aktiv')");
$result = mysqli_query($conn, $sql);
if(mysqli_affected_rows($conn) >0 ) {
echo "Wow it works"; <-- Not working
header("Location: nybonus.php");
exit;
} else {
echo ("<div class='alert alert-danger' role='alert'>" . $sql . "</div><div class='alert alert-danger' role='alert'>" . mysqli_error($conn) . "</div>");
}
It does not output any echo if it has be successful, i have tried making it sleep with correct flushing to try to output an messsage, but it does not work at all. Is there a better way to do it? Also can someone explain why it wont echo before the header and exit?
Could you achieve what you want by setting a session variable and checking for the state of that variable on reload:
$message = '';
if(isset($_SESSION['success'])) {
if($_SESSION['success'] == 'success') {
$message = 'Success';
}
}
$sql = ("INSERT INTO test3 (test1, betvalue, bookmaker, status, aktiv) VALUES ('$bettype', '$betvalue', '$bookmaker', '$status', '$aktiv')");
mysqli_query($conn, $sql);
if(mysqli_affected_rows($conn) > 0) {
$_SESSION['success'] = 'success';
header('Location: nybonus.php');
exit;
}
else {
$_SESSION['success'] = 'fail';
.....
}
<script>
$("#message").fadeOut(2000, function() {
$("#message").fadeIn(0, function() {
document.getElementById("message").innerHTML ="<br>";
});
});
</script>
<div id="message">
<?php echo $message; ?>
</div>
The problem is when you use the "header" it has to be first.
You can't print anything else to the screen before the header.
It's the same as when you're setting cookies.
So in your case you can't do the redirect with "header".
You could use a meta refresh.
<meta http-equiv="refresh" content="0; url=http://www.somewebsite.com">
The "content" is number of seconds to wait before doing refresh.
You'll have to explain what you're trying to accomplish more precisely... like step 1 do this step 2 do this and so on.
Previously I understood you had asked how to do a redirect after echoing a message.
So now explain more detail in steps what you're wanting to do and maybe I can help.
If you mean the user is one "page1" and they submit a form and then on the resulting page you want to display the message? Then redirect...
You would just need to make the form action be the same url path as the page they are currently on.
Do you follow me?

not getting session variables on second page while hosting my website (On localhost, it works)

Down, in the second page i am not getting the session variable values. Actually sessions variables are not recieving in second file(index.php).
Error is Notice: Undefined index: userid in /storage/ssd5/520/5088520/public_html/index.php on line 150
1 - login.php //file 1
session_start();
if (isset($_POST['login'] ))
{
$_SESSION["userid"] = $_POST["userid"];
$_SESSION["user"] = $_POST["user"];
$userid=$_SESSION["userid"];
$user=$_SESSION["user"];
if ($userid=='' || $user=='')
{
//generate error
echo 'ERROR: Please fill in all required fields!';
renderForm();
}
else
{
//query
$result = mysql_query("SELECT user_id FROM users WHERE user_id='$userid'
AND user='$user'") or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row['user_id'] == 1 || $row['user_id'] == 2)
{
$_SESSION['login_status'] = true;
echo "<script> window.open ('index.php','_self') </script>";
}
else
{
echo "Sorry, No account exist";
}
}
}
//if submit button not pressed yet. show form:
else
{
//now show form
renderForm();
}
//redenring form
<?php
//function starts
function renderForm()
{
?>
<form role="form" method="post">
<input placeholder="User ID" name="userid" type="text">
<input placeholder="User" name="user" type="text">
<button type="submit" name="login">Login</a>
</form>
<?php
} //function ends
?>
Second file where error comes
2-index.php //file 2
<?php
session_start();
if ($_SESSION['login_status']==false) {
header("Location:login.php"); } else { ?> <body> //somewhere inside here i am accessing the session variables <?php
if ($_SESSION['userid']==1) //line 150
{
echo "<a class='navbar-brand' href='index.php'>Admin</a>";
}
if ($_SESSION['userid']==2 )
{
echo "<a class='navbar-brand' href='index.php'>Clerk</a>";
} ?> </body>
on local host. this code runs . But i am now hosting it. but i am not understanding, what can be the issue?
Declare session_start(); on second page.
You need to add session_start(); at the top of the second file in order to access session variables in it.
Add session_start(); in every page you are accessing session variables from otherwise it doesn't work. It is a requirement to start the session in order to access the super global variable $_SESSION.
Edit:
You need to use if( !isset($_SESSION['userid']) ) instead of
if ($_SESSION['userid']==1) on the index.php page.
Otherwise, it will throw you undefined index error if you are
visiting the index.php before attempting to log in.
You may have noticed that your code doesn't throw error if you visit index.php after logging in.

PHP Session lost/login not working

I have a question regarding sessions in php. I made a login page, and whenever I tried it, it just gave me a redirect error. So I followed the answer from this question.
So now, instead of getting the redirect error, whenever I press the login button nothing happens, the form is emptied and that is all. What am I doing wrong? This is currently how the code which is giving me issues looks like.
index.php:
<?phpsession_start();
if (isset($_SESSION['valid_user'])) {
Header("Location: index.php");
exit();
}
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$password = $_POST['password'];
$file = file_get_contents("data.txt");
if (strstr($file, "$name||$password")) {
$_SESSION["valid_user"] = $_POST["name"];
$_SESSION["valid_time"] = time();
Header("Location: welcome.php");
} elseif (empty($name) && empty($password)) {
echo "Both fields are empty. Please fill them.";
} elseif (empty($name)) {
echo "No name was entered.";
} elseif (empty($password)) {
echo "No password was entered";
} else {
echo "Wrong credentials, please try again.";
}
}
To be more specific the code which I think is the problem is this part:
<?phpsession_start();
if (isset($_SESSION['valid_user'])) {
Header("Location: index.php");
exit();
}
But whenever I try it I either get the redirect error:
My browser gives me "ERR_TOO_MANY_REDIRECTS" when I try to enter the page.
or the page just empties the form and nothing else happens. And the error messages which are supposed to be displayed when I don't type anything in the form is not displaying either. It's been giving me headaches the whole day today so if anyone could just point me in the right direction that would be great.
Also the form HTML I use in index.php:
<body>
<form method="post" action="index.php" >
<p>Enter name:</p>
<input type="text" name="name" />
<br/>
<br/>
<p>Enter password:</p>
<input type="password" name="password" />
<br/>
<br/>
<input type="submit" value="Login" name="submit"/>
</form>
</body>
I think there are too many errors related to code. There must be spaces between the opening PHP tag and session_start();.
Plus, the conditional statement you've given in if (isset($_SESSION['valid_user'])) is being interpreted as "if it IS set". What you should have used is the ! operator, meaning if it is "NOT" set.
That is why you are getting "too many redirects".
<?php session_start();// try putting space between here
if (!isset($_SESSION['valid_user'])) {
header("Location: login.php"); // Redirect back to your login page
exit();
}
also in } elseif (empty($name) && empty($password)) {
// all elseif should be like else if(condition)
also change file names.
You should also add an exit; after every header, otherwise your code will want to continue to execute.
Problem is here when you have a valid user then you are trying to redirect it on index.php which again check for valid user and again redirect on index.php its like INFINITE loop.
Thanx #Fred-ii-
You've got your answer but here is an explanation about "Too many redirects". You are getting that error on your browser because your code is keep redirecting to another page. Both of your statements are returning true:
if (isset($_SESSION['valid_user'])) {
} //Returning true - Redirect to index
if (strstr($file, "$name||$password")) {
} //Returning true - Redirect to welcome
As there are/were no exits after the redirects, the code carries on executing: redirect here than redirect there...
Also you should check the session validation as follows:
if(!isset($_SESSION['session']) || $_SESSION[''] == "")
This will check if the session is not set OR empty.

Redirect page when user is verified

i have this code to verify if users have Administrator account to backoffice of my website, but if user don't have it don't redirect user to ..index.php. He stay in this page but no content is shown.
Code of verification
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
}
else
{
echo "<script>alert(\"Area Restrita\");</scrpit>";
header("Location: ../index.php");
}
?>
In this page, (header) i call this file to verify session.
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
header("Location: ../index.php"); is not going to stop the rest of the code from running - if you just want to redirect him you should die(); or exit; right after you send the Location header
The alert part before the Location header is also unnecessary because the browser will redirect the user before he'll be able to see the alert. and also it is forbidden to call header function after you sent something to the output (for example, like you did with echo)
Another thing that you should consider - is the security issues that raised from validating user solely by looking at values in the $_SESSION - this means - that if someone is logged - you are not able to log him out until the session expires
The better way is to keep some token in the $_SESSION and save the status of the user in the database - that way, you can change his status directly from the DB without relying on the session/changing code
Your index file:
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
Your verification file:
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
// do some action for administrator
}
else
{
header("Location: ../index.php");
exit();
//echo "<script>alert(\"Area Restrita\");</scrpit>"; <-- you don't need this here
}
?>
Note, that I commented echo. You mustn't output anything before header. If you will output something (and you do in your example) you will get headers already sent error.
Your main mistake is you output something first and after that tried to redirect.
Anyway, I think better to use a bit another approach.
Form and form handler:
<?
$username = $_POST['username'];
$password = $_POST['password'];
// here is some query which will check if this user with this password exists and get the role of the user
// if exists $userExists = true; else $userExists = false;
if($userExists) {
$_SESSION['userLoggedIn'] = true;
if($role == 'administrator') {
$_SESSION['isAdministrator'] = true;
}
else
{
$_SESSION['isAdministrator'] = false;
}
header('Location: index.php');
exit(); // <-- don't forget this
}
else
{
// handler for bad user/password
}
?>
<form action='' method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
</form>
Now, pages which are restricted will start from this code:
<?
$isAdministrator = $_SESSION['isAdministrator'];
if(!$isAdministrator) {
ban_ban_ban();
die('bye bye');
}
// content for administrator
?>
NOTE: This is just example, don't forget to add some check everywhere!!!!!11
But, as you wish :) Hope, this will help you.

php redirection not working

Ive got this register script that puts the information into a mysql database. now it all works fine and when someone does something wrong its says the error (e.g. "Username not defined")
but when it goes wrong it does not look very good because it just displays the message on an empty page, so i thought i would make it redirect to the form page and display the message there.
here is the working script
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$errors = array();
if(!$username) {
$errors[] = "Username is not defined";
}
if(!$password) {
$errors[] = "Password is not defined";
}
and it continues.
now i just thought i could do this
$errors = array();
if(!$username) {
$errors[] = header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
}
if(!$password) {
$errors[] = "Password is not defined";
}
but no, all it does is ignore it.
could someone please help me
please feel free to ask for more of the script if you need it
many thanks connor
You cannot wrap a header in a array like that.
You just call the function, then it redirects.
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
it does not look very good because it just displays the message on an empty page,
What's the problem?
Why not to show the form again? with fields already filled.
This is going to be a user-friendly interface.
Just include your form in the same page with fields populated.
That's more common way than your redirects to blank form.
This is called POST/Redirect/GET pattern and here goes a short example of it:
the code
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
the template
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
You are placing the return value of the header function in an array, then continuing with your page execution.
If you don't care about anything that would normally happen below that redirection, which I believe is what you're implying, you should just set the header and then immediately exit. Do not try to place the return value of the header function into the errors array like that, as there's no point.
if(!$username) {
header('Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined');
exit;
}
I don't if this is the problem, but it's important to include the status code in header too. Like:
header("Location: /foo.php",TRUE,302);
307 for Temporary Redirect, 302 for permanently moved. Chrome, a while ago, didn't accepted headers redirect without status code (i don't know nowadays).
try this after filling your error array:
if (count($errors) > 0)
{
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' );
exit;
}
Keep in mind there should be no html output before this part!

Categories