Reputation: 17
I have a script to upload a image.. It works fine and gives the image the name image1.png.
The problem i'm facing now is that I can only upload png images and I need to be able to upload all kinds of images. I know I have to get the ext. but I can't get it to work.
Here is the script
<?php $target_dir = "images2/";
$target_file = $target_dir . ("image1.png");
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
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;
}
} // Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";}}
?>
Upvotes: 0
Views: 366
Reputation: 66
You could use the extension of uploaded file for the target file:
The $target_file variable doesn't contain the extension:
$target_file = $target_dir . ("image1.");
It gets added at the end:
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file.$imageFileType)) {
Upvotes: 0
Reputation: 34416
Might be better to test to see if the image extension is in an array. Shorter code, less problems:
$imgExt = array('jpg','png','jpeg','gif');
if(!in_array($imageFileType, $imgExt)) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
Upvotes: 1
Reputation: 357
Update this line:
if($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg" || $imageFileType == "gif" ) {
And remove $uploadOk
Upvotes: 0
Reputation: 1290
in that if condition u can use only the following condition
if($imageFileType != "png" ) {
echo "</br>Sorry, only PNG files are allowed.";
$uploadOk = 0; }
Upvotes: 0
Reputation: 965
Remove below piece of code from your uploading script
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
and set $uploadOk=1;
or no need to set it.
Might be it will help you.
Upvotes: 0