简体   繁体   中英

Unlink image on Update PHP Form

I'm trying to create a fairly basic CMS for my own site. I attempting to create image form where I can update fields as well as unlink the old image file and attach the new if one is present. When I have a new image uploaded and then go back to the content management page and update either the title or the content of the form my image is unlinked automatically and deleted from the image folder on my local server. Any clue why this might be?

Here is some of the code...

if (isset($_POST["updateArea"])) {
    $areaID = $_GET["areaID"];
    $area = Web_areas::find_by_id($areaID);
    $area->title = $_POST['area_title'];
    $area->content = $_POST['area_content'];

    if (isset($_FILES['area_upload'])) {
        $old_target_path = SITE_ROOT.DS.'public'.DS.$area->image_path();
        unlink($old_target_path)
        $area->attach_file($_FILES['area_upload']);
        $area->update_image();

            redirect_to("../public/admin/manage_content.php");

    } else { 

        $area->update();
            redirect_to("../public/admin/manage_content.php");
    }

}

areaID is PHP being passed through the URL and then I use the static find_by_id to get the information from the database and instantiate it into object attributes that I can then reassign new values and update. Update_image() calls the update() function as well, but it also assigns the image to the directory using move_uploaded_file() .

Let me know if you need more information from me to help solving this problem. Thanks!!

Found the problem!! I was using if (isset()) for $_FILE when I should have been using is_uploaded_file(); So the code looks like this now and works great!

if (isset($_POST["updateArea"])) {
    $areaID = $_GET["areaID"];
    $area = Web_areas::find_by_id($areaID);
    $area->title = $_POST['area_title'];
    $area->content = $_POST['area_content'];

    if (is_uploaded_file($_FILES['area_upload'])) {
        $old_target_path = SITE_ROOT.DS.'public'.DS.$area->image_path();
        unlink($old_target_path);
        $area->attach_file($_FILES['area_upload']);
        $area->update_image();

            $_SESSION['area_message'] = "Area content and image updated successfully";
            redirect_to("../public/admin/manage_content.php");

    } else { 

        $area->update();
            $_SESSION['area_message'] = "Area content updated successfully";
            redirect_to("../public/admin/manage_content.php");

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM