惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
A
About on SuperTechFans
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
Vercel News
Vercel News
G
Google Developers Blog
J
Java Code Geeks
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
Cloudbric
Cloudbric
L
LINUX DO - 最新话题
MyScale Blog
MyScale Blog
H
Heimdal Security Blog
PCI Perspectives
PCI Perspectives
Attack and Defense Labs
Attack and Defense Labs
S
Security @ Cisco Blogs
Latest news
Latest news
I
Intezer
L
Lohrmann on Cybersecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
月光博客
月光博客
T
Threatpost
博客园 - 【当耐特】
S
Schneier on Security
P
Privacy International News Feed
G
GRAHAM CLULEY
T
Tenable Blog
AWS News Blog
AWS News Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
雷峰网
雷峰网
博客园 - Franky
Engineering at Meta
Engineering at Meta
美团技术团队
S
Secure Thoughts
T
Troy Hunt's Blog
Microsoft Security Blog
Microsoft Security Blog
SecWiki News
SecWiki News
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cisco Talos Blog
Cisco Talos Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Martin Fowler
Martin Fowler
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
10 PHP Bugs That Break Real Projects — And How to Fix Them (Part 2)
Bikki Singh · 2026-06-17 · via DEV Community

Every PHP developer has lived this moment. Code works perfectly on localhost. You push to production. Something silently breaks — no error, no log, just wrong output and a few wasted hours tracing the problem.

These are not textbook bugs. They come from real PHP projects — login systems, e-commerce stores, admin panels, school portals, and APIs. Bugs that pass code review because they look fine at first glance.

This is Part 2 covering Bug #11 through Bug #20. Each one includes the broken code, the correct fix, and a clear explanation of what actually goes wrong on a live server.


Bug #11 — Infinite Loop from a Missing Counter Increment

// ❌ Wrong
$i = 0;
while($i < 10) {
    echo $i;
    // forgot $i++
}

// ✅ Correct
$i = 0;
while($i < 10) {
    echo $i;
    $i++;
}

A forgotten $i++ locks up the PHP process entirely. On a shared server, this takes down the application for all users until the request times out. If the loop also queries a database, you are now firing thousands of repeated queries. One missing line — enormous consequences.


Bug #12 — String Comparison Failing Because of Letter Case

// ❌ Wrong — "admin" or "ADMIN" won't match
if($_POST['role'] == "Admin") { ... }

// ✅ Correct
if(strtolower($_POST['role']) == "admin") { ... }

PHP string comparisons are case-sensitive by default. Users submit "admin", "Admin", or "ADMIN" — all different strings to PHP. If your access control depends on this comparison, some users get incorrectly denied or incorrectly granted access. Normalize with strtolower() before comparing, and store values lowercase in the database too.


Bug #13 — Integer Cast Cutting Off Decimals in Division

// ❌ Wrong
$result = 5 / 2;
echo (int)$result; // Output: 2 (not 2.5)

// ✅ Correct
echo $result;                    // 2.5
echo number_format($result, 2); // 2.50

PHP returns 2.5 for 5 / 2 — that is correct. But (int) truncates, it does not round. So 2.9 becomes 2, 9.99 becomes 9. In billing systems, GST calculations, or cart totals, this produces real financial errors on every invoice. Use round() for rounding and number_format() for display output.


Bug #14 — JSON Decode Returning an Object Instead of an Array

// ❌ Wrong
$data = json_decode($jsonString);
echo $data['name']; // Fatal error: Cannot use object as array

// ✅ Correct
$data = json_decode($jsonString, true);
echo $data['name']; // Works

// Also add error checking
if(json_last_error() !== JSON_ERROR_NONE) {
    error_log('JSON decode failed: ' . json_last_error_msg());
}

By default json_decode() returns a stdClass object. You need -> notation for objects, [] for arrays — mixing them causes a fatal error. Pass true as the second argument to always get an associative array. API responses can also arrive malformed, so always check json_last_error() after decoding.


Bug #15 — Printing User Input Directly to HTML (XSS Vulnerability)

// ❌ Wrong
echo "Hello " . $_GET['name'];

// ✅ Correct
echo "Hello " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');

Echoing $_GET['name'] unescaped means an attacker can inject a <script> tag into your page. That script executes in every visitor's browser. A URL like ?name=<script>alert(document.cookie)</script> is all it takes.

htmlspecialchars() converts <, >, ", ', and & into safe HTML entities. Always use ENT_QUOTES and 'UTF-8'. This is non-negotiable — never print user input to HTML without it.


