0
0
PHPprogramming~10 mins

File upload security risks in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if the uploaded file is an image.

PHP
<?php
if(isset($_FILES['file'])) {
    $check = getimagesize($_FILES['file']['[1]']);
    if($check !== false) {
        echo "File is an image.";
    } else {
        echo "File is not an image.";
    }
}
?>
Drag options to blanks, or click blank then click option'
Atype
Bname
Ctmp_name
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'name' instead of 'tmp_name' causes getimagesize to fail.
Checking 'type' is not reliable for security.
2fill in blank
medium

Complete the code to allow only files with .jpg extension.

PHP
<?php
$filename = $_FILES['file']['name'];
$ext = strtolower(pathinfo($filename, PATHINFO_[1]));
if($ext === 'jpg') {
    echo "File extension allowed.";
} else {
    echo "File extension not allowed.";
}
?>
Drag options to blanks, or click blank then click option'
AEXT
BEXTENSION
CEXTNAME
DEXTENSION_NAME
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect constant names causes errors.
Not converting extension to lowercase can cause mismatches.
3fill in blank
hard

Fix the error in the code to prevent overwriting files by renaming the uploaded file.

PHP
<?php
$uploadDir = 'uploads/';
$filename = $_FILES['file']['name'];
$newName = $uploadDir . time() . '_' . [1];
move_uploaded_file($_FILES['file']['tmp_name'], $newName);
?>
Drag options to blanks, or click blank then click option'
Afilename
B$filename
C$_FILES['file']['name']
Dfile_name
Attempts:
3 left
💡 Hint
Common Mistakes
Using undefined variables causes errors.
Forgetting the $ sign before variable names.
4fill in blank
hard

Fill both blanks to check file size and reject files larger than 2MB.

PHP
<?php
if($_FILES['file']['[1]'] > [2]) {
    echo "File is too large.";
} else {
    echo "File size is acceptable.";
}
?>
Drag options to blanks, or click blank then click option'
Asize
B2000000
Ctmp_name
D5000000
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'tmp_name' instead of 'size'.
Using too large or too small size limits.
5fill in blank
hard

Fill all three blanks to safely move the uploaded file with a unique name and check for errors.

PHP
<?php
if($_FILES['file']['error'] === [1]) {
    $uploadDir = 'uploads/';
    $uniqueName = uniqid('', true) . '.' . pathinfo($_FILES['file']['name'], PATHINFO_[2]);
    $destination = $uploadDir . $uniqueName;
    if(move_uploaded_file($_FILES['file']['[3]'], $destination)) {
        echo "File uploaded successfully.";
    } else {
        echo "Failed to move uploaded file.";
    }
} else {
    echo "Upload error.";
}
?>
Drag options to blanks, or click blank then click option'
A0
BEXT
Ctmp_name
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong error codes.
Using wrong keys for file path or extension.