Yii2 500 ошибка

Приветствую всех! Решил изучать vagrant и поднял на нем проект на yii2, все работало хорошо, но внезапно начала возникать ошибка 500 и никак не пойму причину. Сносил вагрант командой vagrant destroy и заново ставил vagrant up, но все равно ошибка 500. Прошу помочь понять причину возникновения этой ошибки и как исправить.


  • Вопрос задан

    более трёх лет назад

  • 1737 просмотров

http логи смотрим от сервера, затем от php.
смотрим также логи от приложения runtime/log/app.log.
также берем каждый запрос к бд и анализируем через explain наверняка индекса нету на большой таблице.
можно поставить newrealic или ему подобный мониторинг и найти все что тормозит еще быстрей.

Пригласить эксперта

Спасибо за ответы, посмотрел в логах, ошибка была в синтаксисе написанных мной файлов, исправил ошибки , сделал vagrant up и заработало


  • Показать ещё
    Загружается…

04 июн. 2023, в 16:13

2000 руб./за проект

04 июн. 2023, в 16:13

3000 руб./за проект

04 июн. 2023, в 16:06

2000 руб./за проект

Минуточку внимания

Стояло приложение Yii2 бэсик на сервере на всякий случай сообщаю php в консоли 5.4.16

перенес приложение на другой сервер, структура папок начинаю от корня / та же самая. на новом сервере php в консоли 5.3.3

база данных тоже перенсена.

На новом сервере получаю ошибку 500. если убрать htaccess пойти по прямому пути к индексному файлу приложения то он запускается криво, автолоадер подключается но на последней строке index.php где запускается приложение выскакивает 500ка

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

Куда смотреть я уже все логи и апача и php и что там еще есть сервака посмотрел. там нет ни единого намека на причину ошибки.

htaccess такой

Код: Выделить всё

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
 
# Если запрос не начинается с web, добавляем его
RewriteCond %{REQUEST_URI} !^/(yii2-app-basic)
RewriteRule (.*) yii2-app-basic/web/$1
 
# Если файл или каталог не существует, идём к yii2-app-basic/web/index.php 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . yii2-app-basic/web/index.php

Направьте пожалуйста.

Спасибо!

When an application finishes handling a request, it generates a response object
and sends it to the end user. The response object contains information such as the HTTP status code, HTTP headers and body.
The ultimate goal of Web application development is essentially to build such response objects upon various requests.

In most cases you should mainly deal with the response application component
which is an instance of yiiwebResponse, by default. However, Yii also allows you to create your own response
objects and send them to end users as we will explain in the following.

In this section, we will describe how to compose and send responses to end users.

Status Code ¶

One of the first things you would do when building a response is to state whether the request is successfully handled.
This is done by setting the yiiwebResponse::$statusCode property which can take one of the valid
HTTP status codes. For example, to indicate the request
is successfully handled, you may set the status code to be 200, like the following:

Yii::$app->response->statusCode = 200;

However, in most cases you do not need to explicitly set the status code. This is because the default value
of yiiwebResponse::$statusCode is 200. And if you want to indicate the request is unsuccessful, you may
throw an appropriate HTTP exception like the following:

throw new yiiwebNotFoundHttpException;

When the error handler catches an exception, it will extract the status code
from the exception and assign it to the response. For the yiiwebNotFoundHttpException above, it is
associated with the HTTP status 404. The following HTTP exceptions are predefined in Yii:

  • yiiwebBadRequestHttpException: status code 400.
  • yiiwebConflictHttpException: status code 409.
  • yiiwebForbiddenHttpException: status code 403.
  • yiiwebGoneHttpException: status code 410.
  • yiiwebMethodNotAllowedHttpException: status code 405.
  • yiiwebNotAcceptableHttpException: status code 406.
  • yiiwebNotFoundHttpException: status code 404.
  • yiiwebServerErrorHttpException: status code 500.
  • yiiwebTooManyRequestsHttpException: status code 429.
  • yiiwebUnauthorizedHttpException: status code 401.
  • yiiwebUnsupportedMediaTypeHttpException: status code 415.

If the exception that you want to throw is not among the above list, you may create one by extending
from yiiwebHttpException, or directly throw it with a status code, for example,

throw new yiiwebHttpException(402);

