File Manipulation PHP - Practical Example
Learn to create, edit and delete files with PHP
Download Complete ExampleHow Does File Manipulation Work in PHP?
Step 1: Create Files
PHP can create files automatically if they don't exist using different functions:
file_put_contents() - Simplest method
<?php
// Crea el archivo si no existe y escribe contenido
file_put_contents('mi_archivo.txt', 'Contenido inicial');
Advantages: A single function to create and write
Step 2: Read Files
To read the content of an existing file:
file_get_contents() - Read all the content
<?php
// Leer todo el contenido del archivo
$contenido = file_get_contents('mi_archivo.txt');
echo $contenido;
Step 3: Edit Files
PHP allows adding content without deleting what exists:
FILE_APPEND - Add at the end
<?php
// Añadir contenido al final del archivo
file_put_contents('mi_archivo.txt', "\nNueva línea", FILE_APPEND);
Step 4: Verify and Delete
It's important to check whether a file exists before operating on it:
file_exists() and unlink()
<?php
// Check existence before deletingif (file_exists('mi_archivo.txt')) {
unlink('mi_archivo.txt'); // Delete file echo "File deleted";
} else {
echo "The file does not exist";
}
Current File Status
File: archivo.php EXISTS
Size: 0 bytes
Last modified: 2026-09-10 16:12:04
Current content: The file is empty
Try the Code Live
Use the following controls to test the file manipulation functions in real time:
File Control Panel
Full Code Explained
File crear_editar_archivos.php - Main Code
<?php
// Procesar el formulario cuando se envíaif ($_SERVER['REQUEST_METHOD'] === 'POST') {
$opcion = $_POST['opcion'] ?? null;
$mensaje = $_POST['mensaje'] ?? '';
// Switch para manejar diferentes operaciones switch ($opcion) {
case 'crear':
// Crear archivo vacío file_put_contents('archivo.php', "");
$resultado = "✅ " . t('Archivo creado correctamente');
break;
case 'editar':
// Añadir contenido al archivo (FILE_APPEND evita sobrescribir) file_put_contents('archivo.php', $mensaje, FILE_APPEND);
$resultado = "✅ " . t('Texto añadido al archivo');
break;
case 'eliminar':
// Verificar que el archivo existe antes de eliminar if (file_exists('archivo.php')) {
unlink('archivo.php'); // Delete file $resultado = "✅ " . t('Archivo eliminado');
} else {
$resultado = "⚠️ " . t('El archivo no existe');
}
break;
case 'vaciar':
// Vaciar el contenido del archivo file_put_contents('archivo.php', '');
$resultado = "✅ " . t('Archivo vaciado');
break;
}
}
// Verificar estado actual para mostrar en la página$archivo_existe = file_exists('archivo.php');
$contenido_actual = $archivo_existe ? file_get_contents('archivo.php') : '';
?>
PHP Functions Key Used:
- file_put_contents(): Creates/writes files in a simple way
- FILE_APPEND: Constant to add content without deleting what exists
- file_exists(): Checks whether a file or directory exists
- unlink(): Deletes a file from the system
- file_get_contents(): Reads the full content of a file
- $_POST: Array que contiene datos enviados por formulario POST
Exercises to Practice
Exercise 1: Improved Validation
Modify the code to check whether the file exists before creating it.
Suggested solution:
case 'crear':
if (!file_exists('archivo.php')) {
file_put_contents('archivo.php', "");
$resultado = "✅ " . t('Archivo creado correctamente');
} else {
$resultado = "⚠️ " . t('El archivo ya existe');
}
break;
Exercise 2: Line Counter
Add a function that counts and shows how many lines the file has.
Suggested solution:
// Después de verificar que el archivo existe$lineas = file('archivo.php');
$numero_lineas = count($lineas);
echo "The file has $numero_lineas lines";
Exercise 3: Automatic Backup
Create an option that makes a backup before critical operations.
Suggested solution:
// Antes de eliminar o vaciarif (file_exists('archivo.php')) {
copy('archivo.php', 'backup_archivo_' . date('Y-m-d_H-i-s') . '.php');
}
Security Tips
⚠️ Important Precautions
- Never use this code in production without additional validation
- Validate and sanitize all user input
- Limit the permissions of created files
- Use secure directories outside the web root when possible
🔒 Best Practices
- Check existence before operating on files
- Handle errors try-catch when possible
- Operation logging for auditing
- File type validation allowed