I need exact character match in PHP - php

I am trying to make a script, that interact with mysql database and allows to find someone by username. But the problem is that it is not comparing characters. Means in my databse, user name is "abcd", in lowercase. But when I go to
localhost/ABCD or
localhost/Abcd or
localhost/ABcd or any upper or lowercase, it shows me same result. I want different result with different cases. I don't know what to use. I searched a lot and found preg_match function but don't know how to use. The function I created for this match from database is,
function CheckPnP($var){
$db = new mysqli ('localhost', 'root', '', 'database');
if($var){
if($result = $db->query("SELECT * FROM `view` WHERE `username` = '$var'")){
if($result->num_rows){
$rows = $result->fetch_assoc();
$_GET['username'] = $rows['username'];
$_GET['view'] = $rows['page'];
include $_SERVER['DOCUMENT_ROOT'].'/core/view.php';
return true;
}
}
}
}
and my view.php page codes are
<?php
#$view = $_GET['view'];
#$username = $_GET['username'];
if($view == 'profile'){
echo 'This is profile page.';
}
else if ($view == 'page'){
echo 'This is page.';
}
else if ($view){
header('Location: /');
}
else if (empty($view)){
echo 'this is view page123. ';
}
echo '<br>'.$username;
?>
view.php page's codes are temporary. I will change them soon but right now I need to match characters of username from database and I need exact character match.
Please help me.

I actually just found out about this a few weeks ago:
SELECT * FROM `your_table` WHERE BINARY `your_column` = 'VaLue';
SELECT * FROM `your_table` WHERE BINARY `your_column` = 'value';
SELECT * FROM `your_table` WHERE BINARY `your_column` = 'vaLue';
This would return different results depending on your query.
I suggest you do the above instead of in PHP.
About your second question:
There are a ton of things you can do to match characters in PHP. strcmp (case sensitive), ===, ==, strcasecmp (case insenstive)

Related

Unique page for each row in database with PHP