You can send HTTP headers by manipulating the header collection in the response component.
For example,

$headers = Yii::$app->response->headers;

// add a Pragma header. Existing Pragma headers will NOT be overwritten.
$headers->add('Pragma', 'no-cache');

// set a Pragma header. Any existing Pragma headers will be discarded.
$headers->set('Pragma', 'no-cache');

// remove Pragma header(s) and return the removed Pragma header values in an array
$values = $headers->remove('Pragma');

Info: Header names are case insensitive. And the newly registered headers are not sent to the user until
the yiiwebResponse::send() method is called.

Response Body ¶

Most responses should have a body which gives the content that you want to show to end users.

If you already have a formatted body string, you may assign it to the yiiwebResponse::$content property
of the response. For example,

Yii::$app->response->content = 'hello world!';

If your data needs to be formatted before sending it to end users, you should set both of the
format and data properties. The format
property specifies in which format the data should be formatted. For example,

$response = Yii::$app->response;
$response->format = yiiwebResponse::FORMAT_JSON;
$response->data = ['message' => 'hello world'];

Yii supports the following formats out of the box, each implemented by a formatter class.
You can customize these formatters or add new ones by configuring the yiiwebResponse::$formatters property.

  • HTML: implemented by yiiwebHtmlResponseFormatter.
  • XML: implemented by yiiwebXmlResponseFormatter.
  • JSON: implemented by yiiwebJsonResponseFormatter.
  • JSONP: implemented by yiiwebJsonResponseFormatter.
  • RAW: use this format if you want to send the response directly without applying any formatting.

While the response body can be set explicitly as shown above, in most cases you may set it implicitly by the return value
of action methods. A common use case is like the following:

public function actionIndex()
{
    return $this->render('index');
}

The index action above returns the rendering result of the index view. The return value will be taken
by the response component, formatted and then sent to end users.

Because by default the response format is HTML, you should only return a string
in an action method. If you want to use a different response format, you should set it first before returning the data.
For example,

public function actionInfo()
{
    Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
    return [
        'message' => 'hello world',
        'code' => 100,
    ];
}

As aforementioned, besides using the default response application component, you can also create your own
response objects and send them to end users. You can do so by returning such object in an action method, like the following,

public function actionInfo()
{
    return Yii::createObject([
        'class' => 'yiiwebResponse',
        'format' => yiiwebResponse::FORMAT_JSON,
        'data' => [
            'message' => 'hello world',
            'code' => 100,
        ],
    ]);
}

Note: If you are creating your own response objects, you will not be able to take advantage of the configurations
that you set for the response component in the application configuration. You can, however, use
dependency injection to apply a common configuration to your new response objects.

Browser Redirection ¶

Browser redirection relies on sending a Location HTTP header. Because this feature is commonly used, Yii provides
some special support for it.

You can redirect the user browser to a URL by calling the yiiwebResponse::redirect() method. The method
sets the appropriate Location header with the given URL and returns the response object itself. In an action method,
you can call its shortcut version yiiwebController::redirect(). For example,

public function actionOld()
{
    return $this->redirect('https://example.com/new', 301);
}

In the above code, the action method returns the result of the redirect() method. As explained before, the response
object returned by an action method will be used as the response sending to end users.

In places other than an action method, you should call yiiwebResponse::redirect() directly followed by
a chained call to the yiiwebResponse::send() method to ensure no extra content will be appended to the response.

Yii::$app->response->redirect('https://example.com/new', 301)->send();

Info: By default, the yiiwebResponse::redirect() method sets the response status code to be 302 which instructs
the browser that the resource being requested is temporarily located in a different URI. You can pass in a status
code 301 to tell the browser that the resource has been permanently relocated.

When the current request is an AJAX request, sending a Location header will not automatically cause the browser
to redirect. To solve this problem, the yiiwebResponse::redirect() method sets an X-Redirect header with
the redirection URL as its value. On the client-side, you may write JavaScript code to read this header value and
redirect the browser accordingly.

Info: Yii comes with a yii.js JavaScript file which provides a set of commonly used JavaScript utilities,
including browser redirection based on the X-Redirect header. Therefore, if you are using this JavaScript file
(by registering the yiiwebYiiAsset asset bundle), you do not need to write anything to support AJAX redirection.
More information about yii.js can be found in the Client Scripts Section.

