Im creating a image uploader, and i dont know how to do so only the filetype can be .jpg so im asking you, do you know it?
heres what i got so far:
<?php
session_start();
if($_SESSION['username']) {
$target_path = "users/$username/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
"has been uploaded";
header("Location: user.php");
} else{
echo "There was an error uploading the file, please try again!";
}
}
else {
echo "Only members can be here. Register <a href='index.php'>here</a>";
}
?>
And one more thing, how may i rename the uploaded file to : “profile.jpg” ?
There are some important things to consider here:
First of all, never rely on the file extension that was provided. I could upload a php file with the extension
.jpgif I wanted. Granted, I’d probably have to do some more to actually get it to execute as a php file on your server, but it certainly was not a valid image.If the upload was successful,
$_FILES[ 'uploadedfile' ][ 'type' ]will hold the mime-type that was provided by the request. However, this should also not be trusted, as this can be tampered with as well.A more reliable way to determine whether the uploaded file is actually an image of type jpeg is to use the function
getimagesize.getimagesize()will return false if it’s not a valid image and will return an array with information about the image, if it recognized the file as an image. Index2of the array will hold a value that corresponds with one of these constants that begin withIMAGETYPE_.This is somewhat of an old school method which, as far as I know, is reliable though.
I believe, depending on platform (Windows/*nix) and version (< 5.3, >= 5.3) there are more reliable ways to determine the actual mime-type of a file though. I’ll see what I can find for you about that later on.
edit:
I forgot about the renaming part.
Simply replace this:
… with this:
In other words, when you move the file with
move_uploaded_file()the second argument will be the new path (including the new file name).