简体   繁体   中英

how to set user agent for get_headers PHP function

I know It's easy to set user agent for curl but my code is based on get_headers, by default get_headers user agent is empty. thanks for any help.

也许这个?

ini_set('user_agent', 'Mozilla/5.0');

get_headers only specifies the data sent by the server to the client (in this case, PHP), it doesn't specify request headers.

If you're trying to find the user agent the get_headers request was made with, you'll have to use:

ini_get('user_agent');

For more documentation see the links below:

For anyone else coming here, the best option (instead of a server-wide change, which who knows what might break), is to use stream context options (the user agent option , in particular).

The PHP documentation already shows an example for change the HTTP method (sadly, also using a global setting ).

In any case, the code would be something like:

$context = stream_context_create([
    'http' => [
        'user_agent' => 'Mozilla/5.0'
    ]
]);

$headers = get_headers('http://example.com', true, $context);

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