Sending Files ¶

Like browser redirection, file sending is another feature that relies on specific HTTP headers. Yii provides
a set of methods to support various file sending needs. They all have built-in support for the HTTP range header.

  • yiiwebResponse::sendFile(): sends an existing file to a client.
  • yiiwebResponse::sendContentAsFile(): sends a text string as a file to a client.
  • yiiwebResponse::sendStreamAsFile(): sends an existing file stream as a file to a client.

These methods have the same method signature with the response object as the return value. If the file
to be sent is very big, you should consider using yiiwebResponse::sendStreamAsFile() because it is more
memory efficient. The following example shows how to send a file in a controller action:

public function actionDownload()
{
    return Yii::$app->response->sendFile('path/to/file.txt');
}

If you are calling the file sending method in places other than an action method, you should also call
the yiiwebResponse::send() method afterwards to ensure no extra content will be appended to the response.

Yii::$app->response->sendFile('path/to/file.txt')->send();

Some Web servers have a special file sending support called X-Sendfile. The idea is to redirect the
request for a file to the Web server which will directly serve the file. As a result, the Web application
can terminate earlier while the Web server is sending the file. To use this feature, you may call
the yiiwebResponse::xSendFile(). The following list summarizes how to enable the X-Sendfile feature
for some popular Web servers:

  • Apache: X-Sendfile
  • Lighttpd v1.4: X-LIGHTTPD-send-file
  • Lighttpd v1.5: X-Sendfile
  • Nginx: X-Accel-Redirect
  • Cherokee: X-Sendfile and X-Accel-Redirect

Sending Response ¶

The content in a response is not sent to the user until the yiiwebResponse::send() method is called.
By default, this method will be called automatically at the end of yiibaseApplication::run(). You can, however,
explicitly call this method to force sending out the response immediately.

The yiiwebResponse::send() method takes the following steps to send out a response:

  1. Trigger the yiiwebResponse::EVENT_BEFORE_SEND event.
  2. Call yiiwebResponse::prepare() to format response data into
    response content.
  3. Trigger the yiiwebResponse::EVENT_AFTER_PREPARE event.
  4. Call yiiwebResponse::sendHeaders() to send out the registered HTTP headers.
  5. Call yiiwebResponse::sendContent() to send out the response body content.
  6. Trigger the yiiwebResponse::EVENT_AFTER_SEND event.

After the yiiwebResponse::send() method is called once, any further call to this method will be ignored.
This means once the response is sent out, you will not be able to append more content to it.

As you can see, the yiiwebResponse::send() method triggers several useful events. By responding to
these events, it is possible to adjust or decorate the response.

When handling a RESTful API request, if there is an error in the user request or if something unexpected
happens on the server, you may simply throw an exception to notify the user that something went wrong.
If you can identify the cause of the error (e.g., the requested resource does not exist), you should
consider throwing an exception along with a proper HTTP status code (e.g., [[yiiwebNotFoundHttpException]]
represents a 404 status code). Yii will send the response along with the corresponding HTTP status
code and text. Yii will also include the serialized representation of the
exception in the response body. For example:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

The following list summarizes the HTTP status codes that are used by the Yii REST framework:

  • 200: OK. Everything worked as expected.
  • 201: A resource was successfully created in response to a POST request. The Location header
    contains the URL pointing to the newly created resource.
  • 204: The request was handled successfully and the response contains no body content (like a DELETE request).
  • 304: The resource was not modified. You can use the cached version.
  • 400: Bad request. This could be caused by various actions by the user, such as providing invalid JSON
    data in the request body, providing invalid action parameters, etc.
  • 401: Authentication failed.
  • 403: The authenticated user is not allowed to access the specified API endpoint.
  • 404: The requested resource does not exist.
  • 405: Method not allowed. Please check the Allow header for the allowed HTTP methods.
  • 415: Unsupported media type. The requested content type or version number is invalid.
  • 422: Data validation failed (in response to a POST request, for example). Please check the response body for detailed error messages.
  • 429: Too many requests. The request was rejected due to rate limiting.
  • 500: Internal server error. This could be caused by internal program errors.

Customizing Error Response

