Emergency services in the southern Spanish city of Seville tweeted a video of the boy being led away from a bus they said came from Tangier, some 230 kilometres (143 miles) away, wearing a dirtied white t-shirt.
They said he had been taken to hospital but was in good condition.
— Emergencias Sevilla (@EmergenciasSev) June 26, 2017
A police spokesman told AFP the boy appeared to be Moroccan.
But he said he had been told the bus came from Tetouan, another Moroccan city still further away.
“The bus arrived in Seville, and when the driver was going to let the passengers out, he noted something strange,” the spokesman said.
“He called the police and firefighters, and they found the boy who was holding onto the bottom of the bus,” he added.
Migrants from Africa regularly risk their lives trying to get into Europe via Spain.
Many attempt to cross the Mediterranean sea in rickety boats or climb over the border fence that separates the Spanish territories of Ceuta and Melilla from northern Morocco.
Earlier this month, a car with five migrants hidden inside rammed its way through a border post between Morocco and Melilla, forcing officers to abandon their posts to avoid being run over.
Once inside Melilla, the Moroccan driver abandoned the car but was soon detained by police.
Inside the vehicle, they found five migrants — two in the boot, two others under a false bottom in the rear seats and another in the dashboard.