开发者

Best practices for URL with space and special characters

开发者 https://www.devze.com 2023-02-06 11:42 出处:网络
I\'m currently modifying a small web application. This web application allow users to enter / specify a category themselves. I noticed that in the database, there\'s plenty of category that contain sp

I'm currently modifying a small web application. This web application allow users to enter / specify a category themselves. I noticed that in the database, there's plenty of category that contain spaces and special characters, like for example Cakes & cupcakes.

On the front-end, the database shows all the user defined categories in the form of URL links and user can click on them to further see what's in the category.

The front-end category links are encoded using the rawurlencode function and it looks something like this.

./show.php?category=<?php echo rawurlencode($e['category']); ?>

And on the back-end, a function will GET the URL and then decode it before it's being sent to the database for querying.

$category = rawurldecode(htmlspecialchars_decode($category));

It works fine but it seems som开发者_JS百科ewhat 'last-minute' and 'unsophisticated'.

As such I'm wondering, what is the best practice in PHP for URL special characters and spaces?

Thank you in advance.


I prefer to use the "slug" method. You could "slugify" the strings and use the slug in the url.

http://sourcecookbook.com/en/recipes/8/function-to-slugify-strings-in-php

You'll need to add a column to the database for the slug, but then you can easily represent user input fields in the url and make them readable. "function-to-slugify-strings-in-php" is a slug that probably originally looked something like "Function to slugify strings in PHP".

0

精彩评论

暂无评论...
验证码 换一张
取 消