How to Display Alert Message Box in PHP

In this tutorial, we will learn two different ways of displaying an alert message box in the users' browser window using PHP.

 

Example 1

To display the message we can echo a JavaScript alert() function containing a message like this:

 

<?php
// Echo a pop message:
echo '<script>alert("This is a message")</script>';
?>

 

Example 2

The first example works perfectly well, however, if you would like to display a dynamic message to the user VIA PHP, create a function that accepts a message string then insert it into the JavaScript alert() function like this:

 

<?php

function alertMessage($message)
{
  // Echo a pop message:
  echo "<script>alert('$message');</script>";
}

$m = "This is a message";

// Call the alert function:  
alertMessage($m);

?>