I have been trying to create a unique page for each row in my database. My plan is to create a dictionary.php?word=title url, where I can display the description and title of that specific ID. My datbase is contains id, term_title and term_description.
I'm fresh outta the owen when it comes to PHP, but I've managed to atleast do this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Cannot connect to database." . mysqli_connect_error());
}
if (isset($_GET['id']))
{
$id = (int) $_GET['id'];
$sql = 'SELECT * FROM dbname WHERE id = $id LIMIT 1 ';
}
$sql = "SELECT * FROM terms";
$result = $conn->query($sql);
mysqli_close($conn);
?>
I'm really stuck and I dont know what the next step is, I've added the <a href='dictionary.php?=".$row["id"]."'> to each word I want to be linked, and this is properly displayed in the main index.php file (where all my words are listed with <li>. This is my code for this:
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<a href='dictionary.php?=".$row["id"]."'><li class='term'><h4 class='term-title'>" . $row["term_title"]. "</h4></li></a>";
} else {
echo "No words in database.";
}
?>
How do I create this unique page, only displaying title and description for that id? How do I add ?word= to the url?
Thanks for taking your time to help me.
Update from years later: Please, please use parameters when composing your SQL queries. See Tim Morton's comment.
You're on the right track, and ajhanna88's comment is right, too: you want to be sure to include the right key ("word" in this case) in the URL. Otherwise, you're sending a value without telling the page what that value's for.
I do see a couple other issues:
When you click on one of the links you created, you're sending along $_GET["word"] to dictionary.php. In your dictionary.php code, however, you're searching for your word by "id" instead of by "word". I'm guessing you expect users to search your dictionary for something like "celestial" and not "1598", so try this instead:
if (isset($_GET['word'])) {
$word = $_GET['word'];
$sql = 'SELECT * FROM dbname WHERE word = $word LIMIT 1 ';
}
BUT! Also be aware of a security problem: you were letting the user put whatever they want into your query. Take a look at the classic illustration of SQL injection. To fix that, change the second line above to this:
`$word = $conn->real_escape_string($_GET['word']);`
Another problem? You're looking for the word exactly. Instead, you'll probably want to make it case insensitive, so "Semaphore" still brings up "semaphore". There are plenty of ways to do that. The simplest way in my experience is just changing everything to lowercase before you compare them. So that $word assignment should now look like this:
`$word = $conn->real_escape_string(strtolower($_GET["word"]));`
And your query should look something like this:
`$sql = "SELECT * FROM dbname WHERE word = LOWER('$word') LIMIT 1 ";`
Next! Further down, you overwrite your $sql variable with SELECT * FROM terms, which totally undoes your work. It looks like you're trying to show all the words if the user doesn't provide a word to look up. If that's what you're trying to do, put that line in an else statement.
Your $result looks fine. Now you just have to use it. The first step there is to do just like you did when you tested the connection query (if(!$conn)...) and check to see that it came back with results.
Once you have those results (or that one result, since you have LIMIT 1 in your query), you'll want to display them. This process is exactly what you did when printing the links. It's just that this time, you'll expect to have only one result.
Here's a real basic page I came up with from your code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_errno){
die("Can't connect: ".$conn->connect_error);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dictionary!</title>
</head>
<body>
<?php
if(isset($_GET["word"])){
$word = $conn->real_escape_string(strtolower($_GET["word"]));
$sql = $conn->query("SELECT * FROM dictionary WHERE word=LOWER('".$word."') LIMIT 1");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
while($row=$sql->fetch_assoc()){
echo "<h2>".$row["word"]."</h2>";
echo "<p>".$row["definition"]."</p>";
}
}
} else {
$sql = $conn->query("SELECT word FROM dictionary");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
echo "<p>Here are all our words:</p><ul>";
while($row=$sql->fetch_assoc()){
echo "<li>".$row["word"]."</li>";
}
}
echo "</ul>";
}
?>
</body>
</html>
You should also take care to be consistent in your terminology. For this, my MySQL table had three columns: id, word, and definition. I dropped term since your URLs were using word. In my experience, it's best to keep the same terminology. It avoids confusion when your application gets more complicated.
Lastly, to answer your question about creating separate pages, you can see there that for a simple page like this, you may not need a separate page to display the definitions and the links -- just an if/else statement. If you want to expand what's in those if/else blocks, I'd suggest looking at PHP's include function.
You have a great start. Keep at it!

can not login to database using php

