简体   繁体   中英

How to use urlencode in PHP

I'm trying to use urlencode to convert the string: <a href="<?php print 'search.php?query='.quote_replace(addmarks($search_results['did_you_mean'])).'&search=1'?>">

Actually, I want to implement a search engine.

|-www
 |- index.php
 |- search directory
  |- search.php
  |- header.html
  |- search_form.html
  |- search_result.html
  |- footer.html

search.php includes header.html,search_form.html,search_result.html etc.

I access search.php using: localhost/index.php/?page=search

search_form.html include button to search. And it call search.php using: <form action="index.php/?page=search" method="get"> . I'm not sure if it's right.

After submitting the search request, search.php calls search_result.html to show result. The code in search_result.html: <a href="<?php print 'search.php?query='.quote_replace(addmarks($search_results['did_you_mean'])).'&search=1'?>"><?php print $search_results['did_you_mean_b']; ?> <a href="<?php print 'search.php?query='.quote_replace(addmarks($search_results['did_you_mean'])).'&search=1'?>"><?php print $search_results['did_you_mean_b']; ?>

It seems should work, but after I click the search button, the result url is index.php/?query=&search=1 . And I think it should be index.php/?page=search/?query=&search=1 .

So, I try to use urlencode to solve it. And I don't know if the idea is right.

$url = 'search.php?' . http_build_query(array(
    'query'  => $search_results['did_you_mean'],
    'search' => 1
));

That's the most simple way to go - please see http_build_query() .

I don't know what your functions quote_replace() and addmarks() do but when you run urlencode("search.php?query=") this will also encode the ? and the = and will result in search.php%3Fquery%3D (same for urlencode("&search=1") which encodes the & and the = and will result in %26search%3D1 ) which in total will make the URL unusable.

urlencode的用法如下:

$url = 'http://example.com/page?foo='.urlencode($foo).'&bar='.urlencode($bar);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM