FAUSTINE MWOYA November 12, 2025 1 min read

Jinsi ya Kutengeneza File Upload Form kwa PHP

File upload inaruhusu:

Users kupakia images, documents, au videos.

Kutengeneza systems kama profile picture uploads, document submissions, au media galleries.

Usalama:

Kagua file type na size.

Tumia unique file names ili kuepuka overwriting.

Store files kwenye folder salama.

⚙️ 2. HTML Form ya File Upload
<h2>Upload Your File</h2>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="uploaded_file" required><br><br>
<button type="submit" name="submit">Upload</button>
</form>

💡 Maelezo:

enctype="multipart/form-data" lazima iwe kwenye form.

name="uploaded_file" ni jina la input tunalotumia PHP script.

🧩 3. PHP Script ya Upload (upload.php)
<?php
if(isset($_POST['submit'])){
$target_dir = "uploads/";

// Create directory if not exists
if(!is_dir($target_dir)){
mkdir($target_dir, 0755, true);
}

$file_name = basename($_FILES['uploaded_file']['name']);
$target_file = $target_dir . time() . "_" . $file_name; // unique name

$file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$allowed_types = ['jpg','jpeg','png','gif','pdf','doc','docx'];

// Check file type
if(!in_array($file_type, $allowed_types)){
die("❌ Error: Only JPG, PNG, GIF, PDF, DOC allowed.");
}

// Check file size (5MB max)
if($_FILES['uploaded_file']['size'] > 5 * 1024 * 1024){
die("❌ Error: File too large. Max 5MB allowed.");
}

// Move uploaded file
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_file)){
echo "✅ File uploaded successfully: <a href='$target_file' target='_blank'>View File</a>";
} else {
echo "❌ Error uploading file.";
}
}
?>

💡 Maelezo:

time() . "_" . $file_name inazalisha unique filename ili kuepuka overwriting.

Kagua file type na size kwa security.

🧠 4. Vidokezo vya Usalama

Validate file type and size – avoid malicious files.

Rename uploaded files – prevent overwriting & code execution.

Store files outside web root (optional) – extra security.

Set proper folder permissions (0755 or stricter).

Avoid executing uploaded files – do not allow PHP scripts upload in public folder.

✅ 5. Hitimisho

File upload forms zinarahisisha user interaction na content management.

Best practices: validate type & size, unique filenames, secure storage.

Combining with authentication & CSRF tokens inaboresha security zaidi.

🔗 Tembelea:

👉 https://www.faulink.com/

Kwa mafunzo zaidi ya PHP, file handling, na secure web application development.

🚀 Unahitaji mfumo au website ya biashara?

Chagua huduma hapa chini kisha mteja bofya moja kwa moja kwenda kwenye ukurasa wa huduma au kuwasiliana nasi kwa WhatsApp.

Share this post

Comments

0
No comments yet. Be the first to comment.

Continue Reading

Subscribe

Get new updates

Jiunge upokee posts mpya, tutorials, na updates za mifumo moja kwa moja kwenye email yako.

Faulink Support