France was wrong to imprison a Ghanian woman who was arrested at the Channel tunnel during an attempt to enter Britain illegally using a false passport, the EU’s most senior court has ruled.

The European court of justice said on Tuesday that the EU directive on returning irregular migrants prevents any member state imposing a prison sentence on a non-EU migrant who is in the country illegally, and whom they have not attempted to return.

Selina Affum had false travel documents when she was stopped by French police on a coach travelling to London from Ghent, in Belgium, in 2013.

“After presenting a Belgian passport with the name and photograph of another person, and lacking any other identity or travel document in her name she was initially placed in police custody on the grounds of illegal entry to French territory. The French authorities then requested Belgium to readmit her to its territory,” said the ruling, adding that Affum was challenging her detention.

An earlier opinion by the court’s advocate general in February was described by anti-EU campaigners as a blow to David Cameron’s attempts to crack down on migrants and refugees trying to “sneak into the UK”. They claimed that the European judge’s view that Affum should not have been imprisoned, but instead released, would have given her the chance to vanish.

The home secretary, Theresa May, is under pressure to increase resources, including from the Royal Navy, to stem the flow of refugees and migrants illegally crossing the Channel into Britain.

Theresa May delivering a speech on the EU in April. Photograph: Will Oliver/EPA

The European court ruling on Tuesday says that the EU directive for sending back “illegally staying third country nationals” lays down common standards and procedures that apply to all EU member states who want to remove illegally staying migrants from their territory.

The judges said that the directive provides that the migrant must be given a chance to go home voluntarily before the use of forced removal measures if they are necessary.

“If voluntary departure does not take place, the directive requires the member states to carry out forced removal using the least coercive measures possible. It is only if there is a risk of the removal being compromised that the member state may keep the person concerned in detention, the duration of which may not in any case exceed 18 months,” ruled the court in Luxembourg.

They said that illegal entrants could be imprisoned if they have previously been told they must leave and either refuse to go or try to re-enter the country after already having been deported. They can also be detained if they commit some other crime.

The ruling says the fact that Affum was merely in transit between Belgium and Britain when she was arrested in France does not mean the terms of the EU directive did not apply in this case.