File Upload
File Upload
</body>
</html>
Upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
• You will need to create a new directory called
"uploads" in the directory where "upload.php"
file resides. The uploaded files will be saved
there.
Check if File Already Exist
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
• Limit File Size
$target_dir = "uploads/";
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
$uploadOk = 1;
} else {
•
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
</body>
</html>
• <?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str,
FILTER_SANITIZE_STRING);
echo $newstr;
?>
Validating integer
• <?php
$int = 100;
if (filter_var($int,
FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "ma
x_range"=>$max))) === false) {
echo("Variable value is not within the legal range");
} else {
echo("Variable value is within the legal range");
}
?>
Validate IPv6 Address
• <?php
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";
if (!filter_var($ip, FILTER_VALIDATE_IP,
FILTER_FLAG_IPV6) === false) {
echo("$ip is a valid IPv6 address");
} else {
echo("$ip is not a valid IPv6 address");
}
?>
Validate URL - Must Contain QueryString
• <?php
$url = "https://www.w3schools.com";
if (!filter_var($url, FILTER_VALIDATE_URL,
FILTER_FLAG_QUERY_REQUIRED) === false) {
echo("$url is a valid URL with a query string");
} else {
echo("$url is not a valid URL with a query string");
}
?>
Remove Characters With ASCII Value > 127
• <?php
$str = "<h1>Hello WorldÆØÅ!</h1>";
$newstr = filter_var($str,
FILTER_SANITIZE_STRING,
FILTER_FLAG_STRIP_HIGH);
echo $newstr;
?>