Sometimes you may want to customize the default error response format. For example, instead of relying on
using different HTTP statuses to indicate different errors, you would like to always use 200 as HTTP status
and enclose the actual HTTP status code as part of the JSON structure in the response, like shown in the following,

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

To achieve this goal, you can respond to the beforeSend event of the response component in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null && Yii::$app->request->get('suppress_response_code')) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the response (for both successful and failed responses) as explained when
suppress_response_code is passed as a GET parameter.

I had exactly the same problem. My website with ajax works perfectly in the localhost. but when i uploaded it to the server, I realized the ajax request where not workin returning the 500 internal error. And when i click the url it says that undefined variable.
Solution: Check the url of the ajax request:
before:

echo CHtml::textField('idsearch', '', array(
    'onKeyUp' => CHtml::ajax(
            array(
                'type' => 'POST',
                'dataType' => 'html',
                'data' => array(
                    'id' => 'js:idsearch.value'),
                'update' => '#dvfeeform',
                'url' => CController::createUrl('student/searchajax'),
    ))
));

after editing the url to:

'url' => Yii::app()->createUrl('student/searchajax'),

it worked perfectly fine.
hope it may help someone someday

#php #yii2

#php #yii2

Вопрос:

Я хочу вставить данные в таблицу с помощью post-запроса с использованием ajax, но я не могу прочитать данные, которые я просто отправляю с помощью ajax, вот мой код :

Код Ajax :

 $('#newList').on('beforeSubmit', function(e){
e.preventDefault();
$("#newList").modal('hide');
$("#title").val("");
load(1);
$.ajax({
    url: '/site/add-list',
    type: 'post',
    data: {title : $("#title").val()},
    success: function(data) {
      console.log(data); // return 500 (Internal Server Error)
    }
});
 

});

Контроллер :

 public function actionAddList()
{
    $req = Yii::$app->request;
    $newList = new Boards();
    return $req->post(); // return 500 (Internal Server Error)

}
 

каждый раз, когда я отправляю post-запрос, он продолжает указывать 500 (внутренняя ошибка сервера) на консоли. Но когда я возвращаю строку, например. «asdasd», это работает. Как мне это исправить?

Комментарии:

1. Пожалуйста, загляните в журнал ошибок веб-серверов. Он покажет вам полный текст ошибки, а не только ошибку 500. Затем опубликуйте соответствующую ошибку здесь.

2. Где вы получаете доступ к данным post? Я пропускаю что-то вроде $name = $request->post(‘title’) yiiframework.com/doc/guide/2.0/en/runtime-requests

3. Как упоминал Александр, вы стреляете в темноте — вы должны искать журналы, чтобы определить конкретную ошибку. ошибка 500 означает, что что-то на стороне сервера не так. В блоге вы бы точно увидели, что не так — какой файл, какая строка. Пока вы не поделитесь с нами логами — попробуйте прокомментировать строку: » $newList = new Boards();». Работает ли это сейчас?

4. Если вы используете отладчик Mozilla, на вкладке Network, где находится ваш запрос, вы можете увидеть ответ на запрос. Также какова ваша цель? Вы отправляете некоторую строку с post и после этого возвращаете ее такой же?

5. @vvpanchev моя цель — вставить строку в таблицу и отобразить ее во флэш-сообщении

Ответ №1:

Извините за поздний ответ, так что проблема в моем контроллере, он должен выглядеть так, чтобы ajax мог считывать возвращаемое значение

 public function actionAddList()
{
    $req = Yii::$app->request;

    if ($req->isAjax) {
        $res = ['data' => $req->post()];
        $newList = new Lists();
        $newList->title = $res["data"]["title"];
        $newList->save();
        echo $res["data"]["title"]; // Isnt error anymore
    } else {
        return false;
    }
    
}
 

Я получил ошибку, потому что я возвращаю массив на свой контроллер, поэтому мне просто нужно сделать что-то вроде этого

     // Bad
    return array(
        "data" => 'blabla'
    );

    // Good
    $dat = array(
        "data" => "blabla"
    );
    return $dat["data"];
 

Причина, по которой я получил ошибку 500 с консоли, вероятно, исходит от YII, потому что содержимое ответа не должно быть массивом.

 if (is_array($this->content)) {
        throw new InvalidArgumentException('Response content must not be an array.');
    } elseif (is_object($this->content)) {
        if (method_exists($this->content, '__toString')) {
            $this->content = $this->content->__toString();
        } else {
            throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().');
        }
    }
 

