php notice undefined index http user agent

Неопределенный индекс (HTTP USER AGENT) для file_get_contents

В настоящее время я пытаюсь сделать запрос к системе API (возвращение в виде XML), и все работает нормально, когда я использую file_get_contents с URL:

Однако после того, как я найду идентификатор игры и добавлю? Gameid =Я БЫ на URL я получаю очень странную ошибку (которая, по-видимому, не позволяет мне превратить его в многоуровневый массив с помощью json_encode и json_decode).
Пример URL, который не работает:

Когда я использую var_dump для полученных данных, я возвращаю их в несколько искаженном формате со следующей ошибкой HTTP_USER_AGENT в начале, которая все портит.

Полный вывод выглядит примерно так:

Я не вижу этой ошибки, когда захожу по ссылке в моем браузере, поэтому я не уверен, что происходит.

Я также попытался использовать функцию curl ниже для вызова данных через URL, но не повезло. Я все еще получаю ту же ошибку.

CURL ФУНКЦИЯ

Решение

Похоже, этот «API» просто плохо написан. Он ожидает, что каждый сделанный запрос включает User-Agent заголовок запроса — и не учитывает, что не каждый клиент может отправить его. (Ваш браузер обычно это делает, поэтому вы не видите эту ошибку при посещении этого URL в вашем браузере, но ваш PHP-скрипт, по-видимому, этого не делает.)

На самом деле фиксировать это была бы работа любого, кто сделал бы этот API вместе. Если они потребность заголовок User-Agent для отправки вместе с запросом, тогда их скрипт должен проверять задано ли такое значение, и «изящно», если оно не установлено, т.е. возвращая какое-то сообщение об ошибке в виде XML.

В качестве обходного пути вы можете сделать file_get_contents Отправить User-Agent Заголовок в вашем скрипте.
Установка значения для user_agent значение конфигурации во время выполнения, используя ini_set должно хватить. Нужно ли вам отправить конкретный User-Agent (такой же, как обычный браузер), или, если достаточно просто какого-либо значения, попробуйте и посмотрите. Скорее всего подойдет любая ценность.

Если это не сработает, или вам нужно отправить какие-либо дополнительные заголовки, пожалуйста, обратитесь к такому вопросу SO: PHP file_get_contents () и заголовки

Изменить: Конечно, используя cURL, вы столкнулись с той же проблемой, если только вы не указали User-Agent, чтобы этот API не работал. Вы можете сделать это с помощью curl_setopt и CURLOPT_USERAGENT вариант.

Источник

Undefined index: HTTP_USER_AGENT in error logs

I have some problem with empty user user agent in my error logs most of which are happening on the 404 page where I am tracking all errors for further rectification or exclusion.

I have found few solutions that I can implement to solve the problem with this error so this is not too much of a problem, but I guess my real question is, as most of this errors have empty HTTP_USER_AGENT it looks to me like it is not a real user, but instead a robot that is trying my system for any loopholes. What I want to do is to create some sort of a trap for this, but I am not sure about one thing only, which is friendly bots like googlebot or yaoo slurp or similar that I preffer to keep unblocked from crawling my site. Do these friendly bots have any HTTP_USER_AGENT that I can ID it by, so that I am not blocking it accidentally? and my second question what is the right way to go about it? any code or pointers will help.

Thanks in advance and forgive me if my question is not entirely about getting stack and looking for solution in the code creation process. I am just tired of all this recent SPAM activity on my site and have nowhere to turn to search for reliable solutions except here.

I have to edit the question to make it clear.

Is it safe to just issue 403 if HTTP_USER_AGENT is empty?

One of the examples is the following to the page that never existed on my server STATUS 301, COUNTRY China, USER AGENT Bittorrent, then the same IP with blank user agent again.

Источник

Undefined Index (HTTP USER AGENT) on file_get_contents

I’m currently trying to query an API system (the return being XML), and everything works fine when I use file_get_contents with the URL:

When I use var_dump on the data I’ve retrieved, I get it back in a somewhat mangled format with the following HTTP_USER_AGENT error at the beginning, which mucks things up.

The full output looks something like:

I don’t see this error when I visit the link with my browser, so I’m not sure what’s going on.

I’ve also tried using the curl function below to call in the data via the URL, but no luck. I still get the same error.

CURL FUNCTION

1 Answer 1

