Issues with Cyrillic character set in PHP (Black Diamonds & question marks) - php

I am having issues with retrieving and processing data that is in Russian using the cyrillic character set.
I get the data in a text file from an FTP server with the code below and it displays every character with the black diamonds with question marks inside.
If I view it directly by accessing the FTP address with the browser, it displays correctly.
I have tried changing this line:
to
and
and while I get different results, none show the same as when accessing the file directly by the browser.
I'm not sure how to get the code to display the same as the browser when I view it directly
This would be an example of how I view the text file directly which displays correctly : ftp://username:password#ftp.mysite.com/test.txt
This is the code I am using which displays the black diamonds with question marks (other other incorrect characters, depending on the charset mentioned above).
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<?php
$username = "username";
$password = "password";
$server = "ftp://ftp.mysite.com"
$remoteFile = "test.txt";
$conn = ftp_connect($server);
if (#ftp_login($conn, $username, $password)) {
echo "";
}
else {
echo "";
}
ob_start();
ftp_get($conn, 'php://output', $remoteFile, FTP_ASCII);
$data = ob_get_contents();
ob_end_clean();
ftp_close($conn);
echo $data;
?>
</html>

I managed to resolve this by using mb_convert_encoding by adding the following line :
$new_data = mb_convert_encoding($data, "utf-8", "Windows-1251");
with the resulting code as :
<html>
<?php
$username = "username";
$password = "password";
$server = "ftp://ftp.mysite.com"
$remoteFile = "test.txt";
$conn = ftp_connect($server);
if (#ftp_login($conn, $username, $password)) {
echo "";
}
else {
echo "";
}
ob_start();
ftp_get($conn, 'php://output', $remoteFile, FTP_ASCII);
$data = ob_get_contents();
ob_end_clean();
ftp_close($conn);
$new_data = mb_convert_encoding($data, "utf-8", "Windows-1251");
echo $data;
?>
</html>
Hope this helps someone...

Related

php INSERT into sql_latin1_general_cp1_ci_as database charset

I have an sql database with sql_latin1_general_cp1_ci_as collation.
the database will contain about 3 language (English,Turkish,Arabic).
At the main page I set the charset to utf-8 as:
header('Content-Type: text/html; charset=UTF-8');
<meta charset="utf-8">
And I use this code in my php page:
$sql_server = "server";
$sql_user = "user";
$sql_password = "password";
$sql_database = "database";
$sql_conn_string = 'Driver={SQL Server};Server='.$sql_server.';Database='.$sql_database.';';
if ($sql_conn = odbc_connect($sql_conn_string, $sql_user, $sql_password)){
echo 'Connected';
$name = $_POST['cust_name'];
if (odbc_exec($sql_conn,"INSERT INTO inv01 (cust) VALUES (N'".$name."')")){
echo 'is inserted';
}
else{
echo 'is not inserted';
}
odbc_close($sql_conn);
}
else{
echo 'Connection Error';
}
When I enter an English words there is no problem
But when I use the other languages the words is inserted as unclear characters
I tried to use iconv but it's not working
$name = iconv("UTF_8","Windows-1252",$name);
//and
$name = iconv("UTF_8","UCS-2LE",$name);
What is the best collation in my case if sql_latin1_general_cp1_ci_as is not, and is there another solution without change the collation
I hope that my question is not repeated because I have read many questions here and I have not found a correct answer.
Thanks.
You can try with this:
Ensure that your 'cust' column is nvarchar().
Encode your html and php files in UTF-8 (I usually use Notepad++ for this step).
Convert input data.
Code (based on your example):
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta charset="utf-8">
<?php
...
$name = $_POST['cust_name'];
$name = iconv('UTF-8', 'UTF-16LE', $name);
$name = bin2hex($name);
$sql = "INSERT INTO inv01 (cust) VALUES (CONVERT(nvarchar(MAX), 0x".$value."))";
...
?>
</head>
<body></body>
</html>

My server returns blank page with 'null' in the corner

