Skip to content

Instantly share code, notes, and snippets.

@ryantxr
Last active March 13, 2016 07:56
Show Gist options
  • Save ryantxr/d587c96dd3ad33aa3885 to your computer and use it in GitHub Desktop.
Save ryantxr/d587c96dd3ad33aa3885 to your computer and use it in GitHub Desktop.
<?php
// DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE
// MYSQL-DBNAME-GOES-HERE
class LoginHandler {
public $dbHostname = 'DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE';
public $dbDatabaseName = 'MYSQL-DBNAME-GOES-HERE';
public $user = 'DATABASE_USERNAME';
public $password = 'DATABASE_PASSWORD';
//public $port = 3307;
public $message;
public function handleRequest($arg) {
$username = $arg['username'] ? $arg['username']: null;
$password = $arg['password'] ? $arg['password']: null;
if ( ! $username || ! $password ) {
$this->fail();
return;
}
try {
$portChunk = ( isset($this->port) ) ? ';port=' . $this->port : null;
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname}{$portChunk}";
$pdo = new PDO($dsn, $this->user, $this->password);
$sql="SELECT * FROM `user` WHERE `username`='$username' and `password`='$password'";
$stmt = $pdo->query($sql);
// var_dump($stmt);
if ( $stmt === false ) {
$this->message = "Query failed";
$this->fail();
return;
}
elseif ( $stmt->rowCount() > 0 ) {
$this->message = "OK";
$this->success();
return;
}
else {
$this->message = "User not found or wrong password";
$this->fail();
return;
}
}
catch(PDOException $e) {
$this->log('Connection failed: ' . $e->getMessage());
$this->fail();
}
}
function success() {
echo json_encode(['success' => 1, 'message' => $this->message]);
}
function fail() {
echo json_encode(['success' => 0, 'message' => $this->message]);
}
function log($msg) {
file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
// Commend out the next line to test from the command line
$handler->handleRequest($_POST);
// Use this to run from the command line.
// $ php applogin.php username aaaa password bbbb
// $args = [$argv[1] => $argv[2], $argv[3] => $argv['4']];
// $handler->handleRequest($args);
// MacBook-Pro:~ me$ curl http://PUT_YOUR_HOSTNAME/apicall.php -d"username=drum&password=pass1"
// {"success":0}
// MacBook-Pro:~ me$ curl http://PUT_YOUR_HOSTNAME/apicall.php -d"username=drum&password=pass0"
// {"success":1}
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`, `username`, `password`)
VALUES
(1, 'drum', 'pass');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment