Sunderland forward Nicklas Bendtner scored twice (41,80) as Morten Olsen's side recovered from falling 2-0 behind to Pepe's headed opener on 24 minutes and a Helder Postiga finish from inside the Danish area on 36 minutes.
Despite Real Madrid forward Cristiano Ronaldo missing a couple of obvious chances, substitute Varela sealed the three points for Portugal - their first win of the year after a series of indifferent results in friendies - when he walloped a blistering shot into the corner of the net at the second attempt from Fabio Coentrao's delightful pass.
Portugal were worth their win on the night. They join Denmark and Germany on three points with Germany due to face the Netherlands later on Wednesday.
Denmark upset the Dutch 1-0 on Saturday to leave the group delicately poised before the final round of games.
Portugal are the only country to have taken part in at least one group phase at the European Championships without ever going home before the quarter-finals.
They were at risk of falling out of the tournament if they lost this match and Germany drew with the Dutch, but eased their nerves by moving ahead on 24 minutes when Real Madrid defender Pepe rose to power home a header from Joao Moutinho's corner.
They doubled their lead 12 minutes later as Postiga swept the ball high into the Danish goal beyond keeper Stephan Andersen from Nani's delicious pass.
With coach Morten Olsen frantically scribbling down notes, Denmark looked to be heading for a drubbing until they reduced the deficit almost out of nothing four minutes before half-time.
Substitute Jacob Poulsen picked out Michael Krohn-Dehli - scorer of the winner against the Netherlands - deep in the opposition area and he headed back across goal for Bendtner to nod into the unguarded net.
It was his 19th goal in his 50th match for Denmark and a fifth goal in five games against Portugal for the former Arsenal man.
Ronaldo should have put his country 3-1 clear on 51 minutes when he raced in on goal only to fluff his lines as his shot lacked the necessary pace to beat Andersen.
He then looked to have paid the ultimate price when he bounded onto Nani's ball only to slip the shot wide of goal on 78 minutes - Denmark went level three minutes later.
Lars Jacobsen threw over an inviting cross for Bendtner to net his sixth goal in five games against Portugal as his header hit the back of the net via Rui Patricio's glove and post.
It looked like Portugal would need results elsewhere to stay alive in the tournament, but their destiny is back in their own hands courtesy of Varela's winning goal.
Portugal know a win over the Netherlands on Sunday will be enough to secure their place in the last eight. Ronaldo will hope for better times.
Alongside Russia's Aleksandr Kerzhakov (11 shots) and Robin van Persie (eight shots), Ronaldo (10 shots) is in the top three forwards with most efforts at goal. All three have yet to score at the finals.