I need simple web service to get data from local database, but when I've moved files from test server to actual server I just receive blank page with 'null' in top left corner.
My php code is very simple:
<?php
// Include config
require_once 'config/db.php';
$sql = new db();
$conn = $sql->connect();
$task = isset($_GET['task']) ? mysql_real_escape_string($_GET['task']) : "";
if(!empty($task))
{
if($task === "totals")
{
$qur = mysql_query("working query - no problem here;");
$result =array();
while($r = mysql_fetch_array($qur))
{
extract($r);
$result[] = array("total_value" => $total_value, 'orders_date' => $orders_date, 'number_of_orders' => $number_of_orders);
}
$json = $result;
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json, JSON_PRETTY_PRINT);
?>
And here is db.php code:
<?php
class db
{
// Properties
private $dbhost = 'ip-address';
private $dbuser = 'xxx';
private $dbpass = 'yyy';
private $dbname = 'zzz';
// Connect
public function connect()
{
$conn = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
mysql_select_db($this->dbname, $conn);
}
}
?>
May be Json_encode not giving correct answer.
1) Also please make sure JSON_PRETTY_PRINT is only available for PHP versions >= 5.4. It's value is 128, so try replacing JSON_PRETTY_PRINT with 128.
just on error reporting at top of page to debug
2) Also to make sure once try to print $json before encoding it
3) As mentioned in comment just encode only when you are actually getting data
!empty($json){
header('Content-type: application/json');
echo json_encode($json, JSON_PRETTY_PRINT);
}

HTML document was not declared

This is about retriving the data in form of CSV from Mysql Table : -
Code , I tried :-
<?php
// mysql database connection details
$host = "localhost";
$username = "root";
$password = "hello";
$dbname = "mysql2csv";
// open connection to mysql database
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));
// fetch mysql table rows
$sql = "select * from tbl_books";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));
$fp = fopen('books.csv', 'w');
while($row = mysqli_fetch_assoc($result))
{
fputcsv($fp, $row);
}
fclose($fp);
//close the db connection
mysqli_close($connection);
?>
Errors Obtained...
04:12:27.093 The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.1 mysql2csv.php.
your help will be appreciated ...
Add those lines to your html header
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
Edit:
If you are using PHP file:
header('Content-Type: text/html; charset=utf-8');

PHP Session won't work after refresh

