Maybe try redirect using JavaScript.

if ( 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();
}
Answer from Zander Rootman on Stack Overflow
🌐
DaniWeb
daniweb.com › programming › web-development › threads › 487676 › getting-header-error-when-generating-alert-messsage
php - Getting header error when generating Alert ... [SOLVED] | DaniWeb
November 18, 2014 - // check if the item is in the array, if it is, do not add if(array_key_exists($id, $_SESSION['cart_items'])){ // redirect to product list and tell the user it was added to cart header('Location: ../sale_barn_yearlings_test2.php?action=exists&#'.$id.''); } // else, add the item to the array else{ $_SESSION['cart_items'][$id]=$horsename; // redirect to product list and tell the user it was added to cart header('Location: ../sale_barn_yearlings_test2.php?action=added&#'.$id.''); Then on the Products page (which is the page that the header redirects to) I added. if($action=='added'){ echo '<script language="javascript">'; echo 'alert("Item Added")'; echo '</script>'; } if($action=='exists'){ echo '<script language="javascript">'; echo 'alert("Item Already there")'; echo '</script>'; }
🌐
GitHub
gist.github.com › ErMandeep › 6faea4751b7f388c94651dd811933dc0
display alert message after redirecting page php · GitHub
display alert message after redirecting page php. GitHub Gist: instantly share code, notes, and snippets.
🌐
WebDeveloper.com
webdeveloper.com › community › 217839-how-do-i-add-a-msg-box-alert-before-changing-header
How do i?.. Add a msg box alert before changing header.
Copy linkTweet thisAlerts: @opifexOct 07.2009 — #ok. since you have the option to redirect OR show a thank you message already.... replace this [code=php]header ("Location:$location");[/code] with this [code=php] echo "<script type="text/javascript">n"; echo "alert('Thank you for submitting our form.');n"); echo "window.location = ('$location');n"; echo "</script>";[/code]
🌐
Talkerscode
talkerscode.com › howto › alert-in-php-and-redirect.php
Alert In PHP And Redirect
Here, as we see that to alert a message we use alert() function with the help of jQuery. In first case, we use script inside echo and then alert inside that. In next method, we create a function with alert and call it later with required parameter. Now, for redirection here are again two methods. First one by using header() and next one is by window.location.href method...
🌐
CopyProgramming
copyprogramming.com › howto › javascript-alert-and-php-header
Php: Header redirection using PHP and triggering alerts with Javascript
June 6, 2023 - After conducting extensive research, I discovered a solution that involves delaying the alert message using a jQuery function. This delay enables the HTML page to load completely before the alert is executed. ... I am facing an issue with my PHP script. It works fine without a header, and I am able to obtain javascript alert box . However, after adding a header and alert, it redirects me but does not display any box. Can someone assist me with this problem? if ( $pkt < 1 OR $user_id == 0) { header("Location: http://dunno.com/file.php"); $message = 'This is a message.'; echo ""; mysql_close(); }
Find elsewhere
🌐
Edureka Community
edureka.co › home › community › categories › web development › php › how to show an alert box in php
How to show an alert box in PHP | Edureka Community
November 4, 2020 - I want to display an alert box showing a message with PHP. Here is my PHP code: But it is not working.
Top answer
1 of 5
3

Your problem is that you are redirecting without sending the parameters in the URL. If you want to have that data available, you need to do header("Location:thank_you.php?first_name=X"), etc. in your redirect. e.g.

$first_name = /** WHAT??? You don't have this in your code so I can't verify it exists **/

$today = date("Ymd");
$rand = strtoupper(substr(uniqid(sha1(time())),0,4));
$unique = $today . $rand;
$_SESSION['unique'] = $unique;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); 
// sends a copy of the message to the sender
header("Location:thank_you.php?first_name={$first_name}&unique={$unique}");
exit;

To access this on the next page, you would do:

<?php 
if( isset($_GET['first_name']) && isset($_GET['unique']) ) {
    echo "Mail Sent. Thank you " . $_GET['first_name' . ", we will contact you shortly.". ", Your Order Number:". $_GET['unique'];
}

Otherwise, it might just be simpler to include the thank_you.php page which will then have access to all variables within scope:

$first_name = /** WHAT??? You don't have this in your code so I can't verify it exists **/

$today = date("Ymd");
$rand = strtoupper(substr(uniqid(sha1(time())),0,4));
$unique = $today . $rand;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); 
// include the other file
include('thank_you.php');
exit;