This is my login php code but I am unable to login.
My code works until echo "2", after that is not working anymore.
include 'inc.config.php';
if(isset($_POST["submit"]))
{
$user = mysql_real_escape_string($_POST['emailid']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$query=mysql_query("SELECT * FROM logsignup WHERE email='$user' AND password='$pass' ");
echo "1";
$numofrows = mysql_num_rows($query);
echo "2";
if($numofrows!=0)
{
echo "3";
while($row=mysql_fetch_assoc($query))
{
$dbusername= $row['emailid'];
$dbpassword= $row['password'];
}
if($user=$dbusername && $pass=$dbpassword)
{
echo "loggedin";
}
}
else
{
echo "invalid";
}
}
Here is inc.config.php file
$con = mysql_connect("localhost","root","");
$select=mysql_select_db("loginsignup");
Image of the database:
Update to MySQLi, as mysql_ is now deprecated. Read How do I migrate my site from mysql to mysqli? as a starter guide.
Stop using md5 as a password hashing function and instead use password_hash or a similar proven function.
if($user=$dbusername && $pass=$dbpassword) this is running the logic:
If value I get out of the database is the same as the value I put into the database.
Which is pretty pointless, it's a needlessly excessive check. It's better to count the correct number of rows returned, which will tell you exactly the same information.
You need to start using error logging, to help yourself solve your own errors, please read How to get useful error messages in PHP?
Also use MySQL EXPLAIN in (PHPMyAdmin) to help you understand wayward SQL queries.
Your password field in your screenshot looks far too short. md5 is typically 32 characters long, so what could be happening is that the SQL comparison is failing because you're comparing a long string with a shorter string. Double check.
Ensure you are using the correct Character encoding throughout your PHP and your MySQL, please read UTF-8 all the way through and convert all MySQL into utf8mb4_unicode_ci. Also get used to using PHP Multibyte string functions (may need installing).
If the above guides do not solve your problem you will at the very least have a clear path (with the error logs) to see what's going wrong and from that how to solve your issue.
<?php
`include 'inc.config.php';
if(isset($_POST["submit"]))
{
$user = mysql_real_escape_string($_POST['emailid']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT * FROM logsignup WHERE email='$user' AND password='$pass'";
$query=mysql_query($sql);
$numofrows = mysql_num_rows($query);
if($numofrows > 0)
{
$row=mysql_fetch_assoc($query)
$_SESSSION['EMAIL']= $row['emailid'];
$_SESSSION['USERNAME'] $row['username'];
if( $_SESSSION['EMAIL'] && $_SESSSION['EMAIL']) {
echo "valid";
}else{
echo "invalid";
}
}
}`
?>

preg_match does not work

This script checks if there is a special character or not, if there is, it calls for the preg match's "Invalid" function, else it says username available. What happens here is that every time I write a special character like ##%^& it still says username available instead of saying invalid, and that's not how it's supposed to work. I have checked the PHP code for errors and it seemed to be clean. I have tried and run to everything on forums and couldn't find a solution. Your contribution will be so much appreciated!
if(isset($_POST['login'])) {
$login = mysql_real_escape_string($_POST['login']);
if(!empty($login)) {
$login_query = mysql_query("SELECT COUNT(`id`) FROM `account` WHERE `login` = '$login'");
$login_result = mysql_result($login_query,0);
if($login_result == 0) {
echo 'yes';
} else {
echo 'no';
}
}
}
if ( preg_match("/^[a-zA-Z0-9[:space:]]+$/" , $login) ) {
echo 'noinput';
}
P.S I am not some kid who has leeched a code from the internet and is trying to get the others to do the work for him, I have written like 70% of this script and it works pretty well except the special characters thingy which I'm so stuck with. I hope you can help me. Thank you!
Not sure what your problem is. I just wrote the following program:
<?php
$input="good string";
$input2="bad#string";
if (preg_match("/^[a-zA-Z0-9[:space:]]+$/",$input2)) {
echo $input2." matches\n";
}
else {
echo $input2." does not match\n";
}
if (preg_match("/^[a-zA-Z0-9[:space:]]+$/",$input)) {
echo $input." matches\n";
}
else {
echo $input." does not match\n";
}
And it correctly shows that $input matches, but $input2 does not.
Are you sure of what is in your input? Could there be a carriage return?
update I think it is simply a case of you misinterpreting the return values of the php script. Let's look at the options:
1) valid username, is available:
query is empty, print string "yes". The preg_match finds a match and prints "noinput".
2) valid username, not available:
query returns something, print string "no". preg_match prints "noinput"
3) invalid username, is available:
query is empty, print string "yes". The preg_match prints nothing.
4) invalid username, not available:
query returns something, prints string "no". preg_match prints nothing.
If that is not how you interpret the return values, that's your problem...
second update
I have just looked at the source code of your link, and this is indeed the problem. You seem to test for several different responses:
if(data=='no') {
// do stuff
} else {
// something else
});
}
if(data=='noinput') {
// more stuff
});
}
if(data=='invalid') {
// yet more stuff
});
In other words, you check for strings 'yes', 'no', 'noinput'. But the way your code is structured and run, this is not the output you produce. For which I refer you to the four cases above.
solution
You need to move the check for invalid inputs to earlier in the code; and you need to return immediately after finding a user name that does not match. I think the following will work:
if(isset($_POST['login'])) {
$login = mysql_real_escape_string($_POST['login']);
if ( preg_match("/^[a-zA-Z0-9[:space:]]+$/" , $login) )
{
$login_query = mysql_query("SELECT COUNT(`id`) FROM `account` WHERE `login` = '$login'");
$login_result = mysql_result($login_query,0);
if($login_result == 0)
{
echo 'yes';
}
else
{
echo 'no';
}
}
else
{
echo('noinput');
}
}
It doesn't appear your regular expression accounts for special characters. You'll need to add in the characters you want to catch outside of numbers and alpha.
Look here for some advice: http://www.regular-expressions.info/characters.html
Try something like /^[a-zA-Z0-9\$[:space:]]+$/
The \$ accounts for the literal character.

