Home Backend Development PHP Tutorial PHP uses http_build_query, parse_url, parse_str to create and parse urls

PHP uses http_build_query, parse_url, parse_str to create and parse urls

Jul 25, 2016 am 08:46 AM
parse_url

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

See all articles