I have this upload code copy pasted from w3 for image upload and included in a page. The problem is, when the page gets loaded for the first time all the alert boxes get triggered and run. I think the problem is probably because of the $uploadok being not ==. But how do I solve this issue so the alert do not run on start.
I'm actually a beginner so its kinda confusing to come with new logics.
So here is the code
<?php
session_start();
$path = "C:\wamp64\www\Allian\users/".$_SESSION['username']."/uploads";
if (!file_exists($path)) {
mkdir($path, 0700);
}
$target_dir = "users/".$_SESSION['username']."\uploads/";
$target_file = $target_dir . basename($_FILES["dp_btn"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if($_SERVER["REQUEST_METHOD"]=="POST") {
if(isset($_POST["btn_save_changes"])) {
$check = getimagesize($_FILES["dp_btn"]["tmp_name"]);
if($check !== false) {
echo "<script>alert('File is an image - " . $check["mime"] . ".')</script>";
$uploadOk = 1;
} else {
echo "<script>alert('File is not an image.')</script>";
$uploadOk = 0;
}
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "<script>alert('Sorry, file already exists.')</script>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["dp_btn"]["size"] > 500000) {
echo "<script>alert('Sorry, your file is too large.')</script>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "<script>alert('Sorry, only JPG, JPEG, PNG & GIF files are allowed.')</script>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "<script>alert('Sorry, your file was not uploaded.')</script>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["dp_btn"]["tmp_name"], $target_file)) {
echo "<script>alert('The file ". basename( $_FILES["dp_btn"]["name"]). " has been uploaded.')</script>";
} else {
echo "<script>alert('Sorry, there was an error uploading your file.')</script>";
}
}
?>
Thnx