It is narrated from a man of the Ansar (may Allah be pleased with him) that a man came while the Prophet (peace and blessings be upon him) was praying, and he (peace and blessings be upon him) heard the sound of his footsteps. When he (peace and blessings be upon him) had finished the prayer with the salam, he said: "Which of you entered (the prayer)?" The man said: I did, O Messenger of Allah. He (peace and blessings be upon him) asked: "In what state did you find us?" He said: In prostration. He (peace and blessings be upon him) said: "Do likewise: when you find the imam standing, bowing, prostrating or sitting, do as you find him doing; and if you did not catch the bowing, do not count that rak'ah."
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الصلاة / 3619