I have scoured the internet and I'm either not finding the answer or I'm unable to implement it correctly.
Basically I am trying to implement a website in Russian on PHP. I have already got the website in English and French but bringing a whole new range of characters in has sort of broken the test site. My actual goal is to have the Cyrillic characters in the URL, similar to how Wikipedia are able to do it > https://ru.wikipedia.org/wiki/Компьютер and also still find this in the database to show the correct location information.
In my SQL database I have a range of locations, countries such as France, Germany, Australia etc. I have set it up so that the location page is generated dynamically from those entries using the $data['Name'] variable. Now... in the header.php file I use this to generate the location names from the database for the navigation:
<li class="dropdown">
Места
<ul>
<?php if (is_array($locations)) {
foreach ($locations as $key => $location) {
$name = strtolower(str_ireplace(" ","-", $location['name']));
if ($location['top_location'] == 1)
echo '<li>'.$location['name'].'</li>';
}
}
?>
</ul>
</li>
Where $name is replaced by database entries. If I change one of the database entries to Russian (Australia for example - Австралия) then the location page throws a 404 error as it's actually trying to find location/%D0%90%D0%B2%D1%81%D1%82%D1%80%D0%B0%D0%BB%D0%B8%D1%8F rather than location/Австралия.
My location page has the following code to get information from the database:
<?php
include './inc/utils.php';
if (isset($_GET['id'])) {
$name = str_ireplace("-"," ", $_GET['id']);
$result = get_data("Locations", array("name" => $name))[0];
}
else
$result = null;
if ($result != null) {
$data['Name'] = $result['name'];
$data['Url_Name'] = $_GET['id'];
$data['Image'] = $result['image'];
$data['Slider_Text'] = $result['slider_text'];
$data['Description'] = $result['description'];
$data['Country'] = $result['top_location'] != 0 ? true : false;
$data['Cars_In_Location'] = get_cars_in_location($result['id']);
$img_url = $MASTER['car_img_url'];
$link_url = $MASTER['base_url'].'car/';
$cities_id = explode(",", $result['related']);
foreach ($cities_id as $value) {
$data['Related'][] = get_data("Locations", array("id" => $value))[0];
}
}
else {
$data['Name'] = "";
$data['Url_Name'] = "";
$data['Image'] = "";
$data['Slider_Text'] = "";
$data['Description'] = "";
$data['Country'] = false;
$data['Related'] = "";
$data['Cars_In_Location'] = "";
}
if (empty($data['Name']) == true) {
header('HTTP/1.1 404 Not Found');
header('Location: '.$MASTER['base_url'].'404.php');
}
include 'header.php';
?>
I have tried using urldecode to no avail. I think I am missing something either on the SQL side or in one of the function files.
my header.php file contains both
<meta http-equiv="Content-type" content="text/html; charset=utf-8" /> and
header('Content-Type: text/html; charset=utf-8');
as well as my location page containing
header('Content-Type: text/html; charset=utf-8');
my .htaccess file has
AddDefaultCharset UTF-8
I don't know what else I'm missing.
You can see the page here:
https://redfoxluxurycarhire.com/ru/location/Австралия
I am using print_r($host_url) to correctly print the URL despite what it shows so you can see my issue. I am also able to echo Австралия onto the location pages with no problems or encoding.
Any help would be much appreciated as I'm wracking my brain as how to get this to work!
I would start checking if you have any file-systems encoding problem. Check your scripts are using UTF-8, I believe your MySQL database is OK. You should be able to decode requests with urldecode.
Related
I have a problem of charset.
On localhost everything works fine, but now on remote server I see strange characters replacing others like à or è. I have read it's a charset issue and I think the problem can be my php.ini (I can't edit it).
To solve it I've tried many things:
I've set
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
on html,
ini_set('default_charset', 'UTF-8');
on php,
AddDefaultCharset utf-8
on my .htaccess file,
if I use utf8_encode on strings letters are replaced by ã or similar, if I leave it without doing anything letters are �
There is another way to solve this problem that I have not found yet?
Sorry, I forgot to say it: strings are retrieved from another site by a file_get_contents (I'm using a Yandex API)
Here's some code:
$yandex = 'https://dictionary.yandex.net/api/v1/dicservice.json/lookup?key=my_api_key&lang=it-it&text=attualità';
// get json from this page
$object = json_decode(file_get_contents($yandex));
$syns_array = array();
$type = '';
// if the word exists
if (!empty($object->def) && $object->def != FALSE && $object->def != NULL)
{
$type = $object->def[0]->tr[0]->pos;
$rows = $object->def[0]->tr;
// if there're synonyms
if (!empty($rows) && $rows != FALSE && $rows != NULL)
{
foreach ($rows as $row)
{
array_push($syns_array, $row->text);
// if there're more rows with syns
if (!empty($row->syn) && $row->syn !== FALSE && $row->syn !== NULL)
{
foreach ($row->syn as $syns_obj)
{
array_push($syns_array, $syns_obj->text);
}
}
}
}
}
// I echo my synonyms from the array
foreach($syns_array as $syn) {
echo $syn;
}
I forgot to say I was using mb_strtolower on those strings. Replacing it with strotolower the problem is solved... Sorry
I have a JSON file and in it consists of site data. This site data is for a homepage (I decode the JSON into variables so I can echo them out within the HTML).
Here is my code:
<?php
//start json stuff
$path = "../assets/json/home.json";
$fileexists = file_exists($path);
if ($fileexists) {
$json_d = file_get_contents($path,TRUE);
$json = json_decode($json_d,TRUE);
} else {
die("Error retrieving site data - please refresh the page. If that doesn't work, please report a problem, here and come back later.");
}
if(isset($_POST['submit'])) {
$navtitle = $_POST['navtitle'];
$title = $_POST['title'];
$json_arr = array('navtitle' => $navtitle, 'title' => $title);
$json_enc = json_encode($json_arr);
$json_result = file_put_contents($path, $json_enc);
if($json_result) {
echo "<script>alert('WORKING!');</script>";
} else {
echo "<script>alert('NO WORKING!');</script>";
}
}
?>
So, I have created the array, encoded the array and placed it in the file (I think) but I do not see any changes.
NOTE: I have added the <meta http-equiv="expires" content="0"> meta tag to force the website/browser to grab the home.json file everytime the page is loaded in.
Thank you for any help.
I am passing a website and a message through a url to another webpage. The website in its self contains some get variables. The problem comes from the fact that when the site and the message is passed, the site variables are being truncated. I have searched for a way to solve this and did not understand what others were doing. Thanks for the help in advance. The code is below:
<?php
$I_D = 0;
$EI_D = 1;
$site = "orowland/eval.php?eval=$I_D&stats=$EI_D";
header("location:message.php?message=Site has been created&site=$site");
?>
In message.php:
<?php
if (isset($_GET['message']))
{
$message = $_GET['message'];
$site = $_GET['site'];
echo $message;
echo $site;
}
?>
Output on page:
orowland/eval.php?eval=0
But the expected output is:
orowland/eval.php?eval=0&stats=1
It is probably a good idea to urlencode() that string as it contains spaces
So do
<?php
$I_D = 0;
$EI_D = 1;
$site = "orowland/eval.php?eval=$I_D&stats=$EI_D";
$message = urlencode('Site has been created');
$url = "message.php?message=$message&site=$site";
header("location: $url");
?>
So I have this program that allows a user to enter information into a form and upon submission turns that information into a JSON file. When a user goes to a different part of the program, the programs retrieves the JSON file and builds a questionnaire out of it.
The building of the JSON file works fine but whenever I try to retrieve the file I'm getting an error that the JSON is returning as ASCII and as NULL. I've done my homework and saw that this usually happens when their is an encoding conflict(even though ASCII is a subset of UTF-8...).
So I made sure that when creating the file I'm using using mb_convert_encoding($x, 'UTF-8', 'auto');
to ensure that the JSON is properly being encoded as UTF-8.
I was also using mb_convert_encoding when retrieving the JSON, but saw that double encoding can cause issues so when I removed that piece it no longer echoed out what the encoding was(using mb_detect_encoding) but it is still NULL.
I even went so far as to pull down the JSON file, save it as UTF-8 and re-upload it.
Any and all help on this is much appreciated it. I've banged my head for two days over this. This is built in Code Ignitor, if that makes a difference
Here is the code to create the JSON file:
$thisClient = $this->input->cookie('client');
$date = "%m-%Y";
$date = mdate($date);
$clientDir = *********PATH TO CREATE THE DIRECTORIES IN;
$dialogDir = $clientDir."/".$date;
$d_file_name = $thisClient.'-'.$date;
//check to see if client directory exists, if it doesn't then it creates it
if(!is_dir($clientDir)){
mkdir($clientDir, 0755, TRUE);
echo "Client Directory Created!<br>";
} else{
echo "No Client Directory Created!<br>";
}
//check to see if client directory exists, if it doesn't then it creates it
if(!is_dir($dialogDir)){
mkdir($dialogDir, 0755, TRUE);
echo "DIALOG Directory Created!<br>";
} else{
echo "No DIALOG Directory Created!<br>";
}
$custDialog = array();
if(isset($_POST['cust-dialog-title'])){
function encodeMe($x){
//this ensure proper encoding
return mb_convert_encoding($x, 'UTF-8', 'auto');
}
$customDialog = array();
for($i = 0; $i < count($_POST['cust-dialog-title']); $i++){
$customDialog[$i]["title"] = encodeMe($_POST['cust-dialog-title'][$i]);
$customDialog[$i]["intro"] = encodeMe($_POST['cust-dialog-intro'][$i]);
for($ii = 0; $ii < count($_POST['cust-dialog-quest-'.$i]); $ii++){
$customDialog[$i]["questions"]["q".$ii] = encodeMe($_POST['cust-dialog-quest-'.$i][$ii]);
if($_POST["cust-dialog-pos-".$i."-".$ii] == "TRUE"){
//if the question is a true positive
$customDialog[$i]["questions"]["agree"] = -5;
$customDialog[$i]["questions"]["disagree"] = 5;
} else{
//if the question is a false positive
$customDialog[$i]["questions"]["agree"] = 5;
$customDialog[$i]["questions"]["disagree"] = -5;
}
}
$jsonDIALOG = json_encode($customDialog);
$jsonDIALOG = str_replace("[", " ", str_replace("]", " ", $jsonDIALOG));
if ( ! write_file($dialogDir."/".$d_file_name.".json", $jsonDIALOG )) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
//save Custom DIALOG info in database
***********DATABASE INFO**************
}
}
Here is the code to retrieve the JSON object:
if($row["custom"] !== null){ //If the Dialog is a Custom Dialog
$path = str_replace(*****removes an unnecessary portion from the path string**);
$thisDialog = file_get_contents(****PATH TO JSON FILES*****);
//THE FOLLOWING helps debug issues with the JSON -- displays order number and dialog being called -- uncomment to use
//echo $i.' is '.$curDialog[$i]. '<br>';
//$thisDialog = substr($thisDialog,1);
//echo $thisDialog;
//THIS IS THE CODE FOR DEBUGGING ENCODING ISSUES
//$thisDialog = mb_convert_encoding($thisDialog, 'UTF-8', 'ASCII');
//echo mb_detect_encoding($thisDialog);
$jsonDialog = json_decode($thisDialog, true);
echo var_dump($jsonDialog);
if($jsonDialog){
$allDialogs = $jsonDialog;
} else {
echo "Error: Invalid Dialog. Call Order# 0<br>" ;
}
return $allDialogs;
}
I've included some debugging things that I've tried and commented out. Thanks!!
You should probably add JSON_UNESCAPED_UNICODE as an option to json_encode. Keep in mind that this constant is available since PHP 5.4.0
today one of my friends had a problem with his guestbook. We use a small php orientated guestbook which was working fine except for one thing: it had reached its limit of messages.
So what i did is edit the blog file and change the following setting:
//Maximum entry stored in data file
$max_record_in_data_file = 1800;
The moment I did this though, something went very wrong. I uploaded the file back on the server and got the following:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at E:\inetpub\vhosts\trilogianocturnus.com\httpdocs\guestbook.php:1) in E:\inetpub\vhosts\trilogianocturnus.com\httpdocs\guestbook.php on line 95
I don't know what this is, I'm very new to php, but from what I understand, it means something is already being called by the browser before session_start
The page is located at:
http://trilogianocturnus.com/guestbook.php
The code before the head is as follows:
<?
/*-----------------------------------------------------
COPYRIGHT NOTICE
Copyright (c) 2001 - 2008, Ketut Aryadana
All Rights Reserved
Script name : ArdGuest
Version : 1.8
Website : http://www.promosi-web.com/script/guestbook/
Email : aryasmail#yahoo.com.au
Download URL :
- http://www.promosi-web.com/script/guestbook/download/
- http://www.9sites.net/download/ardguest_1.8.zip
This code is provided As Is with no warranty expressed or implied.
I am not liable for anything that results from your use of this code.
------------------------------------------------------*/
//--Change the following variables
//Title of your guestbook
$title = "Guestbook Nocturnus";
//Change "admin" with your own password. It's required when you delete an entry
$admin_password = "***";
//Enter your email here
$admin_email = "***";
//Your website URL
$home = "http://www.trilogianocturnus.com/main.html";
//Send you an email when someone add your guestbook, YES or NO
$notify = "YES";
//Your Operating System
//For Windows/NT user : WIN
//For Linux/Unix user : UNIX
$os = "WIN";
//Maximum entry per page when you view your guestbook
$max_entry_per_page = 10;
//Name of file used to store your entry, change it if necessary
$data_file = "ardgb18.dat";
//Maximum entry stored in data file
$max_record_in_data_file = 1800;
//Maximum entries allowed per session, to prevent multiple entries made by one visitor
$max_entry_per_session = 10;
//Enable Image verification code, set the value to NO if your web server doesn't support GD lib
$imgcode = "YES";
//Color & font setting
$background = "#000";
$table_top = "#000";
$table_content_1a = "#090909";
$table_content_1b = "#000000";
$table_content_2a = "#090909";
$table_content_2b = "#000000";
$table_bottom = "#000";
$table_border = "#1f1f1f";
$title_color = "#9f0000";
$link = "#9f0000";
$visited_link = "#9f0000";
$active_link = "#9f0000";
$font_face = "verdana";
$message_font_face = "arial";
$message_font_size = "2";
//-- Don't change bellow this line unless you know what you're doing
$do = isset($_REQUEST['do']) ? trim($_REQUEST['do']) : "";
$id = isset($_GET['id']) ? trim($_GET['id']) : "";
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$self = $_SERVER['PHP_SELF'];
if (!file_exists($data_file)) {
echo "<b>Error !!</b> Can't find data file : $data_file.<br>";
exit;
} else {
if ($max_record_in_data_file != "0") {
$f = file($data_file);
rsort($f);
$j = count($f);
if ($j > $max_record_in_data_file) {
$rf = fopen($data_file,"w");
if (strtoupper($os) == "UNIX") {
if (flock($rf,LOCK_EX)) {
for ($i=0; $i<$max_record_in_data_file; $i++) {
fwrite($rf,$f[$i]);
}
flock($rf,LOCK_UN);
}
} else {
for ($i=0; $i<$max_record_in_data_file; $i++) {
fwrite($rf,$f[$i]);
}
}
fclose($rf);
}
}
}
session_start();
$newline = (strtoupper($os) == "WIN") ? "\r\n" : "\n";
switch ($do) {
case "":
$record = file($data_file);
rsort($record);
$jmlrec = count($record);
?>
I have of course, removed the password and email for security, now here isthe funny part.
This error started happening the moment i changed that setting up up there, but if i tried to revert it back to 1800 (i changed it to 11800 to test it out), it still gives me that error.
Any idea of what this is?
The guestbook url is: promosi-web.com/script/guestbook/
The most common cause of this error is something being added to the file before the <?
Most likely a space or UTF byte order mark.
Put your session_start() after <? and you should be fine
Note:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
http://php.net/manual/en/function.session-start.php
The message says that the “output started at …\guestbook.php:1”. So there must be something in that file on that line that initiated the output.
Make sure that there are no whitespace or other invisible characters (like a BOM) before the opening <? tag.
Check if you have a space or a byte order mark, you can also do an
ob_start(); at the beginning of the page and ob_end_flush(); at the end to solve this issue.
but IMO check for the space or the B.O.M