Try to convert an attachment URL into a post ID.

Signature

attachment_url_to_postid( $url )
url
 (string) The URL to resolve.

Return

(int) The found post ID.

Source

function attachment_url_to_postid( $url ) {
	global $wpdb;

	$dir = wp_upload_dir();
	$path = ltrim( $url, $dir['baseurl'] . '/' );

	$sql = $wpdb->prepare(
		"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
		$path
	);
	$post_id = $wpdb->get_var( $sql );
	if ( ! empty( $post_id ) ) {
		return (int) $post_id;
	}
}
WP Trac GitHub

Link here