What are best practices for generating user-friendly URLs in PHP without exposing IDs?
When generating user-friendly URLs in PHP, it is important to avoid exposing internal IDs as they can pose security risks and make the URLs less user-friendly. One common practice is to use slugs or friendly names instead of IDs in the URL. This can be achieved by storing a unique slug for each resource in the database and using it to generate the URL.
// Example code snippet for generating user-friendly URLs without exposing IDs
function generateSlug($str) {
$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $str)));
return $slug;
}
// Assuming $title is the title of the resource
$title = "Example Title";
$slug = generateSlug($title);
// Construct the user-friendly URL
$url = "https://example.com/" . $slug;
echo $url;
Related Questions
- What are some best practices for structuring PHP code to separate HTML and PHP, especially when dealing with login forms and error messages?
- What are the advantages and disadvantages of using the imagepng() function in PHP for saving images?
- What are best practices for including external files in PHP scripts and ensuring their proper execution?