In this instance, thank_you.php would be:

<?php 
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.". ", Your Order Number:". $unique;
?>

UPDATE, per your issues...if you are having problems, try this:

php1.php

<?php

    header("Location: php2.php?first_name=Joe");
    exit;

php2.php

<?php

    echo $_GET['first_name'];

If that doesn't work, you have issues with your PHP environment not working like mine does. If it works, the issue is with your code.

2 of 5
1

HTTP is stateless. That means that one page doesn't know anything about another page. As a result, any variables you set on the first page are long gone by the time you get redirected to the second. If you want to have the action span two different pages, then you'll need to persist the values, possibly in a database, or a session, or on the URL via GET parameters.

🌐
PHP
php.net › manual › en › function.header.php
PHP: header - Manual
If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › PHP-header-location-error-warning-cannot-modify-header-information-headers-already-sent.php
PHP Header Location Error- Warning: Cannot Modify Header Information- Headers Already Sent
September 6, 2024 - With the PHP header function, this is forbidden. No output can be written to the browser before the redirect occurs. If this is the case, you will get the error, such as shown above. ... And the answer is, this can take many forms. For one, you may actually have output shown before the php header function, such as an echo statement. ... <?php echo "This output causes the header function to not work"; header('Location: http://www.google.com'); ?>
🌐
Post.Byes
post.bytes.com › home › forum › topic › php
php javascript alert redirect - Post.Byes - Bytes
There is no reason for it to be faster, but it often misbehaves client side (broken browsers or it's disabled) which isn't worth the few CPU cycles you save on the server. Also, go read about ob_start() in the PHP documentation. Make sure you know what it does before copy-pasting it in your code. If you want to execute JS code, you can't use header redirects. Use a JS redirect or don't use alerts at all.
Top answer
1 of 3
2

You can do this all on the server side by using the session:

  1. "Show form" php script creates the form and returns it to the user.

  2. User fills it out and submits it to another php script "receive script" which receives the form data, and notices an error, missing data, etc.

  3. The "receive script" stores the error msg in the session (as item err) and redirects to the 'show form' script.

  4. The "show form" script (same as in step 1) actually does more than create the form. It also:

    • looks in the session to see if it has an item 'err', an error msg. In step 1 there wasn't. But now there is. So the php script creates the form, along with a div that shows the error msg to the user.
    • Resets the session's 'err' item to nil.
    • The php script could also include javascript in the page which would make the error msg disappear after a while or be shown as a popup, etc.

ps. The above flow is how rails handles forms and redisplay of the form.

Update: Thanks to @zod for pointing out that I wasn't clearing the err item in the session.

2 of 3
1

If an error is encountered, store the error state to a $_SESSION array and then redirect the browser to the original page. Have a script on the original page to check if an error state is set. If yes, trigger a javascript alert or whatever handling you want to have.

And at the common footer template (or at the footer of original page), check and clear the errors array, so it doesn't persist when the user moves to other pages or reloads the current page.

Example:

processor.php

<?php
if($something == $iswrong){
    $_SESSION['errors']['error5301'] = 1;
    session_write_close();
    header("Location: http://www.example.com/originalpage.php");
    exit;
} ?>

originalpage.php

<!-- Header -->
<?php
if(isset($_SESSION['errors']['error5301']) && $_SESSION['errors']['error5301'] == 1){ ?>
    <script type="text/javascript">
        alert('Something is not correct!');
    </script>
<?php } ?>

<!-- Some page content -->
....
.....
..
......

<!-- Footer -->
<?php
if(isset($_SESSION['errors'])){
    unset($_SESSION['errors']);
} ?>

Hope that helps.

🌐
Team Treehouse
teamtreehouse.com › community › why-is-headerlocation-contactphpstatusthanks-redirect-not-working
Why is header("Location: contact.php?status=thanks"); redirect not working? (Example) | Treehouse Community
July 24, 2014 - Stackoverflow says it has something to do with unintentional white space but I still haven't figured out how to fix it. header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP http://stackoverflow.com/questions/12525251/header-location-not-working-in-my-php-code · Here's my code for "contact.php": <?php if ($_SERVER["REQUEST_METHOD"]=="POST"){ $name = $_POST["name"]; $email = $_POST["email"]; $message = $_POST["message"]; $email_body =""; $email_body = $email_body .