A man in a Colorado courtroom may have learned a valuable lesson on Wednesday: When you take off your hat in court, make sure a packet of cocaine doesn’t fall out in front of the judge.

That’s what happened to Juan Jose Vidrio Bibriesca, 43, police say. He was standing with two other defendants at an Eagle County court for violating his bond on a drug charge when he removed his hat and held it behind his back.

However, the unthinkable happened: A small square of folded paper fell out and landed on the floor, the Vail Daily reported.

UNDERCOVER VIDEO SHOWS WORKER KICKING COWS AT DAIRY FARM

A police officer in the gallery watched it unfold and another officer suggested they review surveillance footage to confirm who dropped the packet.

When they saw that it fell out of Bibriesca’s hat, he was immediately escorted to jail, the newspaper reported.

Bibriesca, who was born in Mexico and is reportedly in the country illegally, now faces charges of narcotics possession and bond violation, which are both felonies.