Cristiano Ronaldo and Balasz Dzsudzak bagged a brace in an extraordinary 3-3 draw as Hungary topped Group F with Portugal third.
Despite finishing behind Iceland in the group with just three draws, Portugal are still through to the Round of 16 and set up a huge match with Croatia.
The Hungarians found themselves in the position of already having qualified after four points from two games, but a defeat here would send Portugal through as Group F winners. It had been a dire campaign for Cristiano Ronaldo, who missed a penalty during their dismal stalemates with Iceland and Austria. Portugal moved to a 4-4-2 diamond midfield system.
Ronaldo vented his fury at Nani after failing to pass at the end of a long run, but it was Hungary who took the lead. A corner was not cleared effectively, so 37-year-old Zoltan Gera controlled for a fierce half-volley from the edge of the box.
It was almost 2-0, as Rui Patricio beat away an Akos Elek angled drive and Cristiano Ronaldo’s free kick was saved, while Pepe was offside when putting the ball in the net.
Portugal did equalise moments later, as Nani ran on to a Ronaldo through ball and beat Gabor Kiraly and his grey sweatpants at the near post.
Hungary restored their advantage at the dawn of the second half, as a Dzsudzak free kick took a deflection off Andre Gomes to wrong-foot Rui Patricio.
It was almost 3-1, but Lovrencsics hit the side-netting after the offside trap failed, then Portugal got it back to 2-2 with an extraordinary back-heel flick from Cristiano Ronaldo. It made history, as he became the first player to score in four different European Championships.
The drama continued to unfold at an extraordinary pace, as Dzsudzak saw another free kick charged down, his follow-up strike took one more deflection to lift it into the far top corner and put Hungary 3-2 up.
Joao Mario scuffed his finish wide after a confused Portuguese counter, but Ronaldo got Portugal on level terms again with a well-taken glancing header. Ricardo Quaresma provided the assist with his first touch via a corner.
Elek hit back immediately, but his strike thumped the woodwork with Rui Patricio beaten in this truly spectacular game.
Ronaldo nodded wide, but the scoreline no longer changed.
Hungary 3-3 Portugal
Gera 19 (H), Nani 42 (P), Dzsudzsak 47, 55 (H), Ronaldo 49, 62 (P)
Hungary: Kiraly; Lang, Guzmics, Juhász, Korhut; Gera (Bese 46), Pintér; Dzsudzsak, Elek, Lovrencsics (Stieber 82); Szalai (Nemeth 70)
Portugal: Patrício; Vieirinha, Pepe, Carvalho, Eliseu; Andre Gomes (Quaresma 61), W Carvalho, Joao Moutinho (Renato Sanchez 46), Joao Mario; Nani (Danilo 81), Ronaldo
Ref: Atkinson (ENG)
See the latest Serie A predictions and betting tips with Eurotips.co.uk