Integrate Web3 Wallet Connect Into a PHP Website: Secure Login Guide
A practical web3 PHP tutorial: connect a crypto wallet in the browser with Reown AppKit, generate a one-time nonce in PHP, verify the signed message server-side, and start a hardened PHP session.
Connecting a crypto wallet to a PHP site is mostly a two-part job. JavaScript opens the wallet connection in the browser, while PHP creates a secure challenge, verifies the signed message, and starts the user session. Your PHP app should never ask users for private keys, seed phrases, or wallet passwords. It asks the wallet to sign a one-time message, then verifies that signature on the server.
This web3 PHP tutorial shows a login flow you can adapt for a membership area, token-gated page, NFT dashboard, crypto checkout, or any PHP crypto wallet authentication feature. The example uses Reown AppKit for the browser wallet connection and plain PHP for nonce generation, CSRF protection, and server-side verification.
Key takeaways
- Wallet login is signature-based: the browser signs, the server verifies. No key material ever reaches PHP.
- A fresh nonce per attempt plus a short expiry is what stops replay attacks.
- Verify the exact message string you generated — one changed newline breaks recovery, and that is by design.
- Regenerate the PHP session ID after a successful verification to prevent session fixation.
- Smart contract wallets need EIP-1271 verification; EOA-only signature recovery will reject them.
<figure class="my-6"> <img src="https://devloader.com/__l5e/assets-v1/ada976b7-29ca-4f97-97dd-25700e15eefe/w3-1-hero.jpg" alt="Browser Connect Wallet modal with MetaMask, WalletConnect and Coinbase Wallet options linked to a PHP server" width="1600" height="900" class="rounded-lg w-full" /> <figcaption class="text-sm text-muted-foreground mt-2">Integrating web3 wallet connect into a PHP website: the browser handles wallet selection and signing, the PHP backend owns the challenge and the session. © devloader.com</figcaption> </figure>
What you will build
By the end of this guide you will have:
- A PHP page with a Connect Wallet button.
- A secure PHP endpoint that creates a one-time login message.
- Browser JavaScript that asks the wallet to sign that message.
- A PHP verification endpoint that validates the signature.
- A PHP session containing the verified wallet address.
This is a login example, not a token-transfer example. The same base flow extends later to balances, smart contract reads, payments, or token gating.
Prerequisites
Before you integrate web3 wallet connect PHP website functionality, prepare:
- PHP 8.1 or newer, with Composer.
- Node.js and npm for bundling the wallet JavaScript.
- A Reown (WalletConnect) project ID.
- HTTPS in production — non-negotiable.
- A browser or mobile wallet: MetaMask, Coinbase Wallet, Trust Wallet, Rainbow, or any WalletConnect-compatible wallet.
Add your production domain to the allowlist in the wallet project dashboard. AppKit configuration takes a projectId, networks, adapters, and optional metadata (site name, description, URL, icons).
Step 1: Create the project structure
your-php-web3-site/
public/
index.php
assets/
api/
nonce.php
verify.php
me.php
logout.php
src/
wallet.js
includes/
bootstrap.php
vendor/
composer.json
package.jsonYour web server should expose public/ as the document root. Keep api/, includes/, and vendor/ outside the public root when your host allows it; when it does not, block those directories with server rules.
Note: if
api/sits outside the document root, route it with a rewrite (for example/api/(.*)to../api/$1) or move only the endpoint files intopublic/api/while keepingincludes/andvendor/private.
Step 2: Install the PHP signature library
composer require simplito/elliptic-php kornrunner/keccakYou can also use a wrapper package that bundles both, such as agustind/ethsignature. Either way, review any third-party crypto package before production, pin exact versions, and keep them patched. The two primitives you need are Keccak-256 hashing and secp256k1 public key recovery.
Step 3: Add a secure PHP bootstrap
Create includes/bootstrap.php. It starts the session, hardens cookies, and adds small helpers.
<?php
declare(strict_types=1);
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'),
'httponly' => true,
'samesite' => 'Lax',
]);
session_start();
header_remove('X-Powered-By');
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
function json_response(array $data, int $status = 200): void {
http_response_code($status);
header('Content-Type: application/json');
echo json_encode($data, JSON_UNESCAPED_SLASHES);
exit;
}
function json_input(): array {
$raw = file_get_contents('php://input');
$data = json_decode((string) $raw, true);
return is_array($data) ? $data : [];
}
function require_post(): void {
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
json_response(['ok' => false, 'error' => 'POST required'], 405);
}
}
function verify_csrf(array $input): void {
$sent = $input['csrf'] ?? '';
$stored = $_SESSION['csrf_token'] ?? '';
if (!is_string($sent) || $stored === '' || !hash_equals($stored, $sent)) {
json_response(['ok' => false, 'error' => 'Invalid CSRF token'], 403);
}
}PHP sessions alone do not protect against CSRF, which is why every state-changing endpoint below checks a token.
Step 4: Create the PHP page
public/index.php loads the wallet UI, exposes the CSRF token to JavaScript, and shows the connection status.
<?php require __DIR__ . '/../includes/bootstrap.php'; ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Wallet Login</title>
</head>
<body>
<main>
<h1>Member Wallet Login</h1>
<p>Connect your wallet and sign a one-time message to continue.</p>
<appkit-button></appkit-button>
<button id="wallet-login" type="button">Login with wallet</button>
<p id="wallet-status">Not signed in.</p>
</main>
<script>
window.APP_CONFIG = {
csrf: "<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>",
projectId: "<?= htmlspecialchars(getenv('REOWN_PROJECT_ID') ?: '', ENT_QUOTES, 'UTF-8') ?>"
};
</script>
<script type="module" src="/assets/wallet.js"></script>
</body>
</html>Injecting the project ID from an environment variable beats hardcoding it, because staging and production usually use different allowlisted domains.
<figure class="my-6"> <img src="https://devloader.com/__l5e/assets-v1/b9013300-4f11-4d2a-b119-c35550d52dd7/w3-2-flow.jpg" alt="Four-step web3 wallet login flow diagram: connect wallet, request nonce, sign message, verify in PHP" width="1600" height="900" class="rounded-lg w-full" loading="lazy" /> <figcaption class="text-sm text-muted-foreground mt-2">The four-step crypto wallet authentication flow: connect, request nonce, sign, verify — the browser never sends anything PHP is willing to trust on its own. © devloader.com</figcaption> </figure>
Step 5: Build the wallet JavaScript
npm init -y
npm install @reown/appkit @reown/appkit-adapter-ethers ethers
npm install --save-dev viteAdd build scripts to package.json:
{
"scripts": {
"dev": "vite",
"build": "vite build"
}
}Give Vite a predictable output name so the PHP <script> tag never goes stale:
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
build: {
outDir: 'public/assets',
emptyOutDir: false,
rollupOptions: {
input: 'src/wallet.js',
output: { entryFileNames: 'wallet.js' }
}
}
});Now src/wallet.js:
import { createAppKit } from '@reown/appkit';
import { EthersAdapter } from '@reown/appkit-adapter-ethers';
import { mainnet } from '@reown/appkit/networks';
import { BrowserProvider } from 'ethers';
const statusEl = document.getElementById('wallet-status');
const loginBtn = document.getElementById('wallet-login');
const modal = createAppKit({
adapters: [new EthersAdapter()],
networks: [mainnet],
projectId: window.APP_CONFIG.projectId,
metadata: {
name: 'My PHP Web3 Site',
description: 'Wallet login for a PHP website',
url: window.location.origin,
icons: [window.location.origin + '/icon.png']
}
});
async function getSigner() {
if (!modal.getIsConnectedState()) {
await modal.open({ view: 'Connect', namespace: 'eip155' });
throw new Error('Connect your wallet, then click login again.');
}
const walletProvider = modal.getWalletProvider();
if (!walletProvider) throw new Error('No EVM wallet provider found.');
const ethersProvider = new BrowserProvider(walletProvider);
return ethersProvider.getSigner();
}
async function postJson(url, payload) {
const res = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json().catch(() => ({}));
if (!data.ok) throw new Error(data.error || 'Request failed (' + res.status + ')');
return data;
}
async function walletLogin() {
loginBtn.disabled = true;
try {
statusEl.textContent = 'Preparing secure login message...';
const signer = await getSigner();
const address = await signer.getAddress();
const { message } = await postJson('/api/nonce.php', {
csrf: window.APP_CONFIG.csrf,
address
});
statusEl.textContent = 'Check your wallet and sign the message...';
const signature = await signer.signMessage(message);
const verified = await postJson('/api/verify.php', {
csrf: window.APP_CONFIG.csrf,
address,
message,
signature
});
statusEl.textContent = 'Signed in as ' + verified.address;
} catch (error) {
statusEl.textContent = error.message;
} finally {
loginBtn.disabled = false;
}
}
loginBtn.addEventListener('click', walletLogin);Build it with npm run build. credentials: 'same-origin' matters: without it some setups drop the session cookie and verification silently fails.
Step 6: Generate a one-time nonce in PHP
Create api/nonce.php. A nonce prevents replay attacks, where an attacker reuses a captured signature.
<?php
require __DIR__ . '/../includes/bootstrap.php';
require_post();
$input = json_input();
verify_csrf($input);
$address = strtolower(trim((string) ($input['address'] ?? '')));
if (!preg_match('/^0x[a-f0-9]{40}$/', $address)) {
json_response(['ok' => false, 'error' => 'Invalid wallet address'], 422);
}
$domain = $_SERVER['HTTP_HOST'] ?? 'localhost';
$nonce = bin2hex(random_bytes(16));
$issuedAt = gmdate('c');
$message = "Sign in to {$domain}\n"
. "Wallet: {$address}\n"
. "Nonce: {$nonce}\n"
. "Issued At: {$issuedAt}\n"
. "This signature does not send a transaction or cost gas.";
$_SESSION['wallet_login'] = [
'address' => $address,
'message_hash' => hash('sha256', $message),
'expires_at' => time() + 300,
];
json_response(['ok' => true, 'message' => $message]);Keep the expiry short — five minutes is plenty for a wallet approval, and it limits the window for a stolen challenge.
Step 7: Verify the signature in PHP
Create api/verify.php. This is the step that actually authenticates the user.
<?php
require __DIR__ . '/../includes/bootstrap.php';
require __DIR__ . '/../vendor/autoload.php';
use Elliptic\EC;
use kornrunner\Keccak;
require_post();
$input = json_input();
verify_csrf($input);
$address = strtolower(trim((string) ($input['address'] ?? '')));
$message = (string) ($input['message'] ?? '');
$signature = (string) ($input['signature'] ?? '');
$challenge = $_SESSION['wallet_login'] ?? null;
if (!is_array($challenge)) {
json_response(['ok' => false, 'error' => 'No active wallet challenge'], 400);
}
if (($challenge['expires_at'] ?? 0) < time()) {
unset($_SESSION['wallet_login']);
json_response(['ok' => false, 'error' => 'Login message expired'], 400);
}
if (!hash_equals((string) $challenge['address'], $address)) {
json_response(['ok' => false, 'error' => 'Wallet address mismatch'], 400);
}
if (!hash_equals((string) $challenge['message_hash'], hash('sha256', $message))) {
json_response(['ok' => false, 'error' => 'Login message mismatch'], 400);
}
function recover_signer(string $message, string $signature): ?string {
if (!preg_match('/^0x[0-9a-fA-F]{130}$/', $signature)) {
return null;
}
$sig = substr($signature, 2);
$r = substr($sig, 0, 64);
$s = substr($sig, 64, 64);
$v = hexdec(substr($sig, 128, 2));
if ($v > 3) { $v -= 27; } // 27/28 -> 0/1
if ($v !== 0 && $v !== 1) { return null; }
// EIP-191 personal_sign prefix
$prefixed = "\x19Ethereum Signed Message:\n" . strlen($message) . $message;
$hash = Keccak::hash($prefixed, 256);
$ec = new EC('secp256k1');
$publicKey = $ec->recoverPubKey($hash, ['r' => $r, 's' => $s], $v);
return '0x' . substr(Keccak::hash(hex2bin(substr($publicKey->encode('hex'), 2)), 256), 24);
}
try {
$recovered = recover_signer($message, $signature);
} catch (Throwable $e) {
error_log('wallet verify failed: ' . $e->getMessage());
json_response(['ok' => false, 'error' => 'Could not verify signature'], 400);
}
if ($recovered === null || !hash_equals($address, strtolower($recovered))) {
json_response(['ok' => false, 'error' => 'Invalid signature'], 401);
}
unset($_SESSION['wallet_login']);
session_regenerate_id(true);
$_SESSION['wallet_address'] = $address;
$_SESSION['authenticated_at'] = time();
json_response(['ok' => true, 'address' => $address]);Never trust an address just because the browser sent it. The signature is the only thing that proves the visitor controls that private key. Note the byte-length detail in the EIP-191 prefix: use the message length in bytes, not characters, or non-ASCII messages will fail to recover.
<figure class="my-6"> <img src="https://devloader.com/__l5e/assets-v1/5395ddf5-a84c-45db-8923-4ebf5eccc1cb/w3-3-verify.jpg" alt="Signed message card with nonce, timestamp and signature next to a PHP verification script and a verified shield" width="1600" height="900" class="rounded-lg w-full" loading="lazy" /> <figcaption class="text-sm text-muted-foreground mt-2">Server-side verification in PHP: recover the signer from the signature and compare it with the address bound to the stored nonce. © devloader.com</figcaption> </figure>
Step 8: Add a current-user endpoint
api/me.php lets the frontend check who is signed in:
<?php
require __DIR__ . '/../includes/bootstrap.php';
$address = $_SESSION['wallet_address'] ?? null;
json_response([
'ok' => true,
'authenticated' => is_string($address),
'address' => $address,
]);Any protected PHP page can then gate on the session:
<?php
require __DIR__ . '/../includes/bootstrap.php';
if (empty($_SESSION['wallet_address'])) {
header('Location: /');
exit;
}
echo 'Welcome wallet ' . htmlspecialchars($_SESSION['wallet_address'], ENT_QUOTES, 'UTF-8');Step 9: Add logout
<?php
require __DIR__ . '/../includes/bootstrap.php';
require_post();
$input = json_input();
verify_csrf($input);
unset($_SESSION['wallet_address'], $_SESSION['authenticated_at']);
session_regenerate_id(true);
json_response(['ok' => true]);Call this endpoint from the UI, then optionally ask AppKit to disconnect on the browser side with modal.disconnect().
Security checklist for production
Control — Why it matters
HTTPS everywhere — Protects the session cookie and the signed challenge in transit
Fresh nonce per attempt — Blocks replay of a captured signature
Short challenge expiry (5 min) — Limits the attack window if a challenge leaks
Exact message comparison — Prevents an attacker substituting a different signed payload
session_regenerate_id(true) after login — Prevents session fixation
CSRF token on POST endpoints — Stops cross-site forced logins and logouts
Rate limiting on nonce and verify — Blunts brute-force and signature-grinding attempts
Lowercase addresses for comparison — Avoids checksum-case mismatches; display EIP-55 checksummed
EIP-1271 support — Required for smart contract wallets and account abstraction
Never ask for a seed phrase or private key — no legitimate web3 login ever needs one. If you need a standardised challenge format, adopt Sign-In with Ethereum (EIP-4361) instead of a hand-rolled message.
<figure class="my-6"> <img src="https://devloader.com/__l5e/assets-v1/97aa5ab8-4729-4df5-8392-e39d635e2530/w3-4-security.jpg" alt="Web3 authentication security checklist with strong authentication, verified connections, session timeouts and key protection beside an HTTPS padlock" width="1600" height="900" class="rounded-lg w-full" loading="lazy" /> <figcaption class="text-sm text-muted-foreground mt-2">A production wallet connect PHP login is a security project first: HTTPS, short-lived nonces, session rotation and rate limiting. © devloader.com</figcaption> </figure>
Common errors and how to fix them
- Pitfall: "No EVM wallet provider found." Fix: the user has not completed the connection. Open the AppKit modal on the Connect view first, and only then request a signer.
- Pitfall: "Invalid project ID." Fix: confirm the ID in the Reown dashboard and add the exact origin (including subdomain and port) to the domain allowlist.
- Pitfall: "Signature verification failed." Fix: PHP must hash the exact string the wallet signed. A trailing newline, a re-generated timestamp, or a changed address case will break recovery.
- Pitfall: wallet connects but no PHP session appears. Fix: send
credentials: 'same-origin'on fetch, confirm cookies are not blocked, and check that thesecurecookie flag matches your scheme. - Pitfall: a smart contract wallet always fails. Fix: ECDSA recovery cannot validate contract signatures — add an EIP-1271
isValidSignaturecall against the wallet contract.
When to use wallet login vs. alternatives
Approach — Best for — Trade-off
Wallet signature login (this guide) — Token gating, NFT dashboards, crypto checkout — Users must own a wallet; recovery is their responsibility
Email + password / magic link — Broad consumer audiences — No on-chain identity; you own credential security
OAuth (Google, GitHub) — Fast onboarding for SaaS — No wallet address to gate on-chain assets
Wallet + linked account — Mixed audiences and billing — More code: two identities to reconcile in your database
Most production sites end up with the last row: wallet address stored alongside a traditional user record so support, invoicing, and email still work.
Where to go next
Once basic wallet login works, extend the same foundation with token-gated content, NFT ownership checks, DAO member dashboards, on-chain profile pages, crypto checkout flows, smart contract reads through ethers.js, and a database table linking wallet addresses to user profiles.
The architecture stays the same at every step: JavaScript connects and signs in the browser, PHP verifies and controls the server session. That separation is what keeps a web3 PHP example understandable, auditable, and maintainable as the site grows.
Related content
- Best HRIS systems for growing teams — how we evaluate vendor security and integration depth, the same lens to apply to wallet providers.
- Help desk solutions and ticketing systems — support tooling for the moment a user cannot access their gated account.
- CRM for service businesses — linking authenticated identities to customer records.
- Hire developers at Dev Loader — senior PHP and web3 engineers for authentication, smart contract integration, and audits.