Backend Development 9 min read

How to Build a Secure Online Voting System with PHP

This article explains how to design and implement a PHP-based online voting system with user registration, login, vote submission, and anti‑cheating measures such as session validation, duplicate‑vote checks, transactions, captchas, and vote‑limit enforcement.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Build a Secure Online Voting System with PHP

Online voting systems are increasingly common but face challenges like vote‑brushing and cheating due to internet anonymity and data volatility. This guide shows how to create a PHP‑based voting platform and implement safeguards to ensure accurate and fair results.

System Design

1. Database Design

A MySQL table named votes stores voting data with the following fields:

id – auto‑increment primary key

option – name of the voting option

count – number of votes for the option

2. User Registration and Login

To guarantee vote authenticity, a user registration and login system is required. Users create accounts via a registration page and log in through a login page.

Registration page markup:

<form action="register.php" method="post">
    <label for="username">用户名:</label>
    <input type="text" name="username" id="username" required>
    <label for="password">密码:</label>
    <input type="password" name="password" id="password" required>
    <input type="submit" value="注册">
</form>

PHP code that inserts the new user into the users table:

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydatabase";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }

$username = $_POST["username"];
$password = $_POST["password"];

$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
if ($conn->query($sql) === TRUE) { echo "注册成功"; }
else { echo "Error: " . $sql . "<br>" . $conn->error; }

$conn->close();
?&gt;

Login page markup:

&lt;form action="login.php" method="post"&gt;
    &lt;label for="username"&gt;用户名:&lt;/label&gt;
    &lt;input type="text" name="username" id="username" required&gt;
    &lt;label for="password"&gt;密码:&lt;/label&gt;
    &lt;input type="password" name="password" id="password" required&gt;
    &lt;input type="submit" value="登录"&gt;
&lt;/form&gt;

PHP code that validates credentials and starts a session:

&lt;?php
session_start();
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydatabase";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }

$username = $_POST["username"];
$password = $_POST["password"];

$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $_SESSION["username"] = $username;
    header("Location: vote.php");
} else {
    echo "登录失败";
}

$conn->close();
?&gt;

3. Voting Page

The voting page displays available options and a submit button. Only logged‑in users may vote.

&lt;?php
session_start();
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydatabase";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }

if (!isset($_SESSION["username"])) { echo "请先登录"; exit; }

$sql = "SELECT * FROM votes";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<input type='radio' name='option' value='" . $row["id"] . "'>" . $row["option"] . "<br>";
    }
    echo "<input type='submit' value='投票'>";
} else {
    echo "没有可供投票的选项";
}

$conn->close();
?&gt;

4. Voting Logic

When a user submits a vote, the script checks login status, prevents duplicate voting, updates the vote count, and reports success or failure.

&lt;?php
session_start();
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydatabase";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); }

if (!isset($_SESSION["username"])) { echo "请先登录"; exit; }

$optionId = $_POST["option"];
$sql = "SELECT * FROM votes WHERE id = '$optionId'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $newCount = $row["count"] + 1;
    $updateSql = "UPDATE votes SET count = '$newCount' WHERE id = '$optionId'";
    if ($conn->query($updateSql) === TRUE) {
        echo "投票成功";
    } else {
        echo "投票失败";
    }
} else {
    echo "无效的选项";
}

$conn->close();
?&gt;

Anti‑Cheating Measures

Use sessions to ensure only logged‑in users can vote.

Check whether a user has already voted and block duplicate votes.

Employ database transactions to maintain consistency when updating vote counts.

Integrate a CAPTCHA to stop automated bots from voting.

Limit the number of votes per user by recording vote counts in the database.

Conclusion

Building an online voting system requires careful handling of security and data integrity. By using PHP, MySQL, session management, duplicate‑vote checks, transactions, CAPTCHAs, and vote‑limit controls, developers can create a robust platform that mitigates vote‑brushing and cheating.

Backend Developmentsecuritycaptchasessiononline voting
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.