Question

I looked around Stack Overflow for the recommended method type for PHP; either the GET or POST method. Recommended by the community, the GET method seems to be a good idea for passing queries for a simple search engine.

Unfortunately, the GET method adds unnecessary addition symbols to the URL to indicate spaces. Basically, a aesthetic issue.

I tried the trim() function to lessen the spaces, however, that is only called after the data is submitted and the URL is already set with the parameters.

Here is a the index.php file I think is not cooperating with me.

<?php $query = ""; ?>
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <form action="index.php" method="GET">
            <input type="text" name="query" placeholder="Enter Query">
            <input type="submit" text="Search">
        </form>

        <?php
            $query = $_GET['query'];
            print $query;
        ?>
    </body>
</html>

A example, if needed. If I type into the search bar this query...

sample 1

The URL will be formed this way...

http://localhost/search/index.php?query=sample++++++++++++++1

Is there a way to fix this problem or is the POST method the only way to circumvent this problem?

Was it helpful?

Solution

You will need to use the POST method.

 <!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="index.php" method="POST">
        <input type="text" name="query" placeholder="Enter Query">
        <input type="submit" text="Search">
    </form>

    <?php
        $query = $_GET['query'];
        print $query;
    ?>
</body>
</html>

OTHER TIPS

Use urlencode or str_replace. urlencode will replace all spaces with plus symbols, and with str_replace you can replace either underscores with plus symbols, or spaces with minus symbols.

Replace spaces with underscores: str_replace(' ', '_', $url);

Urlencode your $_GET*: urlencode($url);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top