How can PHP developers ensure that calendar events are stored in the correct directories, especially when trying to save files in higher level directories?

When saving calendar events in PHP, developers can ensure that the files are stored in the correct directories by properly sanitizing and validating user input to prevent directory traversal attacks. One way to do this is by using the basename() function to extract the filename and ensure it does not contain any path information. Additionally, developers should set the correct permissions on the directories where the files will be saved to prevent unauthorized access.

// Sanitize and validate user input for calendar event filename
$filename = basename($_POST['filename']);

// Define the directory where the files will be saved
$directory = '/path/to/calendar/events/';

// Check if the directory exists and is writable
if (is_dir($directory) && is_writable($directory)) {
    // Save the file in the specified directory
    file_put_contents($directory . $filename, $eventData);
    echo 'Calendar event saved successfully.';
} else {
    echo 'Error: Unable to save calendar event.';
}