Jump to content
  • 0

Проблема формирования ссылок в интернет-магазине


SHMELODESSA
 Share

Question

Здравствуйте! Делаю интернет-магазин по книге "Кристиан Дари php и mysql. создание интернет-магазина". Проблема состоит в том, что при создании(изменении) пунктов меню с русскими символами ссылки не формируются. Кодировка сайта и базы MySql - utf8_general_ci. Есть подозрение на то, что необходимо внести изменения в класс ссылок

<?php
class Link
{
public static function Build($link, $type = 'http')
{
$base = (($type == 'http' || USE_SSL == 'no') ? 'http://' : 'https://') .
getenv('SERVER_NAME');

// If HTTP_SERVER_PORT is defined and different than default
if (defined('HTTP_SERVER_PORT') && HTTP_SERVER_PORT != '80' &&
strpos($base, 'https') === false)
{
// Append server port
$base .= ':' . HTTP_SERVER_PORT;
}

$link = $base . VIRTUAL_LOCATION . $link;

// Escape html
return htmlspecialchars($link, ENT_QUOTES);
}

public static function ToDepartment($departmentId, $page=1)
{
$link = self::CleanUrlText(Catalog::GetDepartmentName($departmentId)) .
'-d' . $departmentId . '/';

if ($page > 1)
$link .= 'page-' . $page . '/';

return self::Build($link);
}

public static function ToCategory($departmentId, $categoryId, $page=1)
{
$link = self::CleanUrlText(Catalog::GetDepartmentName($departmentId)) .
'-d' . $departmentId . '/' .
self::CleanUrlText(Catalog::GetCategoryName($categoryId)) .
'-c' . $categoryId . '/';

if ($page > 1)
$link .= 'page-' . $page . '/';

return self::Build($link);
}

public static function ToProduct($productId)
{
$link = self::CleanUrlText(Catalog::GetProductName($productId)) .
'-p' . $productId . '/';

return self::Build($link);
}

public static function ToIndex($page = 1)
{
$link = '';

if ($page > 1)
$link .= 'page-' . $page . '/';

return self::Build($link);
}

public static function QueryStringToArray($queryString)
{
$result = array();

if ($queryString != '')
{
$elements = explode('&', $queryString);

foreach($elements as $key => $value)
{
$element = explode('=', $value);
$result[urldecode($element[0])] =
isset($element[1]) ? urldecode($element[1]) : '';
}
}

return $result;
}

// Prepares a string to be included in an URL
public static function CleanUrlText($string)
{
// Remove all characters that aren't a-z, 0-9, dash, underscore or space
$not_acceptable_characters_regex = '#[^-a-zA-Z0-9_ ]#';
$string = preg_replace($not_acceptable_characters_regex, '', $string);

// Remove all leading and trailing spaces
$string = trim($string);

// Change all dashes, underscores and spaces to dashes
$string = preg_replace('#[-_ ]+#', '-', $string);

// Return the modified string
return strtolower($string);
}

// Redirects to proper URL if not already there
public static function CheckRequest()
{
$proper_url = '';

if (isset ($_GET['Search']) || isset($_GET['SearchResults']) ||
isset ($_GET['AddProduct']))
{
return ;
}
// Obtain proper URL for category pages
elseif (isset ($_GET['DepartmentId']) && isset ($_GET['CategoryId']))
{
if (isset ($_GET['Page']))
$proper_url = self::ToCategory($_GET['DepartmentId'],
$_GET['CategoryId'], $_GET['Page']);
else
$proper_url = self::ToCategory($_GET['DepartmentId'],
$_GET['CategoryId']);
}
// Obtain proper URL for department pages
elseif (isset ($_GET['DepartmentId']))
{
if (isset ($_GET['Page']))
$proper_url = self::ToDepartment($_GET['DepartmentId'],
$_GET['Page']);
else
$proper_url = self::ToDepartment($_GET['DepartmentId']);
}
// Obtain proper URL for product pages
elseif (isset ($_GET['ProductId']))
{
$proper_url = self::ToProduct($_GET['ProductId']);
}
// Obtain proper URL for the home page
else
{
if (isset($_GET['Page']))
$proper_url = self::ToIndex($_GET['Page']);
else
$proper_url = self::ToIndex();
}

/* Remove the virtual location from the requested URL
so we can compare paths */
$requested_url = self::Build(substr($_SERVER['REQUEST_URI'],
strlen(VIRTUAL_LOCATION)));

// 404 redirect if the requested product, category or department doesnt exist
if (strstr($proper_url, '/-'))
{
// Clean output buffer
ob_clean();

// Load the 404 page
include '404.php';

// Clear the output buffer and stop execution
flush();
ob_flush();
ob_end_clean();
exit();
}

// 301 redirect to the proper URL if necessary
if ($requested_url != $proper_url)
{
// Clean output buffer
ob_clean();

// Redirect 301
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $proper_url);

// Clear the output buffer and stop execution
flush();
ob_flush();
ob_end_clean();
exit();
}
}

// Create link to the search page
public static function ToSearch()
{
return self::Build('index.php?Search');
}

// Create link to a search results page
public static function ToSearchResults($searchString, $allWords,
$page = 1)
{
$link = 'search-results/find';

if (empty($searchString))
$link .= '/';
else
$link .= '-' . self::CleanUrlText($searchString) . '/';

$link .= 'all-words-' . $allWords . '/';

if ($page > 1)
$link .= 'page-' . $page . '/';

return self::Build($link);
}