Bug #16 — Relative Include Paths Breaking on Different Servers

// ❌ Wrong — works locally, breaks on server
include("includes/header.php");

// ✅ Correct — always works
include(__DIR__ . "/includes/header.php");

Relative paths resolve based on the current working directory — not the file's own directory. On localhost with XAMPP this might work. On a live Apache or Nginx server with different virtual host settings, the same path fails silently with a "No such file or directory" error.

__DIR__ is a PHP magic constant that always returns the absolute path of the current file's directory, regardless of where the script is called from.


Bug #17 — Duplicate Database Entries from Form Resubmission

// ❌ Wrong — direct insert, no duplicate check
$sql = "INSERT INTO users (email) VALUES ('$email')";

// ✅ Correct — check first, then insert
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);

if(!$stmt->fetch()) {
    $insert = $pdo->prepare("INSERT INTO users (email) VALUES (?)");
    $insert->execute([$email]);
}

Two real causes: users double-clicking the submit button on slow connections, and browsers resubmitting POST data on page refresh. Fix requires two layers — a PHP-side check before inserting, plus a database-level UNIQUE constraint so simultaneous requests cannot both slip through:

ALTER TABLE users ADD UNIQUE (email);

After a successful submission, always redirect: header("Location: success.php"); exit;


Bug #18 — array_merge Resetting Numeric Keys

$a = [1 => "one", 2 => "two"];
$b = [2 => "TWO", 3 => "three"];

// ❌ Wrong — keys reset to 0, 1, 2, 3
print_r(array_merge($a, $b));

// ✅ Correct — preserve keys (left side wins on conflict)
$result = $a + $b;

// ✅ Or — right side overwrites left on conflict
$result = array_replace($a, $b);

array_merge() reindexes all numeric keys from zero. If you are merging config arrays or working with database results keyed by IDs, this silently destroys your key structure without any warning or error. The + operator preserves keys; array_replace() preserves keys and lets the right array win on conflicts.


Bug #19 — No Error Logging Set Up in Production

// ❌ Wrong — errors disappear completely
// php.ini: display_errors = Off
// (no error_log path configured)

// ✅ Correct

// Development:
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Production:
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/var/log/php/error.log');
error_reporting(E_ALL);

Turning off display_errors in production is correct — you do not want stack traces visible to users or attackers. But many developers stop there. The result: errors happen silently, users complain, and you have zero record of what broke or when. Always configure log_errors and set an error_log path. Tools like Sentry or Bugsnag give you real-time alerts with full stack traces — the professional standard for production monitoring.


Bug #20 — foreach Not Modifying the Original Array

// ❌ Wrong — only modifies a copy
$prices = [100, 200, 300];
foreach($prices as $price) {
    $price = $price * 1.18;
}
print_r($prices); // Still [100, 200, 300]

// ✅ Correct — reference with &
foreach($prices as &$price) {
    $price = $price * 1.18;
}
unset($price); // ⚠️ Critical — must unset after the loop
print_r($prices); // [118, 236, 354]

// ✅ Alternative — array_map (no reference needed)
$prices = array_map(fn($p) => $p * 1.18, $prices);

foreach works on a copy of each element by default. The & makes it a reference to the actual array element. The unset($price) after the loop is not optional — after the loop, $price still points to the last element. Any later use of that variable name in the same scope will silently corrupt your array. This bug can live in a codebase for months before anyone notices.


Quick Reference

Bug Issue Risk
#11 Infinite loop Server crash
#12 Case-sensitive comparison Access control failure
#13 Decimal truncated to integer Financial error
#14 JSON returns object not array Fatal error
#15 XSS vulnerability Security breach
#16 Include path breaks on server Fatal include error
#17 Duplicate database records Data corruption
#18 Array keys reset after merge Lost key structure
#19 Errors invisible in production Silent failures
#20 Original array not modified Wrong data processed

What These Bugs Have in Common

Most of them do not throw errors. PHP's forgiving nature means the code runs — it just does not do the right thing. No warning. No crash. Just silent wrong behavior that costs hours to trace. That is what makes them dangerous in production.

The developers who catch these early are the ones who have been burned by them before, or who studied real-world bugs before getting burned. Syntax knowledge is not enough — understanding failure modes is what separates junior code from production-ready code.


Read the full article with detailed explanations:
👉 10 PHP Bugs That Break Real Projects — And How to Fix Them (Part 2)
2

Part 3 covers bugs #21–30 — session handling, file upload security, date/timezone bugs, and database connection errors.