Sayyiduna Abdullah bin Abbas (may Allah be pleased with them both) narrates: "I was sitting with Sayyiduna Umar bin al-Khattab (may Allah be pleased with him) when he asked me: 'O Ibn Abbas! Have you heard anything from the Messenger of Allah (peace and blessings be upon him) that he (peace and blessings be upon him) ordered a Muslim man to do when he forgets in his prayer, how he should act?'"
He (Ibn Abbas, may Allah be pleased with them both) said: "I said: 'No, by Allah! O Commander of the Believers, have you heard anything from the Messenger of Allah (peace and blessings be upon him) about this?'"
He said: "No, by Allah, I have not." Meanwhile, Sayyiduna Abd al-Rahman bin Awf (may Allah be pleased with him) came and asked: "What are you two (discussing)?"
Sayyiduna Umar (may Allah be pleased with him) mentioned their conversation to him, and Sayyiduna Abd al-Rahman (may Allah be pleased with him) said to him: "But I have heard (a statement) from the Messenger of Allah (peace and blessings be upon him) about this."
Sayyiduna Umar (may Allah be pleased with him) said to him: "You are trustworthy in our view; so tell us, what did you hear from the Messenger of Allah (peace and blessings be upon him)?"
Sayyiduna Abd al-Rahman (may Allah be pleased with him) said: "I heard the Messenger of Allah (peace and blessings be upon him) say: 'When one of you forgets in his prayer, so that he does not know whether he has prayed (rak'ahs) more or less: if he is in doubt between one and two, let him count it as one; and if he is in doubt between two or three, let him count it as two; and if he is in doubt between three and four, let him count it as three, so that the doubt is on the side of excess; then he should perform two prostrations (of forgetfulness) while sitting, before giving the salam, and then give the salam.'"
Imam al-Tirmidhi (may Allah have mercy on him) narrated it from Ibn Bashshar, from Muhammad bin Khalid bin Uthman, from Ibrahim bin Sa'd (may Allah have mercy on him), with his chain, and said: "This hadith is hasan sahih."
And Imam Ibn Majah (may Allah have mercy on him) narrated it from Abu Yusuf Muhammad bin Ahmad al-Raqqi, from Muhammad bin Salamah, from Ibn Ishaq (may Allah have mercy on him), similarly.
And Isma'il al-Makki (may Allah have mercy on him) narrated it from Imam al-Zuhri (may Allah have mercy on him), from Ubaydullah bin Abdullah (may Allah have mercy on him), from Sayyiduna Ibn Abbas (may Allah be pleased with them both).