Wordpress - Checking if a file is already in the Media Library

global $wpdb;
$image_src = wp_upload_dir()['baseurl'] . '/' . _wp_relative_upload_path( $filename );
$query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE guid='$image_src'";
$count = intval($wpdb->get_var($query));

You can use this at the top of your code. Then check the value of $count. If it's 0, then you can continue adding the attachment


I have this method (thanks Mridul):

function MediaFileAlreadyExists($filename){
    global $wpdb;
    $query = "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_value LIKE '%/$filename'";
    return ($wpdb->get_var($query)  > 0) ;
}

// MediaFileAlreadyExists("my-image.png");

I know this is a old question but I didn't like any of these answers so here is my solution.

This will check if the file exists. If so it will update the existing attachment; if not, it will create a new attachment.

// Get upload dir
$upload_dir    = wp_upload_dir();
$upload_folder = $upload_dir['path'];

// Set filename, incl path
$filename = "{$upload_folder}/myfile-{$id}.pdf";

// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );

// Get file title
$title = preg_replace( '/\.[^.]+$/', '', basename( $filename ) );

// Prepare an array of post data for the attachment.
$attachment_data = array(
    'guid'           => $upload_dir['url'] . '/' . basename( $filename ),
    'post_mime_type' => $filetype['type'],
    'post_title'     => $title,
    'post_content'   => '',
    'post_status'    => 'inherit'
);

// Does the attachment already exist ?
if( post_exists( $title ) ){
  $attachment = get_page_by_title( $title, OBJECT, 'attachment');
  if( !empty( $attachment ) ){
    $attachment_data['ID'] = $attachment->ID;
  }
}

// If no parent id is set, reset to default(0)
if( empty( $parent_id ) ){
  $parent_id = 0;
}

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment_data, $filename, $parent_id );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

In the example above I'm using a .pdf in my $filename but you can replace this with any filename/filetype.