Updated December 2026: this tutorial was first published in November 2015.
The original code used the old mysql_* functions (removed in PHP 7) and was
open to SQL injection, so it has been rewritten for PHP 8 with a secure login.
The original code has been removed because it was not safe to copy.
A login web service lets your Android app check a user's email and password against
a MySQL database on your server. The app sends the login details as JSON, and the server
answers with a small JSON result that tells the app whether the login worked.
How it works
- The app sends a POST request with a JSON body:
{"email": "...", "password": "..."}
- The server looks up the user by email only, using a prepared statement.
- The server checks the password with
password_verify() against the
stored hash. The real password is never stored.
- The server returns
status 1 if the login is OK, and
status 0 with a message if not.
What was wrong with the old version
- It no longer runs:
mysql_* functions were removed in PHP 7.
- SQL injection: the email and password were joined straight into the SQL text,
so a specially written "password" could log in without knowing the real one.
- Plain-text passwords: the database compared passwords as plain text. If the
database leaks, every password leaks with it.
- Root database user: the code connected as
root, which gives the
script far more rights than it needs.
Step 1: The user table
Store a password hash, not the password. 255 characters leaves room for
future hash formats.
CREATE TABLE user (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Step 2: Database connection (config.php)
Keep the connection in one file, so login and register share it. PDO with
ERRMODE_EXCEPTION makes database errors easy to catch.
<?php
// Database settings: change these to your own.
// Use a dedicated database user with limited rights, not root.
const DB_HOST = 'localhost';
const DB_NAME = 'mydb';
const DB_USER = 'app_user';
const DB_PASS = 'change-me';
function db(): PDO
{
static $pdo = null;
if ($pdo === null) {
$pdo = new PDO(
'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
DB_USER,
DB_PASS,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
}
return $pdo;
}
Step 3: Register a user (register.php)
The key line is password_hash(): it turns the password into a
one-way hash before it is saved.
<?php
require __DIR__ . '/config.php';
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true) ?? [];
$email = trim($data['email'] ?? '');
$password = $data['password'] ?? '';
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 8) {
http_response_code(400);
echo json_encode(['status' => 0, 'message' => 'Valid email and a password of 8+ characters required']);
exit;
}
// Never store the password itself, only its hash
$hash = password_hash($password, PASSWORD_DEFAULT);
try {
$stmt = db()->prepare('INSERT INTO user (email, password_hash) VALUES (?, ?)');
$stmt->execute([$email, $hash]);
echo json_encode(['status' => 1, 'message' => 'registered']);
} catch (PDOException $e) {
http_response_code(409);
echo json_encode(['status' => 0, 'message' => 'Email already registered']);
}
Step 4: The login service (login.php)
<?php
require __DIR__ . '/config.php';
header('Content-Type: application/json');
function respond(int $status, string $message, int $httpCode = 200): void
{
http_response_code($httpCode);
echo json_encode(['status' => $status, 'message' => $message]);
exit;
}
// 1. Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
respond(0, 'Use POST', 405);
}
// 2. Read the JSON body: {"email": "...", "password": "..."}
$data = json_decode(file_get_contents('php://input'), true) ?? [];
$email = trim($data['email'] ?? '');
$password = $data['password'] ?? '';
if ($email === '' || $password === '') {
respond(0, 'Email and password are required', 400);
}
// 3. Find the user by email (prepared statement: no SQL injection)
try {
$stmt = db()->prepare('SELECT id, password_hash FROM user WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();
} catch (PDOException $e) {
error_log($e->getMessage()); // log the details, never show them
respond(0, 'error', 500);
}
// 4. Check the password against the stored hash
if ($user && password_verify($password, $user['password_hash'])) {
respond(1, 'done');
}
// Same message whether the email or the password is wrong
respond(0, 'Email or password does not match', 401);
The JSON answers keep the same status and message format as
the 2015 version, so existing apps can read them. Failed logins now also return an HTTP
error code (400, 401 or 500). Some Android HTTP clients treat those as errors, so read
the response body in your error handler too.
Login OK: {"status":1,"message":"done"}
Wrong email/pass: {"status":0,"message":"Email or password does not match"} (HTTP 401)
Missing fields: {"status":0,"message":"Email and password are required"} (HTTP 400)
Server problem: {"status":0,"message":"error"} (HTTP 500)
Step 5: Test it
You can test without the app, from a terminal:
# Register a test user
curl -X POST https://your-server.com/register.php \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"secret123"}'
# Log in
curl -X POST https://your-server.com/login.php \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"secret123"}'
Already using the old version?
If your existing table stores plain-text passwords in a password column,
back up the database, then run this script once to hash them:
<?php
// Run ONCE if your old table stored plain-text passwords in a "password" column.
require __DIR__ . '/config.php';
db()->exec('ALTER TABLE user ADD COLUMN password_hash VARCHAR(255) NULL');
$update = db()->prepare('UPDATE user SET password_hash = ? WHERE id = ?');
foreach (db()->query('SELECT id, password FROM user') as $row) {
$update->execute([password_hash($row['password'], PASSWORD_DEFAULT), $row['id']]);
}
db()->exec('ALTER TABLE user DROP COLUMN password');
echo "Done: passwords are now hashed.\n";
Security checklist
- Run the service over HTTPS only, so passwords are encrypted on the way.
- Use a database user with only the rights this script needs, never
root.
- Give the same message for a wrong email and a wrong password, so attackers can't
find out which emails are registered.
- Limit login attempts (for example 5 per minute per IP) to slow down password guessing.
Written for PHP 8 and MySQL. PHP code tested with PHP 8.3, December 2026.