url_to_postid returns 0

when you are at the post URL, you don’t need to work with referer (which is not reliable moreover) but with $GLOBALS["post"] because you are in the PHP code which generate the page

then you can have the post ID with that :

$post_id = $GLOBALS["post"]->ID;