SQL/PHP "WHERE" not returning correct value?

The code will display the returned values and and if it is greater than one it will return "Yes". But I am having trouble with the WHERE clause in $check. When I take it out the code works just fine but when I add it, the page returns incorrect values. Any ideas what's wrong?
<?php
$con = mysqli_connect("127.0.0.1","root","","lian");
$u= $_GET['username'];
$pw = $_GET['password'];
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
$login = mysqli_query($con,$check) or die(mysqli_error($con));
$num_rows = mysqli_num_rows($login);
echo "$num_rows \n";
if (mysqli_num_rows($login) == 1) {
$row = mysqli_fetch_assoc($login);
echo 'Yes';
exit;
}
else {
echo 'No';
exit;
}
Leaving aside the injection vulnerabilities, it may be because of special characters or whitespace. Try trim'ing your GET values.
$u = trim($_GET['username']);
$pwd = trim($_GET['password']);
Are you getting the number of results as 0? Also try echoing the statement in a development environment to check exactly what the statement is.
Try like this
$u= trim(mysqli_real_escape_string($_GET['username']));
$pw = trim(mysqli_real_escape_string($_GET['password']));
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
Also I hope you are ensuring unique combination of username and password.
Because suppose there are two entries in your users table
username="abc" password ="12345"
Then mysqli_num_rows() function will return two rows and the
if (mysqli_num_rows($login) == 1)
condition will return false meaning the user desn't exist.
The above comments are valid to improve the security of your code and protect vs sql injection.
Regarding your actual problem if the code executes correctly when you don't have the where clause in place but fails when you do there are a couple of possibilities:
The username or password are wrong - where wrong can mean they have extra whitespace, case insensitivities or that the column names are incorrect(case sensitive database?)
The string you are passing to the server is not displaying correctly.
Check both options by doing an echo of $u, $pw and $check right after you form your SQL string. If it's still not clear then copy whatever is echoed for $check and past it directly into the parser(management studio I guess?) and see what it returns.
Good Luck.

Comparison page content

I need script that sends me email when something changes on page.
This is my code but it's not working correct. How can i do this to work properly?
$new_page = file_get_contents('http://www.google.com');
$new_page_in = mysql_real_escape_string($new_page);
mysql_query("UPDATE new SET text='$new_page_in' WHERE id='1'") or die (mysql_error());
$sql1 = mysql_query("SELECT text FROM new WHERE id='1'") or die (mysql_error());
list($new_out) = mysql_fetch_row($sql1);
$sql2 = mysql_query("SELECT text FROM old WHERE id='1'") or die (mysql_error());
list($old_out) = mysql_fetch_row($sql2);
if($new_out != $old_out)
{
$new_page = file_get_contents('http://www.google.com');
$new_page_in = mysql_real_escape_string($new_page);
mysql_query("UPDATE old SET text='$new_page_in' WHERE id='1'") or die (mysql_error());
echo "Text is diferent.";
//send email
}
else
{
echo "Text isn't diferent";
}
Try using the comparison
strcmp($new_out, $old_out) == 0
to test if they are the same.
Also I would suggest just storing a hash of the page content in the database instead of the entire string. So store
hash('md5', $new_page)
in the database instead of $new_page and compare hashes if you want to see if anything has changed. Store the content as well if you need to, but don't compare on the contents.
I will suggest while storing the htmlcontent add htmlentities and also remove all the whitespaces before before storing....
You can refer to this link for the regex to do the same....
Also you can make use of the string algorithms like levenshtein or similar-text to check the matching percentage and keep some threshold maybe 95% for almost same

Categories