Jinsi ya Kutengeneza PDF Upload na Download Function
Users kupakia PDF files kwenye server.
Users kupakua files zilizopakiwa.
Management ya documents (reports, forms, manuals).
Usalama muhimu:
Validate file type (PDF pekee).
Validate file size.
Store files securely na rename ili kuepuka overwrite.
βοΈ 2. HTML Form ya PDF Upload
<h2>Upload PDF</h2>
<form action="upload_pdf.php" method="POST" enctype="multipart/form-data">
<input type="file" name="pdf_file" accept="application/pdf" required><br><br>
<button type="submit" name="submit">Upload PDF</button>
</form>
accept="application/pdf" inasaidia browser filter.
enctype="multipart/form-data" lazima iwe.
π§© 3. PHP Script ya PDF Upload (upload_pdf.php)
<?php
if(isset($_POST['submit'])){
$target_dir = "uploads/pdfs/";
if(!is_dir($target_dir)){
mkdir($target_dir, 0755, true);
}
$original_name = basename($_FILES['pdf_file']['name']);
$file_type = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
$file_size = $_FILES['pdf_file']['size'];
$target_file = $target_dir . time() . "_" . $original_name;
// Validate type
if($file_type !== 'pdf'){
die("β Error: Only PDF files are allowed.");
}
// Validate size (10MB max)
if($file_size > 10 * 1024 * 1024){
die("β Error: File too large. Max 10MB allowed.");
}
// Move file
if(move_uploaded_file($_FILES['pdf_file']['tmp_name'], $target_file)){
echo "β PDF uploaded successfully: <a href='$target_file' target='_blank'>View PDF</a>";
} else {
echo "β Error uploading PDF.";
}
}
?>
π‘ Maelezo:
time() . "_" . $original_name inazalisha unique filenames.
Validation inazuia files zisizo halali au kubwa kupakiwa.
π₯ 4. Download Function
<?php
// download.php?file=filename.pdf
if(isset($_GET['file'])){
$file = basename($_GET['file']);
$filepath = "uploads/pdfs/" . $file;
if(file_exists($filepath)){
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
} else {
die("β File not found.");
}
}
?>
Use basename() kuzuia directory traversal attacks.
Proper headers kuhakikisha browser inapakua file.
π 5. Vidokezo vya Usalama
Validate file type & size β prevent malicious files.
Rename files β avoid overwriting & predictable filenames.
Store outside web root optionally β extra security.
Limit folder permissions β usually 0755.
Use authentication β only authorized users can upload or download.
β 6. Hitimisho
PDF upload & download system ni muhimu kwa document management.
Combine na authentication & CSRF protection kwa secure workflow.
Best practices: validate type & size, unique filenames, secure folder, restrict access.
π Tembelea:
π https://www.faulink.com/
Kwa mafunzo zaidi ya PHP, file handling, na secure web applications.