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.
Do something like
header("Location: index.php?Message=" . urlencode($Message));
Then on index.php...
if (isset($_GET['Message'])) {
print $_GET['Message'];
}
In other words, index.php
will always check if it's being passed a message in the url. If there is one, display it. Then, just pass the message in the redirect
if you really want to use a modal popup, generate the js...
if (isset($_GET['Message'])) {
print '<script type="text/javascript">alert("' . $_GET['Message'] . '");</script>';
}
Note that this will break if you use quotes in the message unless you escape them
<script type="text/javascript">
alert("YOUR MESSAGE HERE");
location="REDIRECTION_PAGE.php";
</script>
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.
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.