The intention (niyyah) is a condition of the prayer being valid, and the prayer is not valid without the intention, because the Prophet (blessings and peace of Allah be upon him) said: Actions are but by intention, and each person will have but that which he intended. What is meant by intention is resolve, and its place is in the heart.
End quote from al-Mughni, 1/287
The intention may accompany the opening takbeer, or it may come before it.
Some scholars even said that there may be a long time between the intention and the prayer, so long as the intention is not cancelled.
See: al-Mawsooah al-Fiqhiyyah, 13/219
Al-Mardaawi said in al-Insaaf (2/23):
Others said: there may be a long time in between, so long as it (the intention) is not cancelled. Abu Taalib and others narrated (i.e., from Imam Ahmad): If he goes out of his house intending to pray, then this is the intention. Do you think that he would say the (opening) takbeer without intending to pray?
This is what is implied by the words of al-Khuraqi and it is the view favoured by al-Aamidi and Shaykh Taqi al-Deen in Sharh al-Umdah. End quote.
Shaykh Ibn Uthaymeen (may Allah have mercy on him) said:
This opinion is more correct, because his intention is accompanied by the ruling, so long as he does not intend to cancel it. When the adhaan is given, if this man does wudoo' for prayer, then the intention escapes his mind, then when the iqaamah is given for prayer he starts to pray without forming a new intention, his prayer is valid because he did not cancel the first intention. So the ruling on it is still connected to the action because of the words of the Prophet (blessings and peace of Allah be upon him): Actions are but by intentions. This man had intended to pray, and nothing happened to cancel out his intention.
End quote from al-Sharh al-Mumti, 2/296
And Allah knows best.
Reproduced from Islam QA