HTTP is stateless, thus any use of a session goes against the design of HTTP (and most of the design and security problems on the web today stem from this).

To achieve true stateless authentication, use the WWW-Authenticate and Authorization headers with your API, or upgrade the API to be exposed over HTTP+TLS (https), issue each API user account with a X509 Certificate which identifies them, then request it is sent with each API call (you can then identify them by the public key which you save against the account as an API key).

ps: always worth reading in context, chapter 6 of Roy's dissertation is invaluable but often ignored for that single chapter 5 REST.

can expand the answer if you need it :) expanding..

The Authorization request header and WWW-Authenticate response header are standard HTTP Headers used for Challenge Response Authentication, the two common and standarized methods for use with these headers are Basic and Digest Authentication. If Authorization credentials are sent with a request you process to allow access else fail with the appropriate status code, or issue a challenge using the WWW-Authenticate response header, the flow is the same as form based authentication, but it works at a RESTful HTTP level instead, and should be used to verify each request rather than setting up a session (like most do with form based authentication).

The HTTP+TLS/x509 method to which I refer is commonly known as Public key authentication, again it works at a protocol level rather than application level and is natively supported. In short the client has an private key + certificate + public key on their side, when they connect to you the certificate (which includes the public key) is sent through to the server, you then read the details from the certificate (if you want) and use the public key to authorize them, if you recognise it you let them in. This is more secure because it uses the HTTP+TLS stack where everything is encrypted and the connection is between client and server with nothing in between, and primarily because effectively the 'password' is in two parts, a private key which never leaves their machine, and a public key which does, together they form a key pair.

The PHP manual has a nice section on HTTP Authentication with code (for the headers method) and all the functions needed for HTTP+TLS/x509 are also in the manual (with examples in the documentation, but split over the various functions).

🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 37018481 β€Ί how-do-you-create-a-php-login-web-service-that-can-be-used-from-multiple-applica
How do you create a PHP login web service that can be used from multiple applications?
May 4, 2016 - Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams Β· Get early access and see previews of new features. Learn more about Labs ... <?php require('_includes.php'); $username = fetchPostParam('username'); $password = fetchPostParam('password'); // A higher "cost" is more secure but consumes more processing power $cost = 10; $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.'); // this is so php can recognize / verify this later.
🌐
SourceForge
sourceforge.net β€Ί projects β€Ί phploginwebservice
PHP Login Webservice with JSON download | SourceForge.net
PHP Login Webservice with JSON
Download PHP Login Webservice with JSON for free. This is basic PHP Login Webservice with JSON output. Run sql dump in your Mysql server, then Put the codes in your server. This webservice always gives JSON output. Run sql dump in your Mysql server, then Put the codes in your server. This webservice always gives JSON output. Β· This project is created for who wants to learn basic PHP webservice. So it is for PHP beginners. Β· We have just one table whose name is "users". Here is its sql: Β· CREATE TABLE IF NOT EXISTS `users` ( Β· `id` int(11) NOT NULL AUTO_INCREMENT, Β· `unique_id` varchar(64) CHAR
Rating: 5 ​
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 22147771 β€Ί php-web-service-for-authenticating-user-login-on-android
PHP web service for authenticating user login on Android - Stack Overflow
March 7, 2014 - Explore Stack Internal ... Trying to get the user authentication work on Android. The Android app sends username and password using POST method. But, I keep getting "Error receiving detail!!" error. I tried to use REST console to see if the web service works, but no success, I get the same error even there. Any help or direction would be appreciated. ... <?php require_once '../site_info.php'; require_once '../database_connect.php'; require_once '../functions.php'; if(isset($_REQUEST['email']) and $_REQUEST['email']!='' and isset($_REQUEST['password']) and $_REQUEST['password']!='') { $email =
🌐
Coding Infinite
codinginfinite.com β€Ί home β€Ί restful web services in php example – php + mysql with source code
Restful Web Services in PHP Example - PHP + MySQL Best Practice
November 8, 2019 - We’ll use this folders & files structure for writing our Webservices. api β”œβ”€β”€β”€ config/ β”œβ”€β”€β”€β”€β”€β”€ database.php – file used for connecting to the database. β”œβ”€β”€β”€ objects/ β”œβ”€β”€β”€β”€β”€β”€ user.php – contains properties and methods for β€œuser” database queries. β”œβ”€β”€β”€ User/ β”œβ”€β”€β”€β”€β”€β”€ signup.php – file that will accept user data to be saved to the DB. β”œβ”€β”€β”€β”€β”€β”€ login.php – file that will accept username & password and validate
Top answer
1 of 3
8

HTTP is stateless, thus any use of a session goes against the design of HTTP (and most of the design and security problems on the web today stem from this).

To achieve true stateless authentication, use the WWW-Authenticate and Authorization headers with your API, or upgrade the API to be exposed over HTTP+TLS (https), issue each API user account with a X509 Certificate which identifies them, then request it is sent with each API call (you can then identify them by the public key which you save against the account as an API key).

ps: always worth reading in context, chapter 6 of Roy's dissertation is invaluable but often ignored for that single chapter 5 REST.

can expand the answer if you need it :) expanding..

The Authorization request header and WWW-Authenticate response header are standard HTTP Headers used for Challenge Response Authentication, the two common and standarized methods for use with these headers are Basic and Digest Authentication. If Authorization credentials are sent with a request you process to allow access else fail with the appropriate status code, or issue a challenge using the WWW-Authenticate response header, the flow is the same as form based authentication, but it works at a RESTful HTTP level instead, and should be used to verify each request rather than setting up a session (like most do with form based authentication).

The HTTP+TLS/x509 method to which I refer is commonly known as Public key authentication, again it works at a protocol level rather than application level and is natively supported. In short the client has an private key + certificate + public key on their side, when they connect to you the certificate (which includes the public key) is sent through to the server, you then read the details from the certificate (if you want) and use the public key to authorize them, if you recognise it you let them in. This is more secure because it uses the HTTP+TLS stack where everything is encrypted and the connection is between client and server with nothing in between, and primarily because effectively the 'password' is in two parts, a private key which never leaves their machine, and a public key which does, together they form a key pair.

The PHP manual has a nice section on HTTP Authentication with code (for the headers method) and all the functions needed for HTTP+TLS/x509 are also in the manual (with examples in the documentation, but split over the various functions).

2 of 3
0

If you want to be hard-core about the stateless aspect, which might be important in certain systems, you could send the user's credentials on each request. This lets you authorize access to certain resources and verbs without creating 'state'. See the documentation for Amazon's S3 service, for example.

I'm tempted to say that other uses for sessions, like a shopping-cart, for example, create a real emphasis on state that goes against REST.

🌐
C# Corner
c-sharpcorner.com β€Ί article β€Ί login-service-in-php-and-mysql-for-android-application
Login Service In PHP And MySQL For Android Applications
June 30, 2016 - INSERT INTO `tbl_user` (`ur_Id`, `ur_username`, `ur_password`, `ur_status`) VALUES ... (3, '[email protected]', 'arvind', 1); After running the below script you will see a table something like below.
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 27183714 β€Ί web-services-login-page-in-php
json - Web services login page in PHP - Stack Overflow
<?php if($_SERVER['REQUEST_METHOD'] == "GET"){ // Get post data` $username = isset($_POST['username']) ? mysql_real_escape_string($_POST['username']) : ""; $password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : ""; //$status = 1; // Here we set by default status In-active.
Find elsewhere
Top answer
1 of 2
3

If this is being called by a custom client program (i.e. you mobile phones), and not the browser, why "log them in" at all. Rather, simply use HTTP Authentication (either DIGEST or BASIC if you're going SSL, or your own scheme), and "log them in" every time.

Then you don't have to worry about sessions, about load balancing, and fail over, etc. Keep it stateless.

Addenda:

Certainly, fewer hits to the DB are better, that's just a general rule. But at the same time, many hits to the DB are handled by cached pages on the DB server, or possibly application caches so that they never hit the DB server. So, in some cases, particularly single row queries against an indexed column, DB hits can be very cheap.

Now, one might consider if they're both stored and readily accessed, what's really the difference between a cache bit of the database, and a unique user session.

Well, primarily, the difference is in the contract with the data. A cached item has lifespan directly proportional to the amount of memory you have and the amount of uncached activity happening. Give it a small amount of memory, and the cached item likely has a very short lifespan. Give it a lot of memory, and the cached item has a much better chance of hanging around. If the amount of memory for cached data is large enough to where repeated activity for that data continues to use the cache, the cache is a big win. If your cache is recycling so fast nothing is ever "in" the cache, you cache has almost no value. But the point is that the system will work with or without the cache, the cache is simply a performance enhancement.

A session, however, has a different contract. Many sessions have a specific, minimum lifespan, typically measured in minutes: 10, 20, even 30 minutes.

That means that if a user hit your site just once, you must dedicate resources to that user even if he never comes back. You have to, otherwise the session offer effectively no value.

If you get a lot of traffic, you get a lot of new sessions to manage. In theory, under bad circumstance, sessions can spike without limit. If you suddenly get 10,000 hits on your site, you get to manage the remains of those hits for the minimal lifespan of your session. You have to dedicate resources (memory or disk) to them, you have to keep track of them, and then, inevitably, you have to clean them up.

A cache is a fixed resource. It only grows to the size you configure it. You have no obligation to keep anything in the cache, and as discussed earlier, the system will function with or without the cache. Caches naturally recycle. If you get that surge of 10,000 hits, they'll possibly roll your cache, but after that they leave no mark on your system. They can hit and be gone in 1 or 2 minutes, never to be seen again.

Finally, with sessions, you need to share them among your infrastructure so that they travel with the user if they hop from machine to machine (for whatever reason). Caches don't. Ideally you want to keep a user local to a set of resources, so that the caches can do their job, but the system works whether they move or stay (it just works better if they stay, because of the cache reuse). If you don't replicate your sessions, they don't work at all.

DB hits add up, they can be cheap, but they're never free. But a session has its own costs as well, so it important to consider them both and how they apply within your architecture.

2 of 2
3

Currently, I'm just using SESSIONS. The client calls a login API, and any other API needed. But I'm concerned about the impact of having 200,000 people all calling this service and have all of those sessions.

Standard those sessions touch the disc because default session_save_handler is set to file. It is better for your system to not touch the disc(memory is much faster). You could try to override session_set_save_handler to use something different than file. For example you could have sessions be stored in:

  • redis(I like the predis client). Even faster would be to install C extension, but need probably need root access to recompile PHP. If you have that many users you should probably own/rent VPS. The nice folks at http://redistogo.com provide you with free plans (5 MB) if you can't install anything on the computer. I mentioned above that you should be having the capability to install things if you really want to have performance.
  • memcached

these in-memory databases also support better scaling. You should also be using these databases to cache the rest of your database-queries(MySQL?). You have to remember that touching the disc is very slow compared to just using memory.

You should also should install APC to get the best performance.

How is this typically handled? Like facebook, flickr, etc....

Nowadays you can't use any API without using OAuth(although I think authentication via sessions are easier to implement). It is the new de facto standard for doing authentication without having to share passwords. The creator of PHP(Rasmus) has made a tutorial explaining how to Writing an OAuth Provider Service. Searching oauth php in google you should get yourself more than enough information.

Also nowadays most of Facebook's site is using HipHop instead of the plain old PHP to speed up their website. PHP has open-sourced a lot of there works which you could/should use:

🌐
PHP
php.net β€Ί manual β€Ί en β€Ί features.http-auth.php
PHP: HTTP authentication with PHP - Manual
Due to this different pattern interpretation by the 'preg_match_all' function, the 'http_digest_parse' function will always return a false result if you have modified your locale (I mean if your locale accepts some extended characters, see http://fr.php.net/manual/en/reference.pcre.pattern.syntax.php for further information). IMHO, I suggest you not to use setlocale before having your authentication completed... PS : Here's a non-compatible setlocale declaration... setlocale ( LC_ALL, 'fr_FR', 'fr', 'FR', 'french', 'fra', 'france', 'French', 'fr_FR.ISO8859-1' ) ; ... New auth: <?php $login = 'test_login'; $pass = 'test_pass'; if(($_SERVER['PHP_AUTH_PW']!= $pass || $_SERVER['PHP_AUTH_USER'] != $login)|| !$_SERVER['PHP_AUTH_USER']) { header('WWW-Authenticate: Basic realm="Test auth"'); header('HTTP/1.0 401 Unauthorized'); echo 'Auth failed'; exit; } ?>
🌐
Androidhub4you
androidhub4you.com β€Ί 2015 β€Ί 11 β€Ί php-login-web-service-php-code-for.html
Android Hub 4 you : the free android programming tutorial: PHP Login web service | PHP code for login | PHP Simple webservices
November 26, 2015 - <?php //take the values from client as json $json = file_get_contents('php://input'); //open database connection $con = mysql_connect('localhost','root','root') or die('Cannot connect to the DB'); mysql_select_db('mydb',$con); //take json values into data variable $data = json_decode($json); //make a sql query to store data $sql="SELECT * from `mydb`.`user` WHERE email = '".$data->{'email'}."' AND password = '".$data->{'password'}."'"; $qur=mysql_query($sql); //check the database response it is true or false if($qur){ if (mysql_num_rows($qur)>= 1 ) { $json=array("status"=>1,"message"=>"done");
🌐
Readthedocs
php-web-services-training.readthedocs.io β€Ί en β€Ί latest β€Ί authentication.html
Authentication - PHP Web Services Basic's documentation!
<?php $api_credentials = array( 'user1' => 'abc123', 'user2' => 'abcxyz' ); if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My API"'); header('HTTP/1.1 401 Unauthorized'); exit; } else { $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; if (!array_key_exists($username, $api_credentials)) { header('HTTP/1.1 403 Forbidden'); exit; } if ($password != $api_credentials[$username]) { header('HTTP/1.1 403 Forbidden'); exit; } } The $api_credentials above simply store the user’s credentials details such as username and password in a PHP array, hardcoded in the source code but in practice you’ll store the information in database such as MySQL.
🌐
Tutorial Republic
tutorialrepublic.com β€Ί php-tutorial β€Ί php-mysql-login-system.php
Creating a User Login System with PHP and MySQL - Tutorial Republic
In this tutorial we'll create a simple registration and login system using the PHP and MySQL. This tutorial is comprised of two parts: in the first part we'll create a user registration form, and in the second part we'll create a login form, as well as a welcome page and a logout script. In this section we'll build a registration system that allows users to create a new account by filling out a web form.
🌐
GitHub
github.com β€Ί topics β€Ί php-login-web-service-example
php-login-web-service-example Β· GitHub Topics Β· GitHub
February 12, 2018 - This API protects from attacks like SQL injunction and XSS. Making development work easier for developers. php-api php-login php-authentication login-api php-login-web-service-example signup-api php-login-form-with-database
🌐
GitHub
github.com β€Ί msaad1999 β€Ί PHP-Login-System
GitHub - msaad1999/PHP-Login-System: Embeddable and Secure PHP Authentication System with Login, Signup, User Profiles, Profile Editing, Account Verification via Email, Password Reset System, Remember-Me Feature and more.
Embeddable and Secure PHP Authentication System with Login, Signup, User Profiles, Profile Editing, Account Verification via Email, Password Reset System, Remember-Me Feature and more. - msaad1999/...
Starred by 453 users
Forked by 127 users
Languages Β  PHP 69.8% | Hack 25.9% | CSS 4.0% | JavaScript 0.3% | PHP 69.8% | Hack 25.9% | CSS 4.0% | JavaScript 0.3%
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 50359853 β€Ί symfony-3-3-web-service-login-form
php - Symfony 3.3 Web Service Login form - Stack Overflow
The goal is login in with the form and the REST web service, updating my session data, like, name, doc, email, etc. And with this data allow or deny the access to some pages or functions. When we submit the form, we donΒ΄t know how to use the data returned by the webservice, also if there are response or not. ... <?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; class SecurityController extends Controller { // public function loginA
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί php β€Ί creating-a-registration-and-login-system-with-php-and-mysql
Creating a Registration and Login System with PHP and MySQL - GeeksforGeeks
December 19, 2025 - A registration and login system is a fundamental component of many web applications and provides user authentication and security. This allows users to create an account log in with their login credentials and manage their session securely. By using PHP for server-side scripting and MYSQL for ...