What are the best practices for handling file uploads and temporary directories in PHP to ensure successful previews?

When handling file uploads in PHP, it is important to move uploaded files to a temporary directory to prevent direct access and ensure security. To successfully display previews of uploaded files, you can create a temporary directory, move the uploaded file to this directory, and then generate a preview of the file using appropriate PHP functions or libraries.

// Create a temporary directory for file uploads
$tempDir = 'uploads/temp/';
if (!file_exists($tempDir)) {
    mkdir($tempDir, 0777, true);
}

// Move the uploaded file to the temporary directory
$uploadedFile = $_FILES['file']['tmp_name'];
$targetFile = $tempDir . $_FILES['file']['name'];
move_uploaded_file($uploadedFile, $targetFile);

// Generate a preview of the uploaded file (example for images)
if (pathinfo($targetFile, PATHINFO_EXTENSION) == 'jpg' || pathinfo($targetFile, PATHINFO_EXTENSION) == 'png') {
    echo '<img src="' . $targetFile . '" alt="Preview">';
}