Sayyiduna Abu Humayd (may Allah be pleased with him) or Sayyiduna Abu Usaid (may Allah be pleased with him) said: The Messenger of Allah (peace and blessings be upon him) said: "When any of you enters the mosque, let him say: «اَللّٰهُمَّ افْتَحْ لِيْ أَبْوَابَ رَحْمَتِكَ» (O Allah! Open for me the doors of Your mercy). And when he leaves the mosque, let him say: «اَللّٰهُمَّ إِنِّيْ أَسْأَلُكَ مِنْ فَضْلِكَ» (O Allah! I ask You for Your bounty)."
Brief Explanation
(Commentary on Hadith 2725)
It is established with a sound chain in Ibn Majah and others that when a person enters the mosque, he should send salutations (salam) upon the Prophet sallallahu alayhi wa sallam, then say: «اَللّٰهُمَّ افْتَحْ لِيْ أَبْوَابَ رَحْمَتِكَ». Similarly, when leaving the mosque, he should first send blessings and salutations, then say: «اَللّٰهُمَّ إِنِّيْ أَسْأَلُكَ مِنْ فَضْلِكَ». In some narrations, there is also this addition: «اَللّٰهُمَّ اعْصِمْنِيْ مِنَ الشَّيْطَانِ الرَّجِيمِ» "O Allah, protect me from the accursed Shaytan (Satan)."
[ابن ماجه 773].