How can I properly URL encode a string in PHP?

To URL encode a string in PHP, you can use the urlencode function. This function will encode any special characters in the string, making it safe to use in a URL.

For example:

<?php

$string = "Hello, World!";
$encoded_string = urlencode($string);

echo $encoded_string;

This will output:

Hello%2C+World%21

Watch a course Learn object oriented PHP

You can also use the rawurlencode function, which works the same way as urlencode, but also encodes characters that are not allowed in URLs, such as spaces.

For example:

<?php

$string = "Hello, World!";
$encoded_string = rawurlencode($string);

echo $encoded_string;

This will output:

Hello%2C%20World%21