I'm setting up a CRUD and realized that I will need to delete the image that's stored in a directory if the user wants to upload a new image.
I have a webpage with a form that brings the information from the database row using the id, then posts the updated values to a script which is where the trouble is.
I'm trying to find the file that needs to be deleted with this:
$target_dir = "images/photo/";
$del_image = $_FILES["image"];
And trying to set the permissions of the file with this:
$change = chmod($del_image,0644);
Then trying the delete the file with this:
$delete = unlink($target_dir.$image);
Before I update everything with this:
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$file = $target_dir . basename($_FILES["ud_image"]["name"]);
$uploadOk = 1;
if (move_uploaded_file($_FILES["ud_image"]["tmp_name"], $file))
{
echo '<script type="text/javascript">';
echo 'alert("News Items Saved")';
echo '</script>';
} else {
echo "Sorry, there was an error with your file.";
}
$id = intval($_GET['id']);
$ud_headline = $_POST["ud_headline"]; //mysql_real_escape_string()
$ud_body = $_POST["ud_body"]; //mysql_real_escape_string()
$ud_image = $_POST["ud_image"]; //mysql_real_escape_string()
$query="UPDATE news SET
headline = '$ud_headline',
body = '$ud_body',
image = '$ud_image'
WHERE id='$ud_id'";
$mysqli->query($query)or die($mysqli->error);
if($mysqli->affected_rows>=1){
echo "<script type='text/javascript'>";
echo "alert('News Item Updated');";
echo 'document.location.href = "/pc.v.2/admin-news.php";';
echo "</script>;";
}
else
{
echo "<script type='text/javascript'>";
echo "alert('News Item Not Updated'. $mysqli->error);";
echo "</script>";
//echo "Error deleting record: " . $conn->error;
}
The errors I get are telling me that I'm not even finding the directory correctly, let alone the file.
This is the form:
<form action="update.php" method="post" class="newNews">
<input type="hidden" name="ud_id" value="<?=$id;?>">
<!-- <input type="hidden" name="old_id" value="<?=$image;?>"> -->
<label for="title">Title</label>
<input type="text" name="ud_headline" value="<?=$headline;?>"/><br />
<label for="text">Body</label>
<textarea name="ud_body" rows="15" cols="21" value=""><?=$body;?></textarea><br />
<p>Current Photo</p>
<img src="<?=$target_dir.$image?>" alt=''><br />
<input type="file" name="ud_image" class="newsImage" ><br />
<input type="submit" name="submit" value="Update news item" class='addNew' />
</form>
How can I fix this?