带空格和特殊字符的URL的最佳做法 [英] Best practices for URL with space and special characters

查看:166
本文介绍了带空格和特殊字符的URL的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在修改一个小型Web应用程序.该Web应用程序允许用户自己输入/指定类别.我注意到在数据库中,有很多类别都包含空格和特殊字符,例如Cakes&纸杯蛋糕.

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.

在前端,数据库以URL链接的形式显示所有用户定义的类别,用户可以单击它们以进一步查看类别中的内容.

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.

前端类别链接是使用rawurlencode函数编码的,看起来像这样.

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']); ?>

在后端,函数将GET URL,然后对其进行解码,然后将其发送到数据库进行查询.

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 somewhat 'last-minute' and 'unsophisticated'.

因此我想知道,PHP中URL特殊字符和空格的最佳实践是什么?

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

谢谢.

推荐答案

我更喜欢使用"slug"方法.您可以将字符串塞子化",然后在网址中使用塞子.

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

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

您需要在数据库中为该段添加一个列,但是您可以轻松地在url中表示用户输入字段并使它们可读. "function-to-slugify-strings-in-php"是一个词条,最初看起来像是在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".

这篇关于带空格和特殊字符的URL的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