'PHP: give alert popup then redirect the page
I am new to PHP.
When someone uploads a file size too big, I want to show them a warning popup and redirect them to a previous page (or vice versa).
if(file size is too big){
ob_start();
header("location:index.php");
echo "<script type='text/javascript'>alert('Your File Size is too big!');</script>";
ob_end_flush();
exit;
}
This code above will just redirect me to index.php and doesn't show any warning popup.
Solution 1:[1]
<script type="text/javascript">
alert("YOUR MESSAGE HERE");
location="REDIRECTION_PAGE.php";
</script>
Solution 2:[2]
The problem is that header("location:index.php"); sets the response code to 302 automatically. The browser immediately redirects without looking at the contents of the page.
You need to either do the redirect itself in javascript after the alert is sent, or else have the page you're redirecting to do the alert.
Solution 3:[3]
The code goes like:
if($_FILES['file']['size'] > 200000) //any file size, 200 kb in this case
{
echo "<script type='javascript'>alert('File size larger than 200 KB')</script>";
}
header("Location: index.php");
The browser will be redirected to index.php page anyway, no matter the file is successfully uploaded or not. Its just that the popup will appear if the file is of larger size.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marco |
| Solution 2 | Andrew Gorcester |
| Solution 3 | Shashank Srivastava |
