PHP/MySQL An issue with echoing comments [TODO: DELETE] [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I got this comment viewer script. And I'm requesting help to find an issue why it's not working. PHP doesn't show any errors. I don't know what wrong with it.
My MySQL databases looks like this:
comments { authorid, content, _when, }
users { id, firstname, name, nickname, password }.
echo "<div id='comments'>";
$sql_comments = "SELECT * FROM table.comments";
$comments = $conn->query($sql_comments);
$sql_2 = "SELECT id, firstname, name, nickname, password, type FROM users.users";
$conn2_2 = $conn->query($sql_2);
$row6 = $conn2_2 -> fetch_array();
while( $row5 = $comments -> fetch_array() && $id_users = $row6["id"] &&
$firstname_users = $row6["firstname"] && $name_users = $row6["name"]) {
if( $id_users == $row5["authorid"] ) {
echo "<div class=\"infoComments\">";
echo "<div class=\"commentsImg\"><img src=\"imgs/randomProfileImgs/$ranNum.png\" id=\"profileImg\" /></div>";
echo "<div class=\"commentsInfo\">" . $firstname_users . "<br />" . $name_users . "</div>";
echo "<div class=\"commantsContent\">" . $row5["content"] . "</div>";
echo "</div>";
};
};
echo "</div>";
Any ideas?

You state that your users table contains the following columns.
id, firstname, name, nickname, and password
You then proceed to put together a query that attempts to pull the type column out.
// bad sql query, tries to get 'type' but that column doesnt exist
$sql_2 = "SELECT id, firstname, name, nickname, password, type FROM users.users";
// query() will return false because theres a problem
$conn2_2 = $conn->query($sql_2);
// this is now a boolean because of the above issue
$row6 = $conn2_2 -> fetch_array();
What you should put after the query() call is this
if (!$conn2_2) {
printf("Errormessage: %s\n", $conn->error);
exit();
}
To avoid this type of thing in the future, do yourself a huge favor and make sure php can tell you when theres a problem by putting this at the start of your scripts.
error_reporting(-1);
ini_set('display_errors', 'On');
Or, you may want to make sure that the user you're connecting to mysql with has access to the databases table, AND users

Related

Exploiting MD5/Salt Vulnerability in this PHP form? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've been practicing security-related subjects and this challenge has befuddled me. Note: I can't access any PHP source code, nor can I edit it. I'm only able to view it.
The following is given:
I have two inputs, "user" and "pass"
After 30 times the form is sent, the salt, the hashes and the final solution change. So bruteforce isn't an option (sadly!)
#The bottom of the page (not shown in the code for some reason), it echos that it found 9 users (calling the getnumberofusers() function)
I've managed to extract this:
username = root
hashed password = 551e18b35e17017742a8ce4ed27f626e
Token (possibly salt?) = 0St31ez14wOT6jTh
What I've attempted thus far with unsuccessful results:
Using SQL injection, select a known MD5 collision as password and send its counterpart as "pass", however the salt is bothering this process. Clearly I couldn't bruteforce this because after 30 attempts the salt would change.
I tried finding the entire list of users but it doesn't print the output anywhere (only errors)
This is the code we receive:
<?php
//by Mawekl
//Objective: login as root.
//Objective is NOT:
// - Blind SQLI
// - Bruteforce password/salt/id
#WARNING
#ANTI-BLIND
#for every 30 queries
#all hashes, salt
#and final solution
#will be reset.
function getnumberofusers()
{
$q = "SELECT 1 FROM `sqlinjection1`";
$r = mysql_query($q);
return 'Number of users: ' . mysql_num_rows($r);
}
function getinfo($user)
{
$q = "SELECT `id`, `password` FROM `sqlinjection1` WHERE `username`='$user'";
$r = mysql_query($q);
if(!$r)
return mysql_error();
$r = mysql_fetch_array($r);
if(!$r)
return "Username doesn't exists.";
return $r;
}
function getfullinfo($id)
{
$q = "SELECT * FROM `sqlinjection1` WHERE `id`=$id";
$r = mysql_query($q);
if(!$r)
return mysql_error();
$r = mysql_fetch_array($r);
if(!$r)
return "What the hell?!";
return $r;
}
function confirmpassword($pass, $passcorrect, $salt)
{
$pass = md5(md5(md5($pass)).$salt);
return $pass===$passcorrect;
}
function challenge($user, $pass)
{
$info = getinfo($user);
if(!is_array($info))
return $info;
$confirm = confirmpassword($pass, $info['password'], $_ENV['ST_SALT']);
if(!$confirm)
return 'Wrong password!';
$info = getfullinfo($info['id']);
if(!is_array($info))
return $info;
$returnmessage = "Welcome " . $info['username'] . "!" . PHP_EOL .
$info['welcomemessage'] . PHP_EOL;
return $returnmessage;
}
?>
Any help is appreciated, and if you have any questions I'd love to clarify my question!
now we can select the welcome message/anything else using sql
$user="1' or exp(~(select * from (select welcomemessage from sqlinjection1 where username='user1')a)) or '1'='1"
but when we found a Secret token (that i wrote up there ^) hidden in the data base and tried using it this way:
The idea: select the hashed version as password using SQL injection so the hashes match.
Here's the code:
<?php
$salt = "v5IftFb0Tx1Jhp4b";
$hashed = "";
$p = "hello";
$hashed = md5(md5(md5($p)).$salt);
echo "The Query: " . "' AND 1 = 0 UNION SELECT `id`, '$hashed' AS `password` FROM sqlinjection1 WHERE `username` = 'root';#";
?>
It echoes the query which we put in the "username" field. In the "password" field we enter "hello".
However it's not working...
but it did not work, anyone has any idea what else can we do? How can we find out what / modify the $_ENV["ST_SALT"]? as appearently its not the secret token that we found

Show summary information of the added employee using PHP and MySQL [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm beginner in PHP MySQL, I would like to ask if this possible:
I have ADD NEW EMPLOYEE page after I submit, I want to have simple summary information of the added employee like
Something like opening a new window page:
Agent Code: The Agent code of the employee newly added
Name: Name of the Employee
Type: Type of the employee
Here is PHP Code in my ADD NEW EMPLOYEE page:
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$res=mysql_query("SELECT * FROM accounts WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
if(isset($_POST['btn-signup']))
{
$agentCode = mysql_real_escape_string($_POST['agentCode']);
$pass = md5(mysql_real_escape_string($_POST['pass']));
$aFName = mysql_real_escape_string($_POST['aFName']);
$aLName = mysql_real_escape_string($_POST['aLName']);
$aMName = mysql_real_escape_string($_POST['aMName']);
$aSuffixName = mysql_real_escape_string($_POST['aSuffixName']);
$aContact = mysql_real_escape_string($_POST['aContact']);
$aAddress = mysql_real_escape_string($_POST['aAddress']);
$aGender = mysql_real_escape_string($_POST['aGender']);
$utype = mysql_real_escape_string($_POST['utype']);
$loctype = mysql_real_escape_string($_POST['loctype']);
$ipadd = mysql_real_escape_string($_POST['ipadd']);
if(mysql_query("INSERT INTO accounts(agentCode, password, agentFname, agentMname, agentLname, aSuffixName, agentContact, agentAddress, agentGender, user_type, location_type, ip_add)
VALUES('$agentCode', '$pass', '$aFName', '$aMName', '$aLName', '$aSuffixName', '$aContact', '$aAddress', '$aGender', '$utype', '$loctype', '$ipadd' )"))
{
?>
<script>alert('Successfully added!');</script>
<?php
} else {
?>
<script>alert('Agent Code is not available!');</script>
<?php
}
}
?>
You can do it in 2 ways.
1) You will have all posted for db from the form which you used to insert the values to you database. You can use same values to display there.
2) Capture the last insert id, on successfully inserted the data, fetch the data based on that id and display in view.
mysql_* to mysqli_*
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qry = "INSERT INTO accounts(agentCode, password, agentFname, agentMname, agentLname, aSuffixName, agentContact, agentAddress, agentGender, user_type, location_type, ip_add)
VALUES('$agentCode', '$pass', '$aFName', '$aMName', '$aLName', '$aSuffixName', '$aContact', '$aAddress', '$aGender', '$utype', '$loctype', '$ipadd' )";
mysqli_query($con, $qry);
// Print auto-generated id
$last_inserted_id = mysqli_insert_id($con);
echo "Last Inserted ID: " . $last_inserted_id;
// Now you can perform a select query by using this ID and show
// Agent Code: The Agent code of the employee newly added
// Name: Name of the Employee
// Type: Type of the employee
mysqli_close($con);

If email exists return error else add php mysql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to write a script that does the following. Takes a users email and added's it to a database however if the users email already exists it rejects.
<?
require_once('includes/db.php');
$email = mysqli_real_escape_string($link, $_POST['email']);
$dupesql = "SELECT * FROM emails where (email = '$email')";
$duperaw = mysqli_query($link, $dupesql);
if(int mysql_num_rows($duperaw) > 0){
echo 'Error already in there';
}
else {
$sql = "INSERT INTO emails(email)
VALUES('$email')";
$result = mysqli_query($link, $sql);
header('Location: poll/poll.php');
}
// close mysql
mysqli_close($link);
?>
Why not let mysql take care of it? When you already want email to be unique, then define an unique index for email :
CREATE UNIQUE INDEX email_index ON emails (email)
now you only have to check if any rows has been affected after insert :
if (mysqli_affected_rows()>0) {
//success, email inserted
} else {
// rejected
}
By that you'll spare a call to the database and make the code more simplistic, imho.
try this
$mysqli->real_query('INSERT INTO '.$table.' ('.$cols.') VALUES ('.$vals.')');
Change your code as follow:
$dupesql = "SELECT * FROM emails where email = '$email'";
$duperaw = mysqli_query($link, $dupesql);
if(mysql_num_rows($duperaw)==1){
echo 'Error already in there';
}
You are mixing mysqli_ with mysql_ which is the main problem here.
Use mysqli_num_rows instead of mysql_num_rows
You should not mix mysqli() and mysql().
And remove int error casting.
//...
if(mysqli_num_rows($duperaw) > 0){
echo 'Error already in there';
}
//...

password and username validation in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
i have this information on my database...
Username - kam, mav, shin
Password - kam, mav, shin
this is my code...
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl2=mysql_query("SELECT * FROM tablename WHERE `username` =
'".mysql_real_escape_string($_POST['username'])."' and `password` =
'".mysql_real_escape_string($_POST['password'])."'");
while($row=mysql_fetch_array($tbl2))
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}
if (($row['username']!=$_POST['username'])&&($row['password']!=$_POST['password']))
{
header("location: /login.php?codeError=1");
die;
}
?>
the problem is, if i enter the username "mav" and the password is "kam", it still go through the next page. What should i do?
You should just check if the query returns any rows with mysql_num_rows():
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl2 = mysql_query("SELECT `username`, `password` FROM `tablename` WHERE
`username` = '".mysql_real_escape_string($_POST['username'])."' AND
`password` = '".mysql_real_escape_string($_POST['password'])."'
");
$rows = mysql_num_rows($tbl2);
if($rows){
// user and password exists in db
} else {
// does not exist
header("location: /login.php?codeError=1");
die;
}
Like I told you in previous question, try to move from mysql_* functions.
Just a suggestion but why not try it this way:
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}else{
header("location: /login.php?codeError=1");
die;
}
I don't understand why you need two if statements here, it's only boolean and the result will either be true or false.
Hope this helps :)!
You are checking for validation already in your query. If the user entered username and password correctly and only then, the query returns a row, containing that data.
So you only have to count the rows returned bye your Query. If it is below 1, then the user is not authenticated
Try
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}
else
{
header("location: /login.php?codeError=1");
die();
}
Anyway, a nice way to address this kind of issues is temporary printing on screen the variables (as a debug).
echo $row['username']." ".$_POST['username']." ".$row['password']." ".$_POST['password']
see if the variables are actually there of if there are issues with your DB query or with the form that posts the data.

if statement not working with database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Why isn't this code working?
$welcome = mysql_query("SELECT welcome FROM users WHERE id = '" . $_SESSION['user']['id'] . "'");
if($welcome == '0')
{
echo 'register is 0';
}
else
{
echo 'register is 1';
}
$_SESSION['user']['id'] returns as 1, by the way.
MySQL returns a resource on success, false on error, not a value from the query. Try this:
$welcome = mysql_query("SELECT welcome FROM users WHERE id = '" . $_SESSION['user']['id'] . "'");
$row = mysql_fetch_assoc($welcome);
if($row['welcome']== '0')
{
echo 'register is 0';
}
else
{
echo 'register is 1';
}
You shouldn't build your query like that as you'll not be protected from a SQL Injection Attack.
$query = sprintf("SELECT welcome FROM users WHERE id = %d", $_SESSION['user']['id']);
// Perform Query
$result = mysql_query($query);
Once that has finished you then need to fetch from the result, you cannot just query it.
if(!$result)
echo "Error"; // Deal with it
$row = mysql_fetch_assoc($result);
echo $row['welcome'];
mysql_free_result($result);
According to MySQL documentation, the resource is returned if the select statement is successful, or 'false' if the statement fails.
Although there's a better, more secure way to achieve what you are trying to accomplish, your statement can be revised simply to :
if($welcome === false)
{
echo 'register is 0';
}
else
{
echo 'register is 1';
}
That will work, but as I said earlier, the whole code needs to be updated to a more secure version.

Categories