This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I have been making a search engine for my website and just got it completed i am using an ajax request to search the database and wanted to know how i can make it safe from any injections?
Search.ajax.php
<?php
$db = new mysqli('localhost', 'root', 'root', 'social');
$search = $_POST['search'];
$query = mysqli_query($db, 'SELECT * FROM users WHERE username LIKE "'.$search.'"');
if (mysqli_num_rows($query) < 1) {
echo "<b>No results found for <i>".$search."</i></b>";
}else{
while ($r = mysqli_fetch_assoc($query)) {
$user = $r['username'];
echo '<div>Go to <a href="profile.php?user='.$user.'">'.$user.'</p></div>';
}
}
?>
I am searching the database for users that have the username of what they put in the search box. i need help making it so no one can search alert(test); if they search this it will show up an alert box here is an example of it.here is a photo of when someone puts in script tags
Firstly, you will need https to make sure you protect users from hackers by using firewalls and other required security tools.
Secondly, you need to use htaccess to change extensions, say show user .html instead of .php
Thirdly, encrypted values instead of plain text.
There are a lot more issues to take care of but its too complex and broad.
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
This query was working on mij older login script, But now that i have this new login script, my code had to change a litlle, Wich i cant seem to pull off. Im think the troubles are in the end where the if user is online is checked...
This is my code
<?php
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
function pay_credits() {
mysqli_query("UPDATE `tbl_users` SET `credits`=`credits`-'1' WHERE `watching`='1' AND `credits`>'0' AND userID=:uid");
}
?>
<?php
pay_credits();
?>
The top script is working fine, But the function pay_credits doesnt work, Ive tried changing mysql to mysqli as i hear alot over that it has deprecated and stuff, But still no result, Ive also been reading about pdo but i have no knowledge of this. Any help is welcome, I also like to learn so maybe you can explain what you`ve done a litlle. Thnx :)
First: if you read mysqli_query manual, you'll see that mysqli_query takes two arguments. First is link and second is a query string.
Do you see a link in your pay_credits function? Nope.
Second: I noticed that you use PDO::FETCH_ASSOC and then suddenly switch to mysqli.
PDO and mysqli are totally different APIs and you should choose which one you use.
You use pay_credits() without settings, your function mysqli_query need a params for db connection.
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
Okay so I am running into an issue with my code since no matter what I change it to, it stays on the index page?
Here is my code
<?php
// Maintenance mode
$system = (mysql_query("SELECT * FROM system"));
if($system['maintenance'] == 1)
{
header('Location: /maintenance');
exit;
}
?>
I want it so if maintenance = 1 it would send you to the maintenance.php page but it doesn't can anyone help me with this? I tried,
if(!$system['maintenance'] == 1)
which works but I have this code in my maintenance.php page
<?php
$system = (mysql_query("SELECT * FROM `system`"));
if(!$system['maintenance'] == 0)
{
header('Location: /index');
exit;
}
?>
What I thought would send me back to the index page once that in the database it shows it is a 0 or that's what I want it to do. Can anyone please explain why my code isn't working?
I am a beginner php, mysql, and C++ coder / programmer so please try to explain it the easiest way possible.
I fixed it thanks to #Script47.
New code and works
<?php
$system = mysql_query("SELECT * FROM system");
$results = mysql_fetch_array($system);
if($results['maintenance'] == 1)
{
header('Location: /maintenance');
exit;
}
?>
The reason I do not need an extension for maintenance is because I have it set in .htaccess to ignore them, but for everyone to know it's a php file.
You need to actually fetch your results from the database. Look in to the link I provided. I will update my post with code.
<?php
$system = mysql_query("SELECT * FROM system");
$results = mysql_fetch_row($system);
if($results[yourColumnKey] == 1)
{
header('Location: /maintenance.php');
exit;
}
?>
http://php.net/manual/en/function.mysql-fetch-row.php
Edit 1
Your code is prone to SQL injection, you are still using MySQL even though it has been deprecated, you should use either MySQLi or PDO with prepared statements.
Edit 2
You don't seem to be specifying a file extension on your header();.
header('Location: /maintenance');
--^
What is maintenance? A PHP file? A HTML file? You need to specify an extension too.
As you are a self-described beginner, it's probably best to learn how to do this using mysqli instead of using old deprecated code.
Below does essentially the same thing, but will last past the current version of php. It's a good habit to get into. (note if you are going to use any variables in your query, you will want to look up Prepared Statements
$conn = new mysqli($host, $username, $password, $dbname);
$system = $conn->query("SELECT maintenance FROM `system`");
while ($row = $system->fetch_assoc()) {
if($row['maintenance'] == 1) {
header('Location: /maintenance');
exit();
}
else {
header('Location: /index');
exit();
}
}
This question already has answers here:
How do I get the last inserted ID of a MySQL table in PHP?
(16 answers)
Closed 7 years ago.
Hello guys I have this php code to register building data in a game that I'm developing. This code work fine.
What I like to know is how can I echo the auto increased ID of the object that I registered using this code when the register function successful.
<?php
$db = "database";//Your database name
$dbu = "username";//Your database username
$dbp = "password";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['oid']) ){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['oid']));
$sql = mysql_query("INSERT INTO `$db`.`building` (`id`,`oid`) VALUES ('','$oid');");
if($sql){
//The query returned true echo the newly registered id
echo '????';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'Fail to save data';
}
}else{
echo 'Fail-No object owner ID';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
Please help me.
Use mysql_insert_id()
if($sql){
//The query returned true echo the newly registered id
echo mysql_insert_id($dblink);
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'Fail to save data';
}
Notes:
Here is reasoning of why you should not use Mysql but mysqli extension for php
MySQL vs MySQLi when using PHP
From PHP developers:
It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.
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 having some troubles to make a login page. I'm still a beginner at PHP programming, but my login system works if it gets the right login and ID or the right login and email, but it doesnt work with the password.
That's how the password is encrypted on the registering page:
$Salt = base64_encode(md5($Login.$Pass, true));
That's a part of my login system:
$Login = StrToLower(Trim($_POST['login']));
$Password = Trim($_POST['passwd']);
$Password = "0x".md5($Login.$Password);
$sql = "select * from users where name ='".$Login."' and passwd ='".$Password."' ";
Thanks in advance.
Before investing any additional effort in your login code, I would instead highly suggest spending your time researching the topics of SQL injection and PHP's parameterized query features. As posted, your code is a textbook example of login code that is trivial to hack with SQL injection.
Currently, it appears to me that simply entering the following in the "name" login field would allow me to login every time:
' or True;
I apologize that this is not a direct answer to your question but I do not yet have the reputation points to use comments. We all must start learning somewhere but coding a login feature is not to be taken on early in your PHP learning process. Even after years of experience, many people will still advise to never roll your own authentication and instead use an existing framework (good advice in my opinion).
The problem is that when you stored the password you encrypted it like:
base64_encode(md5($Login.$Pass, true))
and when you check the password you are saying that your password is encrypted like:
"0x".md5($Login.$Password);
As an example:
I am using user = 'user' and password = 'password'
You are storing the password like 1ECu0YmhP/lw2sfn6PmHsg== and when you check the password, this is 0xd5745f9425eceb269f9fe01d0bef06ff
Testing Code:
$ php -a
php > echo base64_encode(md5('user'.'password', true));
1ECu0YmhP/lw2sfn6PmHsg==
php > echo "0x".md5('login'.'password');
0xd5745f9425eceb269f9fe01d0bef06ffphp >
Suggestions:
You should sanitize your variables Read: http://php.net/manual/en/function.mysql-real-escape-string.php
mysql is depricated, please start using msqli or PDO (recommended) Read: http://php.net/manual/en/book.pdo.php
For a better and more secure password encryption please use password_hash Read: http://php.net/manual/en/function.password-hash.php & http://php.net/manual/en/faq.passwords.php
I am not sure that you got the Lea Tano answer.
You don't need to decode base64.
You need encode it!!!
:-) so change your code to something like this:
$Login = StrToLower(Trim($_POST['login']));
$Password = Trim($_POST['passwd']);
$Password = base64_encode(md5($Login.$Password, true));
$sql = "select * from users where name ='".$Login."' and passwd ='".$Password."' ";
I am using WYSIWYG Webbuilder 8 to construct a website. Part of the website will be restricted access to registered users only. To this end I have created a MySQL database. I also have a sign-up form. When a new user wishes to sign-up I would like to have the username automatically checked against the database to make sure it doesn't already exist. I intend doing this using an AJAX function as the WYSIWYG software has this option built in. What I need to build myself and this is where I'm struggling is the validate.php that the AJAX command will go to.
I have something like this at present (please excuse my ignorance!):
<?php
$username = $_POST['data'];
// TODO: lookup username in database...
if ($username == 'user')
{
echo "true";
}
else
{
echo "false";
}
?>
I have no real idea if this is adequate or secure. I have been reading some scary stuff about sql injection and other black arts involving the use of forms and I'd like to avoid pitfalls if possible.
Would some kind soul please have a look at my request and help me out? I'm not a programmer by any stretch of the imagination and I'm way out of my depth here.
Thanks in advance for your help
You want to use something that will handle the chatter between your application and the database for you. One of the best tools available for this today is the PDO library, specifically PDO-MySQL for your usage. It will handle escaping and SQL injection issues for you by using parameterized (prepared) statements
Here's an example of connecting to a database and issuing a query in MySQL
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF-8', 'username', 'password');
$statement = $db->prepare('SELECT user_id FROM users WHERE username = :username LIMIT 1');
$statement->bindValue(':username', $_POST['data']);
$statement->execute();
if (false == $userId = $statement->fetchColumn()) {
// No matching username was found in the database
} else {
// A matching username was found in the database
// $userId contains the matching user ID
}
Knowing how to pass this back to your JS/AJAX integration could be dependent on what framework (if any) you are using and what format you would like that data in