Since PHP’s file system functions like rename(), copy() & … are not transactional, there’s no built-in rollback mechanism. I’m working on a PHP project where I need to perform multiple file system operations in sequence. The challenge is that if one operation fails, I want to rollback the previous ones to maintain consistency, similar to how database transactions work (especially when there are more than two operations involved, managing consistency becomes even more challenging. If one step fails, I need a way to undo all previous changes to avoid leaving the system in a partial or broken state). I’m looking for a reliable strategy to simulate transactional behavior for such operations.
Note : For simplicity, input validation, path sanitization, and security checks & … are omitted in this example.
<?php
$oldname = $_SESSION['oldname'];
$newname = $_POST['newname'];
$oldFile = './' . $oldname . '/' . $oldname . '.php';
$newFile = './' . $oldname . '/' . $newname . '.php';
$oldDir = './' . $oldname;
$newDir = './' . $newname;
if (file_exists($oldFile) && rename($oldFile, $newFile)) {
if (file_exists($oldDir) && rename($oldDir, $newDir)) {
//if (...) {
try {
$conn->beginTransaction();
$update1 = $conn->prepare("UPDATE table1 SET name=? WHERE name=?");
$update1->execute([$newname, $oldname]);
$update2 = $conn->prepare("UPDATE table2 SET name=? WHERE name=?");
$update2->execute([$newname, $oldname]);
//...
if ($update1->rowCount() > 0 && $update2->rowCount() > 0) {/* if ($update1->rowCount() > 0 && $update2->rowCount() > 0 && ...) { */
$conn->commit();
echo 'changed !';
} else {
$conn->rollBack();
echo 'didnt change !';
}
} catch (PDOException $e) {
$conn->rollBack();
echo 'didnt change !';
}
//}
} else {
echo 'didnt change !';
}
} else {
echo 'didnt change !';
}
async function changename() {
const newname = encodeURIComponent(document.getElementById('username').value);
const formData = 'newname=' + newname;
try {
const response = await fetch('../script.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData
});
if (!response.ok) {
throw new Error();
}
const responseText = await response.text();
//...
} catch (error) {
msg('unfortunately, something went wrong !');
}
}
document.getElementById("changename").addEventListener("click", changename);
Thanks in advance for any insights or suggestions !