If the imam did not intend to lead the prayer, then people come and he leads them
It is permissible for a person who is praying alone to intend to lead the prayer, and act as imaam for those who join him in the prayer. The evidence for that is the hadeeth narrated by al-Bukhaari (667) and Muslim (763) from Ibn ‘Abbaas who said: “I stayed one night with my maternal aunt Maymoonah bint al-Haarith, and I said to her, ‘When the Messenger of Allaah (peace and blessings of Allaah be upon him) gets up, wake me up so that I can pray qiyaam al-layl.’ The Messenger of Allaah (peace and blessings of Allaah be upon him) got up, and I got up and stood beside him on his left. He took my hand and made me stand on his right, and whenever I closed my eyes he tweaked my ear, then he prayed eleven rak’ahs, then he slept until I could hear the sound of his breathing. When Fajr came he prayed two short rak’ahs. (Narrated by al-Bukhaari, 667; Muslim, 763).
The Messenger (peace and blessings of Allaah be upon him) started praying alone, then when Ibn ‘Abbaas joined him in prayer, he led him in the prayer.
Shaykh Ibn Baaz (may Allaah have mercy on him) was asked this question:
If I enter the mosque after the congregation (jamaa’ah) has finished praying, and I say the iqaamah for the prayer and say “Allaahu akbar” to start the prayer, then a man comes in after me and joins me in my prayer, and I did not intend that, is his prayer valid or not?
The correct view is that it is prescribed for you to form the intention of leading the prayer when one or more persons join you in prayer, because praying in congregation is something that is required and there is a great deal of virtue in that. Some of the scholars are of the view that this is valid in naafil prayers, but the correct view is that it is valid in both naafil (supererogatory) and fard (obligatory) prayers, because the basic principle is that the rulings on both are the same, except in cases where there is specific evidence. It was proven that the Prophet (peace and blessings of Allaah be upon him) used to pray on his own at night in the house of Maymoonah, the maternal aunt of Ibn ‘Abbaas (may Allaah be pleased with them all). Ibn ‘Abbaas got up, did wudoo’ and stood to the left of the Prophet (peace and blessings of Allaah be upon him), and the Prophet (peace and blessings of Allaah be upon him) made him move to his right. (Agreed upon) and led him in prayer.
Muslim narrated in his Saheeh that the Prophet (peace and blessings of Allaah be upon him) was praying alone, and Jaabir and Jabbaar came to him and stood to his right and his left. He made them stand behind him and led them in prayer. These two hadeeth indicate what we have mentioned. They also indicate that if there is only one other person, he should stand to the right of the imam, and if there are two or more they should stand behind him.
Majmoo’ Fataawa wa Maqaalaat Mutanawwi’ah li’l-Shaykh Ibn Baaz, 12/151.