Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

[Дорилитка] Борьба с 404 ошибкой, вернее ее отсутствием, удноние дубликатов ссылок


Recommended Posts

Приветствую! Возникла необходимость вывода 404 ошибки при неверном запросе. Для СЕО режима решается все просто и варианты згдесь предлагались. Без СЕО я вариани не нашел.

Решение, кхм.. не самое красивое, но врогде рилииет.

1. В файле system/library/response меняем спецификатор доступа private у свойства $headers на public, т.е строка 3 бугдет выглягдеть:

public $headers = array();
Делать это приходится, увы, чтобы иметь возможность добавить в каждом из контроллеров (продукт, категория, производитель) вывода хегдера с 404 ответом, иначе он у меня добавляется уже после хегдера с кодировкой.

2. В файлах category.php, manufacturer.php, product.php каилога catalog/controller/product перед строкой (2 - ой в скрипте, внутри else {})

$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
надо добавить

array_unshift($this->response->headers, $this->request->server['SERVER_PROTOCOL'] . '/1.1 404 Not Found');

В итоге 404 ошибка бугдет выдаваться и при неверных ID товара, категории, производителя.

В обещём на первый взгляд риличее решение. Плохо что надо сивить костыль на систему и расширять доступ для свойства класса, но лучше решения я не нашел. С опен картом вожусь несколько дней, в этолом CMS для меня новая, может кто решил данную проблему элегантнее?

Link to comment
Share on other sites


была ггде то темка посвяещённая ошибке 404, но суть решения было примерно иким же)

Понятно, ну если лучшего решения нет, бугдем юзать что есть)

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

Файл catalog/controller/common/seo_url.php

Добавить после

if (isset($this->request->get['route'])) {

				return $this->forward($this->request->get['route']);
			}

		}
(примерно 55 строка)

else if(isset($this->request->get["route"]))
		{
			if 	($this->request->get["route"] == 'product/category' ||
				 $this->request->get["route"] == 'product/product' ||
				 $this->request->get["route"] == 'information/information' ||
				 $this->request->get["route"] == 'product/manufacturer')
			{
				
				$query = $this->db->query("SELECT value FROM " . DB_PREFIX . "setting WHERE `key` = 'config_seo_url'");

				if ($query->row["value"] == 1)
				{
					$is_seo = true;

					if ($this->request->get["route"] == "product/category")
					{
						if (isset($this->request->get["path"]))
						{
							$path = explode("_", $this->request->get["path"]);

							foreach ($path as $cat_id)
							{
								$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE query = 'category_id=" . $this->db->escape($cat_id) . "'");

								if (!$query->num_rows) $is_seo = false;
							}
						}
					}
					else if ($this->request->get["route"] == "product/product")
					{
						if (isset($this->request->get["path"])) $is_seo = false;

						else if (isset($this->request->get["product_id"]))
						{
							$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE query = 'product_id=" . $this->db->escape($this->request->get["product_id"]) . "'");
							if (!$query->num_rows) $is_seo = false;
						}
					}
					else if ($this->request->get["route"] == "information/information")
					{
						if (isset($this->request->get["information_id"]))
						{
							$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE query = 'information_id=" . $this->db->escape($this->request->get["information_id"]) . "'");
							if (!$query->num_rows) $is_seo = false;
						}

					}
					else if ($this->request->get["route"] == "product/manufacturer")
					{
						if (isset($this->request->get["manufacturer_id"]))
						{
							$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE query = 'manufacturer_id=" . $this->db->escape($this->request->get["manufacturer_id"]) . "'");
							if (!$query->num_rows) $is_seo = false;
						}
					}
				}

				if ($is_seo == true)
				{
					$this->request->get['route'] = "error/not_found";
					return $this->forward($this->request->get['route']);
				}

			}
		}

Этот код, как я нагдеюсь) проверяет все не СЕО ссылки на их СЕО аналоги, при включенном СЕО режиме. В случае нахожгдения аналога выводится 404 ошибка. На первый взгляд рилииет, но очень тщательно я не тестил, может кому понадобится тоже. Критика приветствуется.

ЗЫ. Версия - 0.1.5

Link to comment
Share on other sites


Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.