I'm building a contact form with PHP that sends the content via mail. I just have a couple of questions that I don't find a solution for on my own.
The first must be simple, but I can't get it why I don't get any line breaks in this code:
$contactForm = $form_name . "\n";
$contactForm .= $form_email . "\n";
$contactForm .= $form_message . "\n";
And my second question is how I can have swedish letters like åäö instead of these strange letters: öäå
I'm using PHPMailer and I have set it to swedish with this line of code,
$mail->setLanguage('se', '/optional/path/to/language/directory/');
EDIT!! I missed to change the path for the language folder in the line above! Have fixed that now!
$mail->setLanguage('se', '/language/');
but it seems like this isn't the problem. I guess it must be some problem with UTF-8 or is it the PHP-code that sanitize the variables?
I'm using this to sanitize the input values:
// Security - call function
$form_name = check_input($_POST['name']);
$form_email = check_input($_POST['email']);
$form_message = check_input($_POST['message']);
// Function to check input
function check_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = strip_tags($data);
return $data;
}
Preciate some help!
Related
In my PHP script I try to send utf8 characters to the google translate website for them to send me a translation of the text, but this doesn't work for UTF8 characters such as chinese, arabic and russian and I can't figure out why. If I try to translate 'как дела' to english I could use this link: https://translate.googleapis.com/translate_a/single?client=gtx&sl=ru&tl=en&dt=t&q=как дела
And it would return this: [[["how are you","как дела",,,1]],,"ru"]
A fine translation, exactly what I wanted, but if I try to recreate it in PHP I do this (I used bytes in the beginning because my future script will use bytes as starting point):
<?php
$bytes = array(1082,1072,1082,32,1076,1077,1083,1072); // bytes of: как дела
$str = "";
for($i = 0; $i < count($bytes); ++$i) {
$str .= json_decode('"\u' . '0' . strtoupper(dechex($bytes[$i])) . '"'); // returns string: как дела
}
$from = 'ru';
$to = 'en';
$url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=' . $from . '&tl=' . $to . '&dt=t&q=' . $str;
$call = fopen($url,"r");
$contents = fread($call,2048);
print $contents;
?>
And it outputs: [[["RєR RєRґRμR ° \"° F","какдела",,,0]],,"ru"]
The output doesn't make sense, it appears that my PHP script send the string 'какдела' to translate to english for me. I read something about making UTF-8 characters readable for google in a URI (or url). It says I should transfer my bytes to UTF-8 code units and put them in my url. I didn't yet figure out how to transfer bytes to UTF-8 code units, but I first wanted to try if it worked. I started by converting my text 'как дела' to code units (with percents for URL) to test it myself. This resulted in the following link: https://translate.googleapis.com/translate_a/single?client=gtx&sl=ru&tl=en&dt=t&q=%D0%BA%D0%B0%D0%BA+%D0%B4%D0%B5%D0%BB%D0%B0
And when tested in browser it returns: [[["how are you","как дела",,,1]],,"ru"]
Again a fine translation, it appears it works so I tried to implement it in my script with the following code:
<?php
$from = 'ru';
$to = 'en';
$text = "%D0%BA%D0%B0%D0%BA+%D0%B4%D0%B5%D0%BB%D0%B0"; // code units of: как дела
$url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=' . $from . '&tl=' . $to . '&dt=t&q=' . $text;
$call = fopen($url,"r");
$contents = fread($call,2048);
print $contents;
?>
This script outputs: [[["RєR Rє RґRμR ° \"° F","как дела",,,0]],,"ru"]
Again my script doesn't output what I want and what I get when I test these URL's in my own browser. I can't figure what I'm doing wrong and why google responds with a mess up of characters if I use the link in my PHP file.
Does someone know how to get the output I want? Thanks in advance!
Updated code to set strings in UTF-8, (not working)
I added a lot of settings at the top of the PHP file to make sure everything is in UTF8 format. Also I added a mb_convert_encoding halfway but the output keeps being wrong. The fopen function doesn't send the right UTF-8 string to google.
Output I get:
URL: https://translate.googleapis.com/translate_a/single?client=gtx&sl=ru&tl=en&dt=t&q=%D0%BA%D0%B0%D0%BA%20%D0%B4%D0%B5%D0%BB%D0%B0
Encoding: ASCII
File contents: [[["RєR Rє RґRμR ° \"° F","как дела",,,0]],,"ru"]
Code I use:
<?php
header('Content-Type: text/html; charset=utf-8');
$TYPO3_CONF_VARS['BE']['forceCharset'] = 'utf-8';
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_http_input('UTF-8');
mb_language('uni');
mb_regex_encoding('UTF-8');
ob_start('mb_output_handler');
$from = 'ru';
$to = 'en';
$text = rawurlencode('как дела');
$url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=' . $from . '&tl=' . $to . '&dt=t&q=' . $text;
$url = mb_convert_encoding($url, "UTF-8", "ASCII");
$call = fopen($url,"r");
$contents = fread($call,2048);
print 'URL: ' . $url . '<br>';
print 'Encoding: ' . mb_detect_encoding($url) . '<br>';;
print 'File contents: ' . $contents;
?>
Solved! I got the hint from another not from these forums to look at this stackoverflow post about setting a user agent. After some more research I found that this answer was the solution to my problem. Now everything works fine!
I'm programming a bot on telegram and I didn't make the special keyboard via reply_mark up someone can help me?
My code is this:
file_get_contents($website."/sendmessage?chat_id=".$myID."&text=keyTest&reply_markup={"keyboard":[["test"]]}");
If I copy&paste your parameters to my bot and execute the command it works. But that's because I use the Text you provide as parts of my url.
api.telegram.org/bot[key]/sendMessage?chat_id=[id]&text=keyTest&reply_markup={"keyboard":[["test"]]}
What you are doing is writing a script that executes the command. As far as I can tell you're using the dot . to concatenate strings. Another thing you're doing is trying to write the JSON for the reply_markup directly into the url.
What your problem probably is, is one of the following: You're not escaping the " sign or not concatenating variables correctly.
So if keyboard and test are variables you need to concatenate them correctly using the dot:
file_get_contents($website."/sendmessage?chat_id=".$myID."&text=keyTest&reply_markup={".$keyboard.":[[".$test."]]}");
but if you just want to write your test keyboard into the string you need to escape the " so your string does not end:
file_get_contents($website."/sendmessage?chat_id=".$myID."&text=keyTest&reply_markup={\"keyboard\":[[\"test\"]]}");
Note: I have no idea if this is the correct way to escape " in php. This is just to explain your error. If you need to escape double quotes in php any other way, do it how it is supposed to be.
OK, I think that I have the solution for you!
So, this is the code:
$key = "{\"keyboard\":[ [\"OPTION1\"], [\"OPTION2\"], [\"OPTION3\"] ]}";
$url = $GLOBALS[API_URL]."/sendmessage?chat_id=$id&text=Choose%20your%20action&reply_markup=".urlencode($key);
file_get_contents($url);
Variable $GLOBALS[API_URL] = https://api.telegram.org/bot123456789:AAf6g4fr4rt5y67hadsffaerafasfasf
So replace my global var with your direct url or whatever :D
Other function that should be interesting for you is this:
function close_keyboard($id, $message)
{
//$text = "Keyboard_closed!";
$message = str_replace(" ", "%20", $message);
$key = "{\"hide_keyboard\":true}";
$url = $GLOBALS[API_URL]."/sendmessage?chat_id=$id&text=$messagge&reply_markup=".urlencode($key);
file_get_contents($url);
}
This function close your custom keyboard, and other my personal function is this:
function build_keyboard($elements, $message, $chat_id)
{
//Get length of array
$len = count($elements);
//Build custom keyboard
$keyboard = "{\"keyboard\":[ [\"";
for($i = 0; $i < $len; ++$i)
{
if($i < $len-1)
$keyboard .= $elements[$i]."\"],[\"";
else
$keyboard .= $elements[$i]."\"] ]}";
}
$url = $GLOBALS[API_URL]."/sendmessage?chat_id=$chat_id&text=".urlencode($message)."&reply_markup=".urlencode($keyboard);
file_get_contents($url);
}
Prototype of this function is build_keyboard(array(), String, String)
Example:
$messagge = "Wrong choise";
$keyboard = array("OPT1", "OPT2", "OPT3");
build_keyboard($keyboard, $message, $chat_id);
Remember that $message is always needed or reply_doesntt work!
Hope this will be usefull! You're welcome!
I'm learning about making my site more secure and am using mysqli's escape function to sanitize input going into SQL queries and am using htmlspecialchars() on input coming from the database (or get/post requests) echoing out onto the page.
But, any text coming from the database to display to the user looks bad because certain characters are escaped with slashes and it shows <br /> or \r\n instead of doing a line break. I can strip the slashes, of course, but shouldn't the mysqli string escape function change the escaped characters back once it is put into the database?
Am I not supposed to use htmlspecialchars to sanitize output being displayed to the user? Or should this not be happening (in which case there must be something weird going on to the data going in)?
I still want line breaks so I'm having to do a string replace. I made the function below as a replacement for just htmlspecialchars(). But I'm not seeing anything about having to do this online anywhere so I'm afraid maybe I'm doing something wrong. :-/
function display($data) {
$new = str_replace('\r\n',"<br />",$data);
$new = str_replace('\n',"<br />",$new);
$new = str_replace('\r',"<br />",$new);
$new = stripslashes($new);
$newer = htmlspecialchars($new);
$search = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '\r\n', '<br />');
$replace = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '<br />', '<br />');
$newest = str_replace($search, $replace, $newer);
return $newest;
}
Here's what I'm using to sanitize the input going into the database:
function escape($data) {
global $conn;
connect();
$data = stripslashes($data);
$data = $conn->real_escape_string($data);
$conn->close();
$data = str_replace(chr(0), '', $data);
return $data;
}
function sanitize($data) {
$data = trim($data);
$data = strip_tags($data);
$data = escape($data);
$data = htmlspecialchars($data);
return $data;
}
I use functions (check(removeTags($data))) to save the text in mysql database:
function check($data){
if (get_magic_quotes_gpc()) {
$data = stripslashes($data);
}
$data =addcslashes( mysql_real_escape_string($data) , "%_" );
return $data;
}
function removeTags($data){
$data=trim($data);
$data=strip_tags($data);
return $data;
}
I use this function to display text above was saved to the user.
function output($data){
return htmlspecialchars($data,ENT_QUOTES,"UTF-8");
}
But Unwanted character are added to the text.replace newline('<br/>') with "\r\n".
I use stripslashes but it didn't worked ( replace '\r\n' with 'nr' ).
I use str_replace("\r\n", "<br />",$data) but it didn't worked too.
how can i remove '\r\n' ?
edit
see this outputting \r\n after text is decoded - PHP .
but user input is not encoded with that function ( like encode ),user input language is persian (Arabic).
For remove all new line characters from string use:
function check($data) {
if (get_magic_quotes_gpc()) {
$data = stripslashes($data);
}
// this will remove all \n\r from output what you asked in question
$data = str_replace(array("\r", "\n"), '', $data);
// in case you want new line in place of \n\r use line below
// $data = nl2br($data);
$data = addcslashes(mysql_real_escape_string($data) , "%_");
return $data;
}
...
Make sure you use this on clean user input. Before addslashes or other escaping methods. After escaping EOL characters became "\\r\\n" and str_replace will not work on them.
Anything wrong with this code? I want it to print the name and address - each on a separate line, but it all comes up in one line.
Here's the code
<?php
$myname = $_POST['myname'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$address3 = $_POST['address3'];
$town = $_POST['town'];
$county = $_POST['county'];
$content = '';
$content .="My name = " .$myname ."\r\n";
$content .="Address1 = " .$address1 ."\n";
$content .="Address2 = " .$address2 ."\n";
$content .="Address3 = " .$address3 ."\n";
$content .="town = " .$town ."\n";
$content .="county = " .$county ."\n";
echo $content;
?>
It looks like the '\n' character is not working.
In your source code this will show on a next line, but if you want to go to another line in HTML you will have to append <br />.
So:
$content .="My name = " .$myname ."<br />\r\n";
I left the \r\n here because it will go to the next line in your source code aswell, which might look nicer if you have to view the source.
The \n character properly works just fine. The problem is, it's not what you expect.
If you see this in a browser, you won't see line breaks, because line breaks are ignored in the source code. The HTML parser only reads <br> as line breaks.
If you try to go to your website and view the source code, you'll find that the line breaks are in there.