// Create an Add to Cart link
public static function ToAddProduct($productId)
{
return self::Build('index.php?AddProduct=' . $productId);
}

// Create link to admin page
public static function ToAdmin($params = '')
{
$link = 'admin.php';

if ($params != '')
$link .= '?' . $params;

return self::Build($link, 'https');
}

// Create logout link
public static function ToLogout()
{
return self::ToAdmin('Page=Logout');
}

// Create link to the departments administration page
public static function ToDepartmentsAdmin()
{
return self::ToAdmin('Page=Departments');
}

// Create link to the categories administration page
public static function ToDepartmentCategoriesAdmin($departmentId)
{
$link = 'Page=Categories&DepartmentId=' . $departmentId;

return self::ToAdmin($link);
}
}
?>

На данный момент, ссылки с русскими символами(для категорий, отделов,товаров) просто не отображаются, имеют вид например: http://localhost/shop/-d1 , а должно иметь вид как http://localhost/shop/сейфы-d1 или http://localhost/shop/safes-d1.

Вопрос как сделать необходимое формирование ссылок и сделать транслитерацию.

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

Если необходим полный исходный код он здесь: http://www.cristiandarie.ro/php-mysql-ecommerce-2/

Ниже прилагаю скриншот, для наглядности проблемы, при наведении на пункт сейфы, необходимая ссылка не формируется. С английскими буквами все нормально.

http://i54.fastpic.ru/big/2012/1224/3f/3d7a84e53eaa0831242838b23009fa3f.jpg

Буду благодарен форумчанам за помощь. Заранее спасибо.

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Неужели Вы думаете, что кто то будет расшифровывать чужой индикод?

Беглый осмотр показал, что в класс необходимо добавить код транслитерации в CleanUrlText(). Но не факт, что заработает :D

Link to comment
Share on other sites

  • 0

Radiosity прав, нужно взять что-то типа вот этого:


function translited($string) {
$converter = array(
'а' => 'a', 'б' => 'b', 'в' => 'v',
'г' => 'g', 'д' => 'd', 'е' => 'e',
'ё' => 'e', 'ж' => 'zh', 'з' => 'z',
'и' => 'i', 'й' => 'y', 'к' => 'k',
'л' => 'l', 'м' => 'm', 'н' => 'n',
'о' => 'o', 'п' => 'p', 'р' => 'r',
'с' => 's', 'т' => 't', 'у' => 'u',
'ф' => 'f', 'х' => 'h', 'ц' => 'c',
'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch',
'ь' => '\'', 'ы' => 'y', 'ъ' => '\'',
'э' => 'e', 'ю' => 'yu', 'я' => 'ya',

'А' => 'A', 'Б' => 'B', 'В' => 'V',
'Г' => 'G', 'Д' => 'D', 'Е' => 'E',
'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z',
'И' => 'I', 'Й' => 'Y', 'К' => 'K',
'Л' => 'L', 'М' => 'M', 'Н' => 'N',
'О' => 'O', 'П' => 'P', 'Р' => 'R',
'С' => 'S', 'Т' => 'T', 'У' => 'U',
'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch',
'Ь' => '\'', 'Ы' => 'Y', 'Ъ' => '\'',
'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya',
);
return strtr($string, $converter);
}
function str2url($str) {
// переводим в транслит
$str = translited($str);
// в нижний регистр
$str = strtolower($str);
// заменям все ненужное нам на "-", а пробелы на "_"
$str = preg_replace('/[^a-z0-9_]+/', '_', str_replace(' ', '_', $str));
// удаляем начальные и конечные '-' и '_'
$str = trim($str, "-_");
return $str;
}

только тут наоборот русские - в транслит, а вам буквы надо местами поменять, но тогда скорее всего уже не будут работать транслитные адреса...

и вставить этот код как-то вот так:


function translited($str) {
$converter = array(
'а' => 'a', 'б' => 'b', 'в' => 'v',
'г' => 'g', 'д' => 'd', 'е' => 'e',
'ё' => 'e', 'ж' => 'zh', 'з' => 'z',
'и' => 'i', 'й' => 'y', 'к' => 'k',
'л' => 'l', 'м' => 'm', 'н' => 'n',
'о' => 'o', 'п' => 'p', 'р' => 'r',
'с' => 's', 'т' => 't', 'у' => 'u',
'ф' => 'f', 'х' => 'h', 'ц' => 'c',
'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch',
'ь' => '\'', 'ы' => 'y', 'ъ' => '\'',
'э' => 'e', 'ю' => 'yu', 'я' => 'ya',

'А' => 'A', 'Б' => 'B', 'В' => 'V',
'Г' => 'G', 'Д' => 'D', 'Е' => 'E',
'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z',
'И' => 'I', 'Й' => 'Y', 'К' => 'K',
'Л' => 'L', 'М' => 'M', 'Н' => 'N',
'О' => 'O', 'П' => 'P', 'Р' => 'R',
'С' => 'S', 'Т' => 'T', 'У' => 'U',
'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch',
'Ь' => '\'', 'Ы' => 'Y', 'Ъ' => '\'',
'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya',
);
return strtr($str, $converter);
}
// Prepares a string to be included in an URL
public static function CleanUrlText($string)
{
// переводим в транслит
$string = translited($string);
// в нижний регистр
$string = strtolower($string);
// заменям все ненужное нам на "-", а пробелы на "_"
$string = preg_replace('/[^a-z0-9_]+/', '_', str_replace(' ', '_', $string));
// удаляем начальные и конечные '-' и '_'
$string = trim($string, "-_");
return $string;
}

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy