I have two files named index.php and uploadcover.inc.php. Everything is working fine, except the script tags being executed if the upload fails for any of the if-else conditions. Here is the code:
index.php =>
<form action="include/uploadcover.inc.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="cover-upload" style="display:none" onchange="this.form.submit();">
<label for="cover-upload" class="fa fa-camera fa-2x" aria-hidden="true"></label>
</form>
uploadcover.inc.php =>
<?php
session_start();
include_once 'dbh.inc.php';
$sessionid = $_SESSION['u_id'];
$filename = "../profile/cover".$sessionid.".*";
$fileinfo = glob($filename);
$fileExt= explode('.',$fileinfo[0]);
$fileActualExt= $fileExt[3];
$file = "../profile/cover".$sessionid.".".$fileActualExt;
if(!unlink($file)){
echo "File not deleted";
} else {
"File deleted";
}
$sql = "UPDATE coverimg SET status=1 WHERE user_id='$sessionid';";
mysqli_query($conn,$sql);
$file= $_FILES['file'];
$fileName= $file['name'];
$fileTmpName= $file['tmp_name'];
$fileSize= $file['size'];
$fileError= $file['error'];
$fileType= $file['type'];
$fileExt = explode('.',$fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png','gif');
if(in_array($fileActualExt,$allowed)){
if($fileError=== 0){
if($fileSize<3145728){
$fileNameNew = "cover".$sessionid.".".$fileActualExt;
$fileDestination = '../profile/'.$fileNameNew;
move_uploaded_file($fileTmpName,$fileDestination);
$sql = "UPDATE coverimg SET status=0 WHERE user_id='$sessionid'";
mysqli_query($conn,$sql);
header("Location: ../index.php?upload=success");
} else {
header("Location: ../index.php?upload=size_exceeded_3MB");
exit();
echo "<script>alert('File should be less than 3MB!')</script>";
}
} else {
header("Location: ../index.php?upload=error");
exit();
echo "<script>alert('Error uploading the file!')</script>";
}
} else{
header("Location: ../index.php?upload=typeerror");
exit();
echo "<script>alert('Filetype not supported!')</sc
ript>";
}
Note: I tried die(), exit() and also removing them in case it executes the script after being redirected to index.php but it doesn't work.
A redirect tells the client that why they are looking for can be found at a different URL. The client then requests that other URL and displays that document instead.
You can't simultaneously say "Here is the document you should show" and "The document you should show can be found over here". It is one or the other.