This is something we get asked a lot. Most visitors to Morocco do not require visas and are allowed to remain in the country for 90 days on entry. Exceptions to this include nationals of Israel, South Africa and Zimbabwe; these people can apply for a three-month, single-entry visa (about US$30). In all cases, your passport must be valid for at least six months beyond your date of entry.
As visa requirements change, it’s a good idea to check with the Moroccan embassy in your country or a reputable travel agency before travelling.
The Spanish enclaves of Ceuta and Melilla have the same visa requirements as mainland Spain.
If 90 days is insufficient, the simplest thing to do is to leave (eg travel to the Spanish enclaves) and come back a few days later. Your chances improve if you re-enter by a different route.