I've tried adding a PHP session, so they don't have to fill in the same password all the time. If I go to the page and fill in the code it will show the page with the correct session but when I refresh the page the session is gone.
Code of the session:
<head>
<script>
{ background-color:#87CEFA; }
</script>
</head>
<?php
error_reporting(0);
session_start();
$_SESSION["pass"] = $_POST["code"];
$pass = $_POST["code"];
$con=mysqli_connect("localhost","bb","$pass","bb");
if (mysqli_connect_errno($con))
{
echo "Kan geen verbinding maken, de ingevulde code is verkeerd of de server is offline!";
echo 'Hello '.$_SESSION["pass"].'!';
}
$result = mysqli_query($con,"SELECT * FROM ftp");
while($row = mysqli_fetch_array($result))
{
$myuser = $row['user'];
$mypass = $row['pass'];
$myhost = $row['host'];
$conn_id = ftp_connect($myhost) or die("Couldn't connect to $myhost");
if (#ftp_login($conn_id, $myuser, $mypass))
{
//Path to your *.txt file:
$file = $ftp_server['DOCUMENT_ROOT'] . "bbbb";
$contents = file($file);
$string = implode($contents);
echo $string;
}
}
mysqli_close($con);
?>
Thanks.
On every page load you are running the code $_SESSION["pass"] = $_POST["code"];. Then you try to echo it like echo 'Hello '.$_SESSION["pass"].'!';. What you are essentially doing is echoing $_POST["code"]. Only when you submit the form will the $_POST variable be set.
You're overwriting your session variable on each page load. You need to check if the form was submitted before setting your session variable:
session_start();
$_SESSION["pass"] = $_POST["code"];
needs to be
session_start();
if ('POST' === $_SERVER['REQUEST_METHOD']) {
$_SESSION["pass"] = $_POST["code"];
}
You should check that your server configured correctly. Check session storage and stored data
You should start session before any output (check where you start session and you don't have space after ?>). Overriding of super globals values is bad practise
I'm sorry to say this but you seriously need to read more on php sessions.
I took some liberties rewriting and commenting but if there's anything you don't understand, please ask
combo script
<?php
// protect against any output, leave no spaces or shenanigans before the session_start()
// even warnings and errors
// this is the first thing that has to happen BEFORE ANY OUTPUT
session_start();
// is this a good idea when you're in development
error_reporting(0);
// we don't know if $_POST['whateva'] actually exists
if (isset($_POST['code'])) {
// this may not be such a good idea...
$_SESSION['pass'] = $_POST['code'];
}
$pass = isset($_POST['code']) ? $_POST['code'] : '';
$error = '';
try {
$con = mysqli_connect('localhost','bb',$pass,'bb');// is this barebones MVC? just curious
if (mysqli_connect_errno($con)) throw new Exception('Kan geen verbinding maken, de ingevulde code is verkeerd of de server is offline! Hello '.$_SESSION['pass'].'!');
$result = mysqli_query($con,'SELECT * FROM ftp');
$ftpContent = array();
while ($row = mysqli_fetch_array($result)) {
$myuser = $row['user'];
$mypass = $row['pass'];
$myhost = $row['host'];
if (!$conn_id = ftp_connect($myhost)) throw new Exception('Couldn\'t connect to '.$myhost);
if (#ftp_login($conn_id,$myuser,$mypass)) {
//Path to your *.txt file:
$file = $ftp_server['DOCUMENT_ROOT'].'bbbb';// where does this $ftp_server come from????
$contents = file($file);
$string = implode($contents);
$ftpContent[$myuser] = $string;
}
}
mysqli_close($con);
} catch (Exception $e) {
$error = $e->getMessage();
}
// now output all your stuff here
?>
<!DOCTYPE html>
<html>
<head>
<style>body{background-color:#87cefa;}.error{color:#f00;}</style>
</head>
<body>
<?php if ($error) echo '<p class="error">There has been an error: '.$error.'</p>'; ?>
</body>
</html>
Don't copy paste this, look up what was done and evaluate what will happen, there's also a missing variable so you have to take care of that

Creating a new page for each submission - PHP errors

Here is the site.
I have the submit page, and a form action to a page that queries the submission info into my database. I'll include that code below. What I want to do, is have it create an individual page for each submission. However, I'm getting tons of errors when I try to upload. It uploads but it definitely doesn't create new page. the I have a template form which I'll show you, but first, here's the upload page:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$placeholders = array("{name}", "{filename}", "{username}");
$tpl = file_get_contents($tpl_path.$tpl_file);
$new_member_file = str_replace($placeholders, $data, $tpl);
$php_file_name = $username.".php";
$fp = fopen($submissions_path.$php_file_name, "w");
fwrite($fp, $new_submission_file);
fclose($fp);
?>
And here's the template file (submission.php)
<html>
<title>{name}</title>
<head>
</head>
<body>
<h1>{name}</h1>
Posted by: {username}
<br/>
<img src="{filename}"/>
</body>
</html>
It looks like you might have a path issue. When you use the path "/~lyons" you may not be pointing to the directory you want. Try making the changes below:
// For use in creating individual page
$tpl_file = "submission.php";
//$tpl_path = "/~lyons/templates/";
$tpl_path = "templates/";
And then please post the new error message(s), if any.
To help you in debugging, try turning error reporting and error display on.
// add after <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Opening the file is probably failing, for better error control try this:
$fp = #fopen($submissions_path.$php_file_name, "w");
if (!$fp) {
die('Failed to open file! Reason: ' . $php_errormsg);
}
I think your paths are incorrect, most likely the following 2 lines need to be changed to use a full path.
// change
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// to
$tpl_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/templates/";
$submissions_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/submissions";
When you go to open the file, it is trying to open /~lyons/templates/ which is a directory that does not exist, it is probably something like /home/lyons/public_html/templates/ or /home/something/public_html/~lyons/templates or /usr/local/apache2/htdocs/~lyons/templates etc. $_SERVER['DOCUMENT_ROOT'] should fill in the correct value, but in few cases you may need to manually set the correct path and prepend it to your $tpl_path and $submissions_path.
**save the "submission.php" in root folder**
`$tpl_file = "submission.php";`
**create "templates/`" folder in root folder**
`$tpl_path = "templates/";`

Categories