When handling a RESTful API request, if there is an error in the user request or if something unexpected
happens on the server, you may simply throw an exception to notify the user that something went wrong.
If you can identify the cause of the error (e.g., the requested resource does not exist), you should
consider throwing an exception along with a proper HTTP status code (e.g., [[yiiwebNotFoundHttpException]]
represents a 404 status code). Yii will send the response along with the corresponding HTTP status
code and text. Yii will also include the serialized representation of the
exception in the response body. For example:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

The following list summarizes the HTTP status code that are used by the Yii REST framework:

  • 200: OK. Everything worked as expected.
  • 201: A resource was successfully created in response to a POST request. The Location header
    contains the URL pointing to the newly created resource.
  • 204: The request was handled successfully and the response contains no body content (like a DELETE request).
  • 304: The resource was not modified. You can use the cached version.
  • 400: Bad request. This could be caused by various actions by the user, such as providing invalid JSON
    data in the request body, providing invalid action parameters, etc.
  • 401: Authentication failed.
  • 403: The authenticated user is not allowed to access the specified API endpoint.
  • 404: The requested resource does not exist.
  • 405: Method not allowed. Please check the Allow header for the allowed HTTP methods.
  • 415: Unsupported media type. The requested content type or version number is invalid.
  • 422: Data validation failed (in response to a POST request, for example). Please check the response body for detailed error messages.
  • 429: Too many requests. The request was rejected due to rate limiting.
  • 500: Internal server error. This could be caused by internal program errors.

Customizing Error Response

Sometimes you may want to customize the default error response format. For example, instead of relying on
using different HTTP statuses to indicate different errors, you would like to always use 200 as HTTP status
and enclose the actual HTTP status code as part of the JSON structure in the response, like shown in the following,

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

To achieve this goal, you can respond to the beforeSend event of the response component in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null && !empty(Yii::$app->request->get('suppress_response_code'))) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the response (for both successful and failed responses) as explained when
suppress_response_code is passed as a GET parameter.

В каждом ответе Http-протокола существует некий 3-х значный код. Он позволяет клиенту правильно трактовать полученный результат. Думаю всем веб-мастерам хорошо известен код «404 — Not found». Кодов на самом деле огромное множество, все они описаны в спецификации Http протокола. Но знать все не обязательно. Главное при создании Exception (исключения) выбрать правильную группу кодов ответа. Групп всего 5:

  • 1xx Информационные сообщения
  • 2xx Успешное выполнение запроса
  • 3xx Перенаправления (редирект)
  • 4xx Ошибки клиента
  • 5xx Ошибка на сервере

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

HttpException в Yii2

Зачем вообще нужны Exception? Для того, чтобы в случаи неожиданной ошибки, приложение могло сообщить о том, что его работа прекращена по такой-то причине. Exception можно отлавливать и обрабатывать, например с помощью конструкции try catch.
В Yii2 есть класс yiiwebHttpException с помощью которого можно создать любое исключение.

 throw new HttpException(404 ,'User not found');

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

  • BadRequestHttpException — 400 ошибка
  • UnauthorizedHttpException — 401 ошибка
  • ForbiddenHttpException — 403 ошибка
  • NotFoundHttpException — 404 ошибка
  • MethodNotAllowedHttpException — 405 ошибка
  • NotAcceptableHttpException — 406 ошибка
  • ConflictHttpException — 409 ошибка
  • GoneHttpException — 410 ошибка
  • UnsupportedMediaTypeHttpException — 415 ошибка
  • TooManyRequestsHttpException — 429 ошибка
  • ServerErrorHttpException — 500 ошибка

Все они отнаследованы от yiiwebHttpException и не нуждаются указании кода ответа.

 throw new NotFoundHttpException('User not found');

Установить статус ответа можно и с помощью метода setStatusCode() класса yiiwebResponse

Yii::$app->response->setStatusCode(422);

Это удобно тогда, когда есть необходимость передать что-либо в теле ответа.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Yii сообщение об ошибке
  • Yii показывать ошибки
  • Yii отображение ошибок
  • Yii обработка ошибок

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии