WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] unlink() doesn't delete the file! (13 posts)

  1. aminb5
    Member
    Posted 10 months ago #

    Hi,
    I'm using this code in my plugin to add an extra field to the user profiles so that the user can upload an image. It uploads the file perfectly but the only problem is the part that has to delete the previous uploaded image doesn't work.

    This is my code:

    <?php
    add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
    add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );
    
    function my_show_extra_profile_fields( $user ) {
    ?>
    <script type="text/javascript">
        var form = document.getElementById('your-profile');
        form.encoding = "multipart/form-data";
        form.setAttribute('enctype', 'multipart/form-data');
    </script>
    <table class="form-table">
        <tr>
            <th><label for="profile_photo">Upload your profile photo</label></th>
            <td>
            <p>
                <input type="file" name="profile_photo" id="profile_photo" />
                <input type="hidden" name="action" value="save">
                <input type="submit" name="submitprofilephoto" id="submitprofilephoto" class="button" value="بارگذاری">
            </p>
                <span class="description">
                <?php
                $author_profile_photo = get_author_profile_photo($user->ID);
                if(is_array($author_profile_photo)):
                ?>
                    <a href="<?php echo $author_profile_photo["url"];?>" target="_blank">
                        <img src="<?php echo $author_profile_photo["file"];?>" height="100" width="100" />
                    </a>
                <?php
                endif;
                ?>
                </span>
            </td>
        </tr>
    </table>
    
    <?php
    }
    
    function get_author_profile_photo($user_ID) {
    
    $author_data = get_the_author_meta( 'profile_photo', $user_ID );
    $uploads = wp_upload_dir();
    $author_data["file"] = $uploads["baseurl"] . $author_data["file"];
    return $author_data;
    }
    
    add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
    add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );
    
    function my_save_extra_profile_fields( $user_id ) {
    
    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;
    
    $upload=$_FILES['profile_photo'];
    $uploads = wp_upload_dir();
    if(isset($_POST) && $_POST['submitprofilephoto']!='') {
        if ($upload['tmp_name'] && file_is_displayable_image( $upload['tmp_name'] )) {
    
                // handle the uploaded file
                $overrides = array('test_form' => false);
                $file=wp_handle_upload($upload, $overrides);
                $file["file"] = $uploads["subdir"]."/".basename($file["url"]);
    
                // Setup the array of supported file types. In this case, it's just Images.
                $supported_types = array( 'image/jpeg', 'image/pjpeg', 'image/png' );  
    
                // Get the file type of the upload
                $arr_file_type = wp_check_filetype(basename($upload['name']));
                $uploaded_type = $arr_file_type['type'];  
    
                // Check if the type is supported. If not, throw an error.
                if( $file && in_array($uploaded_type, $supported_types) ) {
                    if($upload['size'] > 204800) {
                         wp_die('<strong>ERROR</strong>: Maximum size allowed is 200KB.');
                    }
    
                    //remove previous uploaded file
                    $author_profile_photo = get_author_profile_photo($user_id);
                    @unlink($author_profile_photo["file"]);
                    // I even tried unlink without the @ and it still doesn't delete the file!
    
                    update_user_meta( $user_id, 'profile_photo', $file );
    
            } else wp_die('<strong>ERROR</strong>: Allowd image formats are JPEG, JPG and PNG.');
    
        } elseif (!file_is_displayable_image( $upload['tmp_name'] )) wp_die('<strong>ERROR</strong>: The file you selected is not an image!');
    }
    }
    ?>

    Where or what is the problem?
    Regards!

  2. flynsarmy
    Member
    Posted 10 months ago #

    First add an exit($author_profile_photo["file"]) just above your unlink line and make sure you see the filepath message when my_save_extra_profile_fields() is called. Do a nano <filepath> in the terminal and just make sure the file exists.

    Next up check file permissions. If you're calling unlink on a file that exists and it doesn't delete, chances are it's file permissions.

  3. aminb5
    Member
    Posted 10 months ago #

    I put the exit($author_profile_photo(["file"])); above the unlink link and when uploading it shows the url like this :
    http://SITENAME/wp-content/uploads/2013/10/IMAGENAME.png

    So do I have to check the permissions? How do I have to do that? Can you please guide me on that? I'm not familiar with it!

    Regards!

  4. catacaustic
    Member
    Posted 10 months ago #

    Remove the @ from in front of your unlink() function call. That way you'll see the error message instead of surpressing it.

  5. aminb5
    Member
    Posted 10 months ago #

    WP_DEBUG is true and I removed the @ from the beginning of unlink() but no error messages!

  6. catacaustic
    Member
    Posted 10 months ago #

    OK try something like this:

    unlink ($file);
    die ();

    And you really need to start learning some basic de-bugging skills. Mainly so that you can go through these things yourself and save a whole lot of time. :)

    BUT... Something else just came to mind. You do understand that under most circumstances you can't delete a file using the http:// protocol, you need to use the local file system URI, and not the internet URL.

    EG:

    Works: /path/to/file.jpg

    Doesn't work: http://www.site.com/file.jpg

  7. aminb5
    Member
    Posted 10 months ago #

    Yeah I put the wp_die('erorr!') thing and when uploading it died! and showed the erorr!

    I'm guessing it's either the path thing or the permissions.

    Any idea how I have to get the path like this: /path/to/file.jpg
    ??

  8. catacaustic
    Member
    Posted 10 months ago #

    It's the path. You can't set permissions over the internet. ;)

    As for how to get the file URI, no idea. The function of get_author_profile_photo() isn't a core WordPress function, so I'm going to guess that it's either from a plugin or some additional functionality that you've written for your theme? Where ever it's come from, I'd look around that area in the source code and you might find another function that does what you're looking for. If not ask in the pluign/themes support forum and you should get some sort of answer.

  9. aminb5
    Member
    Posted 10 months ago #

    Ok, I figured it out!

    I did some searching and I found this line of code that converts the url to path:

    function url_to_path_test($url){
      $url=str_replace(rtrim(get_site_url(),'/').'/', ABSPATH, $url);
     return $url;
     }

    So I did it like this in my code:

    //remove previous uploaded file
                        $author_bank_resid = get_author_bank_resid($user_id);
                        $url=str_replace(rtrim(get_site_url(),'/').'/', ABSPATH, $author_bank_resid["file"]);
                        @unlink($url);

    Thanks a lot for guiding me in the right direction!

    Regards.

  10. catacaustic
    Member
    Posted 10 months ago #

    That's a bit of a nasty way of doing it, but if it works... :/

    I'm sure that there's got to be a better way to do it, but without knowing what "extras" your using on your site it's impossible to say just how.

  11. aminb5
    Member
    Posted 10 months ago #

    Yeah your right!

    maybe something like this is better: ?

    //remove previous uploaded file
     $author_profile_photo = get_author_profile_photo($user_id);
     $httpurl = $author_profile_photo["file"];
     $url=url_to_path_test($httpurl);
     @unlink($url);

    and of course I have to declare the function url_to_path_test() too.

  12. catacaustic
    Member
    Posted 10 months ago #

    Maybe, but I meant more that there's most likely some function that can get the correct full file system URI for that file, not just hope that the escaping will be correct and get the right folder if something ever changes/moves. If that code is only used in that section, then there's no point at all in moving it to a separate function call.

  13. aminb5
    Member
    Posted 10 months ago #

    your absolutely right.

    This is what I came up at last :

    //remove previous uploaded file
     $author_data = get_the_author_meta( 'profile_photo', $user_id );
     $author_data["file"] = $uploads["path"] . $author_data["file"];
    
     $imagepath = $author_data["file"];
     @unlink($imagepath);

Reply

You must log in to post.

About this Topic