3

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?

tdrsam
  • 527
  • 1
  • 8
  • 28
  • Are you actually trying to overwrite the old file? Just so you know, move_uploaded_file() will overwrite the old file. – light Jun 12 '15 at 06:03
  • I tried but it wouldn't work, so I thought I better delete the old one first. – tdrsam Jun 12 '15 at 07:15

1 Answers1

0

PHP's move_uploaded_file() will actually overwrite the old file, so you don't actually need to perform the redundant unlink().

Since we don't have access to your server, we can't tell you exactly what went wrong. But it could be one (or more) of these:

  • Ensure that your $target_dir is prepended with $_SERVER['DOCUMENT_ROOT'].'/' or the root path of your server, e.g. '/var/www/'.
  • Ensure the folders actually exist.
  • Ensure your webserver has write permissions to the folders.
  • (a good practice) Check for file errors before upload

I'd do this to troubleshoot:

// Derive target paths
$target_dir = $_SERVER['DOCUMENT_ROOT'].'/images/photo/';
$target_path = $target_dir . basename($_FILES["ud_image"]["name"]);

// Check target dir exists and is writable
if (!file_exists($target_dir )) {
    // Try to automatically create the folders
    umask(0);
    if (!mkdir($target_dir , 0777, true)) { // or whatever permissions
        // Do your error handling here
        echo 'Sorry, target directory does not exist and we could not create it automatically.';
        exit(1);
    }
}
if (!is_writable($target_dir)) {
    // Do your error handling here
    echo 'Sorry, the directory is not writable.';
    exit(1);
}

// Check for file errors
if (!isset($_FILES["ud_image"]["tmp_name"])) {
    echo 'Sorry, no upload file detected.';
    exit(1);
}
if ($_FILES["ud_image"]["error"] > 0) {
    echo 'Sorry, there was an error with the file. Error code: '.$_FILES["ud_image"]["error"]);
    exit(1);
}

// Move uploaded file
if (!move_uploaded_file($_FILES["ud_image"]["tmp_name"], $target_path)) {
    // Do your error handling here
    echo "Sorry, there was an error with the upload operation.";
    exit(1);
}

// If you reach here, the upload should have succeeded. Go on to do whatever else you need to do
echo '<script>alert('News Item saved')</script>';

Just by the way, echo statements in server-side code is probably not a good idea, but that's besides the point. It's best to keep presentation and logic separate for maintainability and ease of troubleshooting.

light
  • 4,157
  • 3
  • 25
  • 38
  • This looks like it should work, but I can't get it going. It doesn't seem to be able to find the new file. – tdrsam Jun 15 '15 at 00:54
  • I changed the target directory to this: `$target_dir = 'images/photo/';` and it was working until I realized that I had changed the mysql statement to Insert. After I put back to Update it stopped working. The folder exists and has write permissions, but I'm getting an error saying the file was not detected, so I have a problem passing the file to the update script. I even added jquery to show the name of the file after it's selected (from the input type equals file, in the form) but it's not passing from there. – tdrsam Jun 15 '15 at 06:30
  • If you use the code I provided, and the error says "Sorry, no upload file detected." it simply means the file was not even uploaded. I think you need to explain your problem better, and maybe show your jQuery code and the html of the file input. As far as anyone can tell, this has nothing to do with your SQL, so you can safely leave your SQL code out. – light Jun 15 '15 at 09:39
  • It's definitely not the jQuery causing the problem. That only displays the name of the file the user has selected before they click submit. This is the input in the html `
    ` It's exactly the same as the one I have in the create section of the CRUD, which works fine. Just can't figure this out. I pass the image to the script which passes everything from the form to the database and it's done pretty much the same way as the create is done, but there's something wrong with it (the script is not getting the file, I think).
    – tdrsam Jun 15 '15 at 23:20
  • If your script is "not getting the file", there are a few possible reasons. You need to post the HTML of your form, and any JS that could have intercepted the form. – light Jun 16 '15 at 01:35
  • This is the entire form `


    Current Photo



    Fairly sure there's no js affecting it.
    – tdrsam Jun 16 '15 at 01:59
  • edit your question and put it in there please,for everyone's benefit. its also hard to read from comments. – light Jun 16 '15 at 02:01
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/80618/discussion-between-user2964055-and-light). – tdrsam Jun 16 '15 at 02:42