0

Im trying to make a login php for an android app, I modified this php from a tutorial, the issue is I used to always get a response of "success" = 0 "message"= "Not all fields are filled", so I added a few print_r to see where is the problem now I only get this result aimatosnintendo , with are the inputs for username and password, so it's not even getting to the ifs, this is my code:

<?php
// array for JSON response
$response = array();
define('DB_USER', ""); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', ""); // database name
define('DB_SERVER', ""); // db server
// array for JSON response

$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE);

// check for post data
print_r ($_POST['username']);
print_r ($_POST['password']);

if(isset($_POST['username'],$_POST['password'])) {
    $username = $_POST["username"];
    $password = $_POST["password"];


$sql = "SELECT *FROM login WHERE username = $username AND password = $password";
$result = $conn->query($sql) or die (mysqli_connect_error());
 print_r ($username);

    if (!empty($result)) {
        // check for empty result

        if (mysqli_num_rows($result) > 0) {

            $result = mysqli_fetch_array($result);

            $loginfo = array();
            $loginfo["name"] = $result["name"];
            $loginfo["username"] = $result["username"];
            $loginfo["password"] = $result["password"];
            $loginfo["phone"] = $result["phone"];
            $loginfo["email"] = $result["email"];
            $loginfo["license"] = $result["license"];
            //$loginfo["expiration"] = $result["expiration"];


            // success
            $response["success"] = 1;

            // user node
            $response["logina"] = array();

            array_push($response["logina"], $loginfo);

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "Wronglogin";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "Wronglogin";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing

    $response["success"] = 0;
    $response["message"] = "Not all fields are filled";


    // echoing JSON response
    echo json_encode($response);
}
?>

db user password server and name are all correct i just deleted them in this post for safety, i have a code to register info on the database and it works but this one gets me stuck

im expecting a $response["success"] = 1; when username and password match with the database

happymacarts
  • 2,547
  • 1
  • 25
  • 33
Aimatos
  • 49
  • 6
  • 1
    You are vulnerable to [sql injection attacks](http://bobby-tables.com), you have SQL syntax errors, and you're checking for query errors completely WRONG. mysqli_ **CONNECT**_ error. You're not running a connection attempt there... – Marc B Aug 23 '16 at 21:16
  • 1
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST` or `$_GET` data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Aug 23 '16 at 21:29
  • 1
    **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. This code allows *anyone* to get *anything* from your site. **DO NOT** write your own authentication system. Any [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with an [authentication system](https://laravel.com/docs/5.2/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords as plain-text**. – tadman Aug 23 '16 at 21:29

1 Answers1

0

Try

$sql = "SELECT * FROM login WHERE username = '". $username ."' AND password = '".$password."'";
Jfed
  • 187
  • 1
  • 7
  • that did it, buch of thanks =) – Aimatos Aug 23 '16 at 21:30
  • 1
    @Aimatos This makes an already bad problem even worse. Do not use this code. – tadman Aug 23 '16 at 21:30
  • what should i do? – Aimatos Aug 23 '16 at 21:37
  • @tadman im just testing if i can login, this app is not for distributions, the prinr_ post and gets were only for testing if the code got to that point and if it was picking up the inputs from postman. i will hash the password later – Aimatos Aug 23 '16 at 21:48
  • If it's "not for distribution" why have a login at all? Just set a static username and password in your code and forget about the database. – tadman Aug 23 '16 at 21:50
  • 1
    @Aimatos escape the post and get values before sending them to the database, or while you've got the code, play about with some sql injection techniques to get a feel for what needs to be done to avoid it. Passwords don't need escaping, but should be hashed/keyed/salted if being used by others – independent.guru Aug 23 '16 at 21:54
  • @tadman its for a family project, i need for some to have certain acces to some features and some not so much – Aimatos Aug 23 '16 at 22:00
  • @GCRRDev thanks a bunch ill check out injection techniques, im just new to all this =) – Aimatos Aug 23 '16 at 22:01
  • @Aimatos Whatever the project's for, it's a good opportunity to learn how to do this correctly. Short-cuts often lead to a whole lot of wasted time tracking down subtle mistakes. I'd strongly encourage you to give a framework like Laravel a shot, 80% of what you need is probably already done and you can focus on adding the 20% that isn't generic boilerplate. – tadman Aug 23 '16 at 22:07
  • 1
    @tadman relying on a third party framework isn't the best way to go about learning how to do things correctly. If 80% of the work's done for you, you're only gaining 20% of the knowledge you should be getting. There are many tutorials online for building a framework and as you progress in your skill level, your own framework will wind up being more efficient for your projects than any other out there. – independent.guru Aug 23 '16 at 22:11
  • @GCRDev Don't take this position. It's ridiculous and absurd. Python, Ruby, Java, Node, Perl and many other communities *strongly* recommend people start with a framework. PHP stands alone in it's stubborn resistance to such a thing and it's hurting the PHP community in a huge way. Building a framework is an enormous undertaking, and the risks of simple mistakes have never been higher. Don't think of frameworks as the easy way out, they still have many, many opportunities for people to learn, but they can learn *and* be productive. – tadman Aug 23 '16 at 22:13
  • "Your own framework will wind up being more efficient for your projects than any other out there." This is why most PHP projects that involve Little Jimmy's First Framework are so horrible that they need to be burned to the ground and written from scratch in a coherent manner. There's **nothing** efficient about re-inventing the wheel. – tadman Aug 23 '16 at 22:14
  • @tadman He's just starting out. He should get the basics down before throwing in a framework. – Jfed Aug 23 '16 at 22:18
  • @tadman ahh, the whole reinventing the wheel phrase thrown about on here so often, why don't we just stop the learning process all together and use one of the many scripts available for pretty much every type of application now. The whole point in coding in the first place is so you reinvent and create new and better things. Your whole premise is about learning a third party framework's structure, something that's completely unnecessary. By the time you're done with learning one framework, you could have been well on your way to finishing your own – independent.guru Aug 23 '16 at 22:21
  • @JoshFedoryszn The basics **are** learning a framework, not core PHP, as it will show you how to organize your code, give you tools for solving complicated problems without making a mess of things, and there's a ton of community code you can leverage that makes you more productive. Learning is important, don't get me wrong, but you program not to learn but to solve problems. – tadman Aug 23 '16 at 22:22
  • @GCRDev There's a huge difference between using a canned script and using a framework. A framework *supports* you, a canned script *constrains* you. The PHP community is lucky to have nearly a dozen full-featured frameworks, a luxury no other language has, and yet people *insist* on ignoring them and writing their own junk instead. It's completely ridiculous. These arguments simply do not happen in other languages. Python people recommend Django or Pyramid, Ruby is a big fan of Rails, and Node would have you start on Express. Those who *want* to learn do learn. – tadman Aug 23 '16 at 22:25
  • @tadman what's ridiculous is a coder's complete reliance on an open source framework that can be studied by absolutely anybody. They update because open source isn't as secure as the people who use it like to think, and you have to learn whole new things, set at standards the original writers set. Your own framework isn't as easily accessibly by absolutely anyone, updates to it are done by yourself so you know what you're doing with each change and puts you and your site in a much securer position. Frameworks are for those who don't want to learn or can't be bothered to do certain things – independent.guru Aug 23 '16 at 22:29
  • @GCRDev I'd challenge you to find a security bug in a professional framework like Laravel, because if there is one many people want to know about it. You're recommending **security through obscurity** which is, as anyone knows, false security at best. There are tools that will [carve through your code like a hot knife through butter](http://sqlmap.org) and the consequences can be [extremely severe](http://codecurmudgeon.com/wp/sql-injection-hall-of-shame/). Everything you're advocating is risky, dangerous, and ill-advised. – tadman Aug 23 '16 at 22:31
  • @GCRDev I'd bet money that you'd be hard pressed to find a security problem in the shipping version of Laravel just as much as any home-rolled framework probably has *multiple* security holes nobody's ever noticed. – tadman Aug 23 '16 at 22:33
  • @tadman no, recommending open source & free software is a risky and dangerous thing. If Laravel never had security problems, they wouldn't need updates to fix them. As for 'finding a problem' for you I'd use a certain link but the search link's not allowed to be posted on here, but again I suppose you're just looking for 80% of the work to be done for you. – independent.guru Aug 23 '16 at 22:40
  • @GCRDev Any non-trivial code-base will have some kind of flaws but most large-scale open-source projects are self-correcting due to the amount of oversight and detailed review the code gets. Laravel has had some vulnerabilities but these were quickly rectified. The nature of these bugs is often so [obscure and nuanced](https://labs.mwrinfosecurity.com/blog/laravel-cookie-forgery-decryption-and-rce/) that I highly doubt anyone's naïve home-made framework offers any protection at all. The list of possible exploits these days is **huge**. – tadman Aug 23 '16 at 22:44
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/121673/discussion-between-gcrdev-and-tadman). – independent.guru Aug 23 '16 at 22:45
  • @GCRDev Do you protect against CSRF? XSS? SQL injections? Each of these things is just the tip of a very big iceberg and understanding these on a level where you can defend against them takes years of specialized experience. – tadman Aug 23 '16 at 22:45
  • @tadman this is going on forever so I'll move it to chat to avoid clogging up the comments any more – independent.guru Aug 23 '16 at 22:46
  • Are those the only things you could google? Again, you're just showing nothing but lazy "learning" techniques. – independent.guru Aug 23 '16 at 22:48
  • @tadman , i did not use a framework because i dont know what it is, i tried to solve the problem i had as best as i could before asking for help, ive never touched programing in java, just did a little c at school, it hard to learn from online when you dont even know what youre seraching for, so i go by baby steps, beside im sure you can tell english is not my first lenguage and most online resourses are in english – Aimatos Aug 23 '16 at 23:52
  • @Aimatos There are many frameworks to choose from and they all help you in different ways, but the fundamental thing they do is give you a lot of higher-level tools to work with when making your site. A [basic introduction course](https://laracasts.com/series/laravel-5-fundamentals) can give you a sense of how you go about building a site. There's some work to get up to speed on that, but once you've got a basic understanding you can do a lot of things pretty quickly. – tadman Aug 24 '16 at 02:12