PHP Error Control Operator (@)
What is PHP Error Control Operator (@)?
In PHP, the Error Control Operator (@) is a special symbol that is used to suppress error messages generated by an expression.
Whenever an error occurs in PHP — for example, trying to open a missing file or accessing an undefined variable — PHP normally displays a warning or notice.
But if you place @ before the expression, PHP hides that error message.
Syntax
@expression;
Where:
@tells PHP to suppress any error message generated by that expression.
Example 1: Suppressing an Undefined Variable Error
<?php
// Without @ operator
echo $name; // Warning: Undefined variable $name
?>
With Error Control Operator:
<?php
// Using @ to suppress the error
echo @$name; // No warning shown
?>
Explanation:
The variable
$nameis not defined.Normally, PHP would display a “Notice: Undefined variable” message.
By using
@, PHP hides the error — keeping the page output clean.
Example 2: Suppressing File Handling Errors
<?php
$file = @fopen("non_existing_file.txt", "r");
if (!$file) {
echo "File could not be opened!";
}
?>
Output:
File could not be opened! Explanation:
Normally,
fopen()would display a warning if the file doesn’t exist.The
@operator suppresses that warning.You can still handle the error manually with a custom message.
Example 3: Using @ with Database Connection
<?php
$conn = @mysqli_connect("localhost", "root", "wrong_password", "testdb");
if (!$conn) {
echo "Database connection failed!";
}
?>
Explanation:
The
@hides PHP’s warning message about connection failure.You show a user-friendly message instead.
Important Note:
Although the @ operator hides errors, the suppressed errors can still be retrieved using the error_get_last() function.
Example:
<?php
@file_get_contents("missingfile.txt");
print_r(error_get_last());
?>
Output:
Array ( [type] => 2 [message] => file_get_contents(missingfile.txt): Failed to open stream [file] => index.php [line] => 2 )When to Use and When to Avoid @
Use @ When:
You expect an error but don’t want to show it to the user.
You plan to handle the error manually (like using
ifconditions).Working with functions that may fail due to user input or external systems.
Avoid @ When:
Debugging — it hides useful error details.
In production environments without proper logging.
On performance-sensitive pages (since
@can slow down execution slightly).
Best Practice
Instead of depending heavily on @, use:
try...catchblocks for exceptions.Custom error handlers (
set_error_handler()).Error logging to track problems without showing them to users.
Real-World Example
Imagine you’re building a web application where users upload files.
If the file doesn’t exist, you don’t want PHP to throw a scary warning — instead, you want to show a simple message.
<?php
$profilePic = @file_get_contents("uploads/user123.jpg");
if ($profilePic === false) {
echo "No profile picture found!";
}
?>