search
HomeBackend DevelopmentPHP TutorialPHP uses http_build_query, parse_url, parse_str to create and parse urls

php uses http_build_query, parse_url, and parse_str to create and parse URLs. Friends in need can refer to it.


1.http_build_query

http_build_query can create the request string after urlencode.

  1. string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )
Copy code



Parameters:
query_data
Can be an array or an object containing properties.

A query_data array can be a simple one-dimensional structure, or an array composed of arrays (which in turn can contain other arrays).

If query_data is an object, only public attributes will be added to the result.

numeric_prefix
If numeric subscripts are used in the underlying array and this parameter is given, this parameter value will be used as a prefix for the numeric subscript elements in the underlying array.

This is to allow PHP or other CGI programs to obtain valid variable names when decoding the data later.

arg_separator
Unless this parameter is specified and used, arg_separator.output will be used to separate parameters (this parameter is available in php.ini, the default is "&").

enc_type
By default, PHP_QUERY_RFC1738 is used.

If enc_type is PHP_QUERY_RFC1738, the encoding will be based on the ? RFC 1738 standard and the application/x-www-form-urlencoded media type, and spaces will be encoded as plus signs (+).

If enc_type is PHP_QUERY_RFC3986, it will be encoded according to ? RFC 3986, and spaces will be percent encoded (%20).


Example 1: Only use query_data parameter

  1. $data = array(
  2. 'name' => 'fdipzone',
  3. 'gender' => 'male',
  4. 'profession' => 'programmer',
  5. 'explain ' => 'a new programmer'
  6. );
  7. echo http_build_query($data);
  8. ?>
Copy code

Output:
name=fdipzone&gender=male&profession=programmer&explain=a+new+programmer



Example 2: query_data uses a one-dimensional subscript array, specify
numeric_prefix=info_,arg_separator=#,enc_type=PHP_QUERY_RFC3986

  1. $data = array('fdipzone','male','programmer','a new programmer');
  2. echo http_build_query($data, 'info_', '#', PHP_QUERY_RFC3986) ;
  3. ?>
Copy code

Output:

  1. info_0=fdipzone#info_1=male#info_2=programmer#info_3=a%20new%20programmer
Copy code
2.parse_url

parse_url parses the url and returns its components

  1. mixed parse_url ( string $url [, int $component = -1 ] )
Copy code



Parameters:
url
URL to be parsed, invalid characters will be replaced with _

component
One of PHP_URL_PATH, PHP_URL_QUERY, or PHP_URL_FRAGMENT to get the string for the specified part of the URL. (Except when specified as PHP_URL_PORT, an integer value will be returned).

Return value:
parse_url() may return FALSE for severely unqualified URLs.

The returned data generally includes the following types
scheme (such as http), host, port, user, pass, path, query (after the question mark?), fragment (after the hash symbol #)


Example:

  1. $url = 'http://fdipzone:123456@www.fdipzone.com:80/test/index.php?id=1#tag';
  2. print_r(parse_url($url) );
  3. echo parse_url($url, PHP_URL_SCHEME).PHP_EOL;
  4. echo parse_url($url, PHP_URL_HOST).PHP_EOL;
  5. echo parse_url($url, PHP_URL_PORT).PHP_EOL;
  6. echo parse_url($url, PHP_URL_USER).PHP_ EOL ;
  7. echo parse_url($url, PHP_URL_PASS).PHP_EOL;
  8. echo parse_url($url, PHP_URL_PATH).PHP_EOL;
  9. echo parse_url($url, PHP_URL_QUERY).PHP_EOL;
  10. echo parse_url($url, PHP_URL_FRAGMENT).PHP_EOL;
  11. ?>
Copy code

Output:

  1. Array
  2. (
  3. [scheme] => http
  4. [host] => www.fdipzone.com
  5. [port] => 80
  6. [user] => fdipzone
  7. [pass] => 123456
  8. [path] => /test/index.php
  9. [query] => id=1
  10. [fragment] => tag
  11. )
  12. http
  13. www.fdipzone.com
  14. 80
  15. fdipzone
  16. 123456
  17. / test/index.php
  18. id=1
  19. tag
Copy code
3.parse_str

parse_str parses a string into multiple variables

  1. void parse_str ( string $str [, array &$arr ] )
Copy code

If str is the query string passed in by the URL, parse it into a variable and set it to the current scope.


Parameters:
str
Input string

arr
If the second variable arr is set, the variable will be stored in this array as an array element instead.


Example 1: Resolve to the current scope

  1. $str = 'name=fdipzone&gender=male&profession=programer&explain=a new programmer';
  2. parse_str($str);
  3. echo $name.PHP_EOL;
  4. echo $gender.PHP_EOL;
  5. echo $ profession.PHP_EOL;
  6. echo $explain.PHP_EOL;
  7. ?>
Copy code

Output:

  1. fdipzone
  2. male
  3. programer
  4. a new programmer
copy code



Example 2: Save the result to the arr array

  1. $str = 'name=fdipzone&gender=male&profession=programer&explain=a new programmer';
  2. parse_str($str, $arr);
  3. print_r($arr);
  4. ?>
Copy code

Output:

  1. Array
  2. (
  3. [name] => fdipzone
  4. [gender] => male
  5. [profession] => programer
  6. [explain] => a new programmer
  7. )
Copy code
4. Get the query parameters of the url and parse them

First use parse_url to get the query, and then use parse_str to parse the parameters

  1. $url = 'http://www.fdipzone.com/test/index.php?name=fdipzone&gender=male&profession=programmer&explain=a new programmer';
  2. $query = parse_url($url , PHP_URL_QUERY);
  3. parse_str($query, $data);
  4. print_r($data);
  5. ?>
Copy code

Output:

  1. Array
  2. (
  3. [name] => fdipzone
  4. [gender] => male
  5. [profession] => programmer
  6. [explain] => a new programmer
  7. )
Copy code
php, http


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.