First of all i am a beginner and idk if the following code is a proper way to do what i want but this is how i think i could do this (using forms to pass some values).
So, i use the following code to let the user choose if he wants to delete a file in folder, while uploading one with the same name in it. The parameters of the FIRST "move_uploaded_file" have the same content with the SECOND "move_uploaded_file" (this is why i echo them) and it is working perfectly but it is for files that DONT have the same name with the uploaded one.
So any ideas what is my mistake here? The delete (unlink) is working but when i click the "Yes" button it is not uploading the new file.
If you need more information let me know and sorry if this is a dumb question but i really cant understand what is wrong.
Thanks is advance!
<?php
$target_dir = "wp-content/themes/astra-child/myuploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
if (file_exists($target_file)) {
echo "Already exists.<br>";
echo "Do you want to replace the file?";
?>
<form action="" method="post">
<input type="hidden" id="myfilename" name="myfilename" value="<?php echo ($_FILES["fileToUpload"]["tmp_name"]);?>">
<input type="hidden" id="replacefilename" name="replacefilename" value="<?php echo basename($_FILES["fileToUpload"]["name"]);?>">
<input type="submit" value="Yes" name="btn-replace-yes">
<input type="submit" value="No" name="btn-replace-no">
</form>
<?php
if (isset($_POST['btn-replace-yes'])) {
$replacelink = $target_file . $_POST["replacefilename"];
unlink(realpath("$replacelink"));
$target = $target_file . $_POST["replacefilename"];
$last = $_POST["myfilename"];
$last = str_replace('\\\\', '\\', $last);
echo $last;
?><br><?php
echo $target;
if (move_uploaded_file($last, $target)){
$uploadOk = 0;
echo "The file with name «". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). "» is inserted in folder successfully!";
$uploadOk = 0;
mysqli_close($link);
} else {
echo "Failure.";?>
<button onclick="window.location.href='secretary-panel';">
Go Back
</button>
<?php
}
$uploadOk = 0;
}else if (isset($_POST['btn-replace-no'])){
$uploadOk = 0;
header("location:../secretary-panel/");
}
$uploadOk = 0;
}
?>
<?php
$target_dir = "wp-content/themes/astra-child/myuploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
// if everything is ok and we dont have the same name of the files, try to upload
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
echo $_FILES["fileToUpload"]["tmp_name"];?><br><?php
echo $target_file;
} else {
echo "Failure.";?>
<button onclick="window.location.href='secretary-panel';">
Go Back
</button>
<?php
}
}
?>