Skip to content
Advertisement

Deleting and Renaming in PHP

I am using an html form with a JS upload field to update the site logo.

I am trying to:

  1. Upload the new logo using the form
  2. Delete the old logo to free up the name
  3. Rename the uploaded logo so it is rendered as per the HTML (Light_Logo_Nav)

So far I have the following but it is not working:

if ( isset( $_POST['Edit_Business_Details'] ) && '1' === $_POST['Edit_Business_Details']){
    $URLcheck='https';
    $New_Light_Logo_Nav = $_POST['light_logo_nav'];
    $Light_Logo_Nav_Directory_Name = ABSPATH . "wp-content/uploads/Light_Logo_Nav";

        { 
            if(strpos($New_Light_Logo_Nav, $URLcheck) !== false){
                unlink($Light_Logo_Nav_Directory_Name);
                rename($New_Light_Logo_Nav , $Light_Logo_Nav_Directory_Name);
         }}}

Upon form submission, the file will have already been uploaded to the base directory and $_POST[‘light_logo_nav’] will contain the file path in the format: https://example.com/wp-content/uploads/Light_Logo_Nav.png

Advertisement

Answer

Thanks to all who commented, you comments pointed me in the right direction.

The problem was that the format https://example.. was not accepted for deleting, I was receiving the error unlink(): http does not allow unlinking

The work around I created was to save the name in a custom field, then use the ABSPATH, the following script shows how I filtered the URL to get the file name, then plug it into the ABSPATH

if ( isset( $_POST['Edit_Business_Details'] ) && '1' == $_POST['Edit_Business_Details']){
    $URLcheck='https';
    $New_Light_Logo_Nav = $_POST['light_logo_nav'];
    $light_logo_nav= get_post_meta( 10416, 'light_logo_nav' );
    $light_logo_nav_del=$light_logo_nav[0];
    $disallowed = array('http://example.com/wp-content/uploads/', 'https://example.com/wp-content/uploads/');
    $Updated_Light_Logo_Nav = array
    
        (
                                'light_logo_nav'    => $New_Light_Logo_Nav,
        );

    if(strpos($New_Light_Logo_Nav, $URLcheck) !== false){
        foreach($disallowed as $d) {
            if(strpos($light_logo_nav_del, $d) === 0) {
                $delete_existing_light_logo_nav=str_replace($d, '', $light_logo_nav_del);
                    wp_delete_file(ABSPATH . '/wp-content/uploads/'.$delete_existing_light_logo_nav);
      }
   }
                    wp_update_post(array(
                                           'ID'        => 10416,
                                           'meta_input'=> $Updated_Light_Logo_Nav));
}
}

This was working I don’t need to rename since I am dynamically requesting the custom field in HTML.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement