php - variable from a form - lack of special characters - php

I'm aware there are many similar questions on this forum, but it's the 2nd day that I'm going through the answers and nothing seems to work.
It's my first week of PHP learning, so please try to answer in a simple way :) So:
I'm creating a conjugator and so far it's going well, but only if I don't use special characters. As Polish verbs are all about special characters, I'm stuck.
This code works (the conjugation is visible on the screen after pressing "submit"):
Page 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Conjugator</title>
</head>
<body>
<form action="new.php" accept-charset="UTF-8" method="post" >
Conjugate: <input type="text" name="verb"><br>
<input type="submit">
</form>
</body>
</html>
Page 2:
<?php
header('Content-Type: text/html; charset="UTF-8"');
$verb = $_POST['verb'];
$last2 = substr ($verb, -2);
$last3 = substr($verb, -3);
$last4 = substr($verb, -4);
$root2 = str_replace($last2, "", $verb);
$root3 = str_replace($last3, "", $verb);
$root4 = str_replace($last4, "", $verb);
$nic = array("nie", "nisz", "ni", "nimy", "nicie", "nia" );
$gnic = array("gnije", "gnijesz", "gnije", "gnijemy", "gnijecie", "gnija");
$ac = array("am", "asz", "a", "amy", "acie", "aja");
if ($last3 == "nic" && $last4 != "gnic") {
foreach ($nic as $one) {
echo "<li>$root3$one</li>";
}
}
elseif ($last4 == "gnic") {
foreach ($gnic as $one) {
echo "<li>$root4$one</li>";
}
}
elseif ($last2 == "ac") {
foreach ($ac as $one) {
echo "<li>$root2$one</li>";
}
}
?>
But if I write for example:
$nic = array("nię", "nisz", "ni", "nimy", "nicie", "nią" );
and then:
if ($last3 == "nić" && $last4 != "gnic")
no result shows up.
For checking, try with verbs like "pienić" or "lśnić" (they don't work) or write them without the special characters ("pienic", "lsnic") - the first code will work.
Help will be deeply appreciated!!

You probably can't use substr() with UTF-8. It thinks in terms of bytes, not characters. Take a look at mb_substr().

Related

What's wrong with this calculation?

Consider this markup:
<?php
$drill = 0;
$result = '';
$dynamicD = rand(5,15);
$num01 = $dynamicD-4;
$placeholder = $num01.'+4';
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["drill"])){
$humanErr = "Empty";
}
else {
$drill = $_POST["drill"];
if($drill !== $dynamicD) {
$result = "No";
}
else {
$result = "Yes";
}
};
};
?>
<!doctype html>
<html>
<body>
<p>Correct Answer: <?php echo $dynamicD ?></p>
<p>Does this work? <?php echo "$result";?></p>
<form method="post">
<fieldset>
<label for="drill">Can you solve it?</label>
<input type="text" name="drill" id="drill" maxlengh="2" placeholder="<?php echo $placeholder ?>" required="true" />
</fieldset>
<button type="submit" name="check">Check</button>
</form>
</body>
</html>
Basically it generates "random" number, insert it as a drill, and then let the user submit his answer. The problem is that the answer is always "NO"*.
I tried to separate the condition to this:
if($drill > $dynamicD) { $result = "bigger" }
elseif ($drill < $dynamicD) { $result = "smaller" }
and so on - but can't understand the logic of the $result (sometime bigger, sometime smaller, but i ALWAYS enter $dynamicD...).
What am i doing wrong here???
EDIT:
As the comments points, every time the page submit it generates new numbers. The first time the code execute is the only time that correct answer would be equal to the numbers that display. After the first submit there is a gap.
Note for future readers: The above code extracted and simplified from bigger and much complex system. Not something that anyone would want to just copy-paste.
The solution i choose was to store the dynamically created vars on a session and re-declare if the answer is correct.
Would love to hear about other ways (not client side).

Store random value, $_SESSION and $_POST issue

I'm making something similar a captha, the not working part is the IF, under if(isset($_POST['submit'])), that always returns false. I think.
Tried a lot ways with no luck...
Anyway, I have followed this solution https://stackoverflow.com/a/21504949/4167976 without success.
Here is my test php and html:
<?php
session_start();
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
$_SESSION["testcode"] = $code;
echo $_SESSION["testcode"]."<br>"; // echo here only for testing
if(isset($_POST['submit'])) {
$code1 = mb_substr($_POST['fullcode'], 0, 5);
$code2 = mb_substr($_POST['fullcode'], -6);
if ($code2 == $_SESSION["testcode"])
{echo "The code is correct!";}
else
{echo "Wrong code!";}
// unset($_SESSION['testcode']); // ???
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="fullcode">
<input type="Submit" name="submit" value="Submit!">
</form>
</body>
</html>
Please, tell me what and where I'm wrong... Thanks! :)
EDIT:
<?php
session_start();
if (!isset($_SESSION["testcode"])) {
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
$_SESSION["testcode"] = $code;
}
if(isset($_POST['submit'])) {
$code1 = mb_substr($_POST['fullcode'], 0, 5);
$code2 = mb_substr($_POST['fullcode'], -6);
if ($code2 === $_SESSION["testcode"])
{echo "The code is correct!<br>";}
else
{echo "Wrong code!<br>";}
unset($_SESSION['testcode']);
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
$_SESSION["testcode"] = $code;
}
?>
Finally, get a new code IF the condition is false!
<?php
session_start();
// first request.
// if not set session 'testcode' and set it, else do nothing.
// prevent session be covered.
if (!isset($_SESSION["testcode"])) {
reFreshCode();
}
if(isset($_POST['submit'])) {
$code1 = mb_substr($_POST['fullcode'], 0, 5);
$code2 = mb_substr($_POST['fullcode'], -6);
if ($code2 == $_SESSION["testcode"])
echo "The code is correct!";
else {
// get a new code IF the condition is false!
echo "Wrong code!";
echo “new code:”.reFreshCode();
}
}
function reFreshCode() {
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
return $_SESSION["testcode"] = $code;
}

How to validate php if form is filled

//So i have a php validation external and a html file. I'm trying to validate if //the input boxes are filled out correctly... so far i have one but I can't get it //to run and i tried testing it out doesn't work... do i need to download //something or is my code completely wrong. I just trying to check if its empty and if it has at least 3 characters
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cal5t</title>
</head>
<body>
<?php
$title= $_REQUEST["title"];
if ($title == "" or >3 ) {
echo "<p>5please!</p>";
?>
</body>
</html>
You are probably looking for something like:
if (($title == "") or (strlen($title) < 5))
{
echo "<p>5please!</p>";
}
if(!empty($title= $_POST['title']) && strlen($title) > 5){
echo "valid: $title";
} else {
echo "incorrect title: '$title'";
}
Also, its beter to use $_POST or $_GET over $_REQUEST.
I think you're looking for:
if(strlen($title) < 5){
echo '<p>The title you entered is not long enough.</p>";
}
You can make sure there is a value with the isset() function.
requird validation
$title = trim($_POST['title']); // it will remove stat and end spaces
if(strlen($title) <= 0)
{
echo "Title Field is required";
}

Search engine issue

I need your help. When user enter plural word or adjective to find singular word in my native language: czech. For example: when user enters motorový, it should return motor (now return motorov) without ový, same when i enter motorce (return motorc). It seems like 2letter and 3letter check doesn't work for me, 1letter check works. U can try my code on webiste . Thank you for you effort, time and good advices.
My Code:
<!DOCTYPE html>
<html lang="cs">
<meta charset="utf-8" />
<head>
<title>Vyhledavac</title>
</head>
<body>
<form method="get" action="index.php">
<input type="text" name="s_word" value="<?php $_GET['s_word'] ?>" /> <input type="submit" value="Hledat" />
</form>
<hr />
<?php
if(isset($_GET['s_word'])){
$s = $_GET['s_word'];
$s_word = $s;
$l_word = substr($s_word,-3);
if($l_word == "ovi" or $l_word == "ovy" or $_l_word == "ový" ){
$s_word = rtrim($s_word,$l_word);
}
$l_word = substr($s_word,-2);
if($l_word == "ce" or $l_word == "ku" or $l_word == "em"){
$s_word = rtrim($s_word,$l_word);
}
$l_word = substr($s_word,-1);
if($l_word == 'y' or $l_word == 'i' or $l_word == 'u' or $l_word == 'e' or $l_word == 'ů' or $l_word == 'ý'){
$s_word = rtrim($s_word,$l_word);
}
$query = "SELECT * FROM search_test WHERE title LIKE '%$s_word%' OR message LIKE '%$s_word%'";
echo "$query";
mysql_connect("localhost","user","passwd") or die('spatne pripojeni');
mysql_select_db("search") or die('nelze najit databazi');
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_general_ci'");
$query = mysql_query($query) or die('spatny dotaz');
$numrows = mysql_num_rows($query);
if($numrows > 0){
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$message = $row['message'];
$website = $row['website'];
echo "<h2><a href='$website'>$title</a></h2><br /><p>$message</p>";
}
}else{
echo "Žádné výsledky pro dotaz: ".$s_word."<br />";
}
}
?>
</body>
</html>
Shouldn't this:
$l_word = $s_word[strlen($s_word)-3];
Be something like:
$l_word = substr($s_word,-3);
The way you currently have it, it will only give you 1 character into $l_word and not the amount you think you're subtracting. Which means $l_word == "ovi" will never match.
For example:
<?php
$s_word = 'motorce';
$l_word = $s_word[strlen($s_word)-3];
echo $l_word;
Will return:
r
Live DEMO and what you actually want is:
<?php
$s_word = 'motorce';
$l_word = substr($s_word,-3);
echo $l_word;
Which returns:
rce
Live DEMO.
It gives you only one character:
$l_word = $s_word[strlen($s_word)-3];
Try with substr().
$l_word = substr($s_word, -3);
Not a fully working solution but the road i would have taken (assuming a UTF-8 encoded file):
$word = $_GET["s_word"];
$removelist = array("ový","ce");
foreach($removelist as $entry) {
if ((pos = mb_stripos($word,$entry)) !== FALSE) {
$word = mb_substr($word,$pos);
break;
}
}
Now $word should be trimmed and ready for searching, otherwise you should add more to the list.

problem with output of this code

i wrote this code.
in this code we user guess a number then program checked the number with the number that i gite to it and print appropriates message.
when i start program it shows welcome that is true but when i entered number in it always it shows little in output but it isn't true.
$val = '42';
$gues ;
if(!isset($gues))
$mess = "welcome<br>";
elseif($gues > $val)
$mess = "bigr<br>";
elseif($gues < $val)
$mess = "little<br>";
else
$mess = "win<br>";
$gues = #(int) $gues;
?>
<html>
<head><title>bazi riazi</title></head>
<body>
<h1>
<?php print $mess;
?>
</h1>
<form method="POST">
type you gues here:<input type="text" name='gues'>
</form>
</body>
</html>
How your var $gues get value from form? Did you use $_POST['gues'] first?
Script always print little because probably variable $gues was not initialized any value (default is zero, I suppose...).
This code should work (untested, though):
$val = '42';
$gues = int($_POST['gues']);
if (!isset($gues))
{
$mess = "welcome<br>";
}
elseif($gues > $val)
{
$mess = "bigr<br>";
}
elseif($gues < $val)
{
$mess = "little<br>";
}
else
{
$mess = "win<br>";
}

Categories