Looks as if this “API” is just poorly written. It expects each and every request made to it to include a User-Agent request header – and fails to consider that not every client might send one. (Your browser usually does, which is why you don’t experience that error when you visit that URL in your browser, but your PHP script apparently does not.)

To actually fix this would be the job of whoever cobbled this API together. If they demand a User-Agent header to be send with the request, then their script should check whether such a value is set, and fail “gracefully” if it isn’t, f.e. by returning some kind of error message as XML.

As a workaround, you can make file_get_contents send a User-Agent header in your script.
Setting a value for the user_agent configuration value at runtime using ini_set should suffice. Whether or not you need to send a specific User-Agent (one like a common browser would send), or if just any value is enough, you have to try and see. Most likely any value will do.

If that doesn’t work, or you need to send any additional headers, then please refer to this SO question: PHP file_get_contents() and headers

Edit: Using cURL of course you got the same problem, unless you specify a User-Agent so that this API will not fail. You can do that using curl_setopt and the CURLOPT_USERAGENT option.

Источник

I am trying to do a registration form that registers a user in a database (MySQL).

The code is supposed to register:

The code, before saving to the table, checks whether the username or password already exists, and if they do it echoes an error message, and if not, it saves to the db.

However, on page load, I’m getting these errors:

Any help would be appreciated.

4 Answers 4

You’re getting errors because you’re attempting to read post variables that haven’t been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’)

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

php notice undefined index http user agent. Смотреть фото php notice undefined index http user agent. Смотреть картинку php notice undefined index http user agent. Картинка про php notice undefined index http user agent. Фото php notice undefined index http user agent

From line 215, update:

POST variables are coming from your form, and you have to check whether they exist or not, else PHP will give you a NOTICE error. You can disable these notices by placing error_reporting(0); at the top of your document. It’s best to keep these visible for development purposes.

You should only be interacting with the database (inserting, checking) under the condition that the form has been submitted. If you do not, PHP will run all of these operations without any input from the user. Its best to use an IF statement, like so:

Источник

Undefined index: HTTP_HOST /joomla/application/web.php #10203

Comments

photodude commented May 2, 2016 •

mod_fcgid: stderr: PHP Notice: Undefined index: HTTP_HOST in /libraries/joomla/application/web.php on line 863

Steps to reproduce the issue

Expected result

proper handling of situations where HTTP_HOST is undefined.

Actual result

mod_fcgid: stderr: PHP Notice: Undefined index: HTTP_HOST in /libraries/joomla/application/web.php on line 863

System information (as much as possible)

Additional comments

I’m sure something much more complex than

would be needed to fix this issue.

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

andrepereiradasilva commented May 2, 2016

does that happens in CLI scripts?

photodude commented May 2, 2016

@andrepereiradasilva I’m not sure, but I would venture to say that it’s not CLI scripts.

The server logs just say mod_fcgid: stderr: mod_fcgid: stderr: PHP Notice: Undefined index: HTTP_HOST /libraries/joomla/application/web.php on line 863

andrepereiradasilva commented May 2, 2016

i said that because in CLI scripts normally the HTTP_HOST doesn’t exist.

Bur the method is detectRequestUri and i don’t believe some CLI script is calling that.

andrepereiradasilva commented May 2, 2016

photodude commented May 2, 2016

@andrepereiradasilva I don’t believe that /libraries/joomla/application/web.php is ever used via CLI.

As far as I know all the use on the site for testing is related to web access not cli. I don’t believe this is the same, or even related to the issue you mentioned (as it’s throwing the error from a completly different file).

mbabker commented May 2, 2016

JApplicationWeb CAN be booted from a CLI environment. So in some ways it’s relevant.

photodude commented May 2, 2016

Thank @mbabker I was unaware that » JApplicationWeb CAN be booted from a CLI environment.»

So CLI is relevant, but unknown if CLI is part or source of the issue.

andrepereiradasilva commented May 2, 2016

photodude commented May 2, 2016

I have no server level cron tasks, and the one extension that I know has a cron like task that runs in CLI doesn’t seem to call JApplicationWeb or JUri

I will note that I recently read «$_SERVER[‘HTTP_HOST’] is not available when php is executed on the command line «

Which sounds like all cases where code is accessible via CLI will need to address the possibility that Undefined index: HTTP_HOST will happen under CLI

I did take a GEOIP check against the IP that triggered the notice and I am sure it’s just someone who happened onto the site via the web. So the issue is caused by either a script the triggers running something in CLI, or it’s some other issue.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *