i am trying to match a image/type of a file upload in PHP for validation:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$data = [
// Other POST Variables
'uploadimageType' => $_FILES['uploadimage']['type']
];
if((strcmp($data['uploadimageType'],'image/jpeg')!=0) || (strcmp($data['uploadimageType'],'image/png')!=0) || (strcmp($data['uploadimageType'],'image/gif')!=0) ) {
echo 'Invalid Image format';
}else{
echo 'Valid';
}
?>
The HTML used for submit:
<form action="<?php echo URLROOT; ?>/users/upload" method="post" enctype="multipart/form-data">
<!-- Other Input Tags -->
<div class="form-group">
<label for="uploadimage">Upload Image <sup>*</sup></label>
<input type="file" name="uploadimage" class="form-control-file <?php echo (!empty($data['uploadimage_err'])) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo $data['uploadimage_err']; ?></span>
</div>
<!-- Submit Button -->
</form>
Now, the problem is that even if I try to upload an image(.jpg, .png, .gif) it shows Invalid Image Format. Is there anything that I am missing here because this seems to be very simple yet complicated. Any suggestions would help.
Try this
$allowed_mime_type_arr = array('image/gif','image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['uploadimage']['name']);
if(in_array($mime, $allowed_mime_type_arr)){
echo 'Valid Image format';
}else{
echo 'Invalid Image format';
}
This will Works by Change if Condition.
$data = [
'uploadimageType' => 'image/jpeg'
];
if((strcmp($data['uploadimageType'],'image/jpeg')!=0) && (strcmp($data['uploadimageType'],'image/png')!=0) && (strcmp($data['uploadimageType'],'image/gif')!=0) ) {
echo 'Invalid Image format';
}
else {
echo 'Valid';
}
if($_SERVER['REQUEST_METHOD'] == "POST") {
$data = ['uploadimageType' => strtolower(pathinfo($_FILES['uploadimage']['name'],PATHINFO_EXTENSION))];
$ext = array("png","jpg","jpeg");
if(!in_array($data['uploadimageType'],$ext) ) {
echo 'Invalid Image format';
}else {
echo 'Valid';
}
}
Related
I am on Ubuntu. I am trying to take user file upload of small images. I checked the $_FILES it's filled with data. I tried to debug the move command but it doesnot echo anything.
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
//Now handle everything
if(isset($_POST["submit"])) {
print_r($_FILES);
//Store the image
if(!empty($_FILES['uploaded_file']))
{
$path = "/neel/public/img/";
$path = $path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo 'Its working';
} else{
echo 'I am done!!!';
die();
}
}
createnewEvent($conn);
header('Location:/neel/index.php');
}
}
You can check if the file exists by checking its name.
if(!empty($_FILES['file']['name']))
Where file is the name of input field for file.
P. G above here is correct.
Instead of checking, if $_POST['submit']
You should check this:
if(isset($_FILES['uploaded_file']['name']))
Try this code it's a complete sign up form with PHP , Bootstrap
HTML
<div class="container">
<div class="row">
<br>
<h1 class="text-center">Create new account</h1>
<br>
<div class="col-lg-4 col-md-6 col-sm-12">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="name" placeholder="Your Name">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="Password">
</div>
<div class="form-group text-center">
<div class='file-input'>
<input type='file' name="profile-img">
<span class='button label' data-js-label>Choose your profile image</span>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success form-control form-control-lg" name="signup" value="Signup">
</div>
</form>
</div>
</div>
</div>
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors;
if (empty($_POST['name'])) {
$errors[] = "Name field is empty";
}
if (empty($_POST['username'])) {
$errors[] = "Username field is empty";
}
if (empty($_POST['password'])) {
$errors[] = "Password field is empty";
}
if (empty($_FILES['profile-img'])) {
$errors[] = "You should upload profile image";
} else{
$img = $_FILES['profile-img'];
$ext = end(explode('.', $img['name']));
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 4; //MegaBytes
if (! in_array($ext, $allowed_extensions)) {
$errors[] = "Please , Choose a valid image";
}
$img_size = $img['size'] / 1000000; // By Megabyte
if ($img_size > $max_size) {
$errors[] = "This picture is so large";
}
}
if (!empty($errors)) {
echo '<div class="container">';
foreach ($errors as $error) {
echo '
<div class="alert alert-danger" role="alert">
' . $error . '
</div>
';
}
echo "</div>";
} else {
$username = filter_var(htmlentities(trim($_POST['username'])), FILTER_SANITIZE_STRING);
$name = filter_var(htmlentities(trim($_POST['name'])), FILTER_SANITIZE_STRING);
$password = sha1(filter_var(htmlentities(trim($_POST['password'])), FILTER_SANITIZE_STRING));
// Profile Picture :-
$imgname = uniqid(uniqid()) . #date("Y-m-d") . "." . $ext;
$target_bath = "uploads/imgs/";
$target_bath = $target_bath . basename($imgname);
$orginal_img = $img['tmp_name'];
if (move_uploaded_file($orginal_img, $target_bath)) {
$sql = "INSERT INTO users(name, username, password,profile_picture, r_d) VALUES ('$name', '$username', '$password', '$target_bath', NOW())";
$result = mysqli_query($conn, $sql);
header('location: ./login.php');
}
}
}
The script you've shown shown will only "not echo anything" if $_SERVER['REQUEST_METHOD'] is not "POST". Assuming your description of events is accurate, then the problem is in the form #halojoy has asked that you show here.
I do hope that you are not redirecting the script back to itself. Also you shouldn't attempt to do a redirect after an echo.
i wanted to upload the mp3 file to the related folder name /uploads/ inside my project folder. But something not working correctly in php. Image file are uploading without any error but when i tried to upload the mp3 file its not working.
Here is my html form
<form action="act_songs.php" method="post" enctype="multipart/form-data">
<?php
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
<p>
<label>Song Title</label>
<input type="text" name="sng-title">
</p>
<p>
<label>Song Name</label>
<input type="file" name="mp3" accept="audio/*" runat="server">
</p>
<p>
<input type="submit" name="add-song" value="ADD">
</p>
</form>
And here is my php code
if (isset($_POST['add-song'])) {
$title = $_POST['sng-title'];
$audio = $_FILES['mp3']['name'];
$audio_type = $_FILES['mp3']['type'];
$audio_size = $_FILES['mp3']['size'];
$tmp_location = $_FILES['mp3']['tmp_name'];
$audio_url = "../uploads/".$audio;
if ($type == '.mp3' || $type == '.wav') {
if ($size <= 5000) {
move_uploaded_file($tmp_location, $audio_url);
}
}
if (!empty($title)) {
$sql = "insert into `tbl_songs` (`title`,`songs`) values ('$title','$audio_url')";
$sql_run = mysql_query($sql);
if ($sql_run) {
$_SESSION['msg'] = "<div class='alert'>Record Saved</div>";
header('location:songs.php');
}
else{
$_SESSION['msg'] = "<div class='alert'>Record Cannot Saved</div>";
header('location:add-songs.php?invalid');
}
}
else{
$_SESSION['msg'] = "<div class='alert'>Title Must be requiired.</div>";
header('location:add-songs.php?invalid');
}
}
What is the problem i am unable to debug the problem. If anybody have solution then place your answer
When uploading images from my website into the designated folder I can see the file in the directory, but cannot open the files nor display them on the webpage.
EDIT This is an issue with my permissions, when trying to open the file in various programs I am receiving permission denied errors.
include('header.php');
$message = "";
$user_id=$_SESSION['user']['user_id'];
$images = getImageCount($user_id);
if(!isset($_SESSION['user']))
{
$_SESSION['message'] = "You must be logged in to manage your images";
header("Location:login.php");
}else if($_SESSION['user']['type'] == INCOMPLETE_USER)
{
$_SESSION['message'] = "You must create a profile to upload images";
header("Location:create_profile.php");
}else if($_SESSION['user']['type'] == DISABLED_CLIENT)
{
$_SESSION['message'] = "Your profile has been disabled";
header("Location:login.php");
}else if($_SERVER['REQUEST_METHOD'] == 'POST')
{
print_r($_FILES);
$user_folder="./profiles/". $user_id;
echo "test";
$file=$_FILES['uploadfile'];
//go to the profile table an SELEECT images FROM profiles WHERE user_id =
if ($images <= MAXIMUM_IMAGES)
{
if ($file['error']!=0)
{
$_SESSION['message']= "Upload Failed!";
}
else if ($_FILES['uploadfile']['type'] != "image/pjpeg" && $_FILES['uploadfile']['type'] != "image/jpeg")
{
$message = "Error! image file must be a'". DEFAULT_FILE_TYPE."'";
}
else if ($file['size'] > MAX_FILE_SIZE)
{
$message = "Error! File must be smaller than '".MAX_FILE_SIZE."' bytes";
}
else
{
$directory = "./profiles/".$user_id;
echo $directory;
//echo $user_folder;
if (!is_dir("profiles/".$user_id))
{
mkdir("profiles/".$user_id, intval( 0777, 8 ), true);
echo 2;
}
$temp_name=$file["tmp_name"];
$new_count = $images + 1;
$file_name=$user_id."_".$new_count;
echo $file_name;
$full_file_name ="profiles/".$user_id."/".$file_name. ".jpg";
move_uploaded_file($temp_name ,$full_file_name);
pg_execute($conn,"update_images",array ($new_count,$_SESSION['user']['user_id']));
}
}
else
{
$message = "Error! no more than " .MAXIMUM_IMAGES . "picture can be uploaded";
}
}
else if (!empty($_POST['submit_changes']))
{
echo "Fail";
$images= $_SESSION['profile']['images'];
}
?>
<form id="uploadform" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php echo $message; ?>
<strong>Select image for upload: </strong>
<input name="uploadfile" type="file" id="uploadfile" />
<input type="submit" value="Upload New Image" />
<img src="profiles/sault/saultl_4.jpg" alt = "Sault"/>
</form>
<?php
include('footer.php');
?>
I think you did not set the right permission to the folder, just try it in this way:
if (!is_dir("profiles/".$user_id))
{
mkdir("profiles/".$user_id, intval( 0777, 8 ), true);
}
If this do not work we would need some more detailed information in order to help you!
I'm sure there is a simple solution that I just can't see.
I have a form for uploading stuff.
When the script completes it uses Header('Location: admin.php?success') and a if($_GET['success']) { echo WOOHOO SUCCESS } type message before the rest of the script is run.
The problem with this is that is you want to upload 2 files at once you can't because the first part of the script is executed and nothing else. I then considered using a boolean value to set true or false and display a message from that but that also failed.
I'd like to be able to upload several files in succession and receive a success message for each one.
Many thanks.
relevant PHP:
if(isset($_GET['success']) && empty($_GET['success'])){
echo '<h2>File Upload Successful! Whoop!</h2>';
} else{
if(empty($_POST) === false){
//check that a file has been uploaded
if(isset($_FILES['myTrainingFile']) && !empty($_FILES['myTrainingFile']['tmp_name'])){
file stuff...
if(in_array($fileExt, $blacklist) === true){
$errors[] = "File type not allowed";
}
}
if(empty($errors) === true){
//run update
move file stuff...
}
}
$comments = htmlentities(trim($_POST['comments']));
$category = htmlentities(trim($_POST['category']));
$training->uploadDocument($fileName, $category, $comments);
header('Location: admin.php?success');
exit();
} else if (empty($errors) === false) {
//header('Location: messageUser.php?msg=' .implode($errors));
echo '<p>' . implode('</p><p>', $errors) . '</p>';
}}
}
?>
You need to loop through the $_FILES super-global array and then upload each file.
Here's a working example to give you a better idea.
<?php
$upload_dir= './uploads';
$num_uploads = 2;
$max_file_size = 51200;
$ini_max = str_replace('M', '', ini_get('upload_max_filesize'));
$upload_max = $ini_max * 1024;
$msg = 'Please select files for uploading';
$messages = array();
if(isset($_FILES['userfile']['tmp_name']))
{
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
elseif($_FILES['userfile']['size'][$i] > $upload_max)
{
$messages[] = "File size exceeds $upload_max php.ini limit";
}
elseif($_FILES['userfile']['size'][$i] > $max_file_size)
{
$messages[] = "File size exceeds $max_file_size limit";
}
else
{
if(#copy($_FILES['userfile']['tmp_name'][$i],$upload_dir.'/'.$_FILES['userfile']['name'][$i]))
{
$messages[] = $_FILES['userfile']['name'][$i].' uploaded';
}
else
{
$messages[] = 'Uploading '.$_FILES['userfile']['name'][$i].' Failed';
}
}
}
}
?>
<html>
<head>
<title>Multiple File Upload</title>
</head>
<body>
<h3><?php echo $msg; ?></h3>
<p>
<?php
if(sizeof($messages) != 0)
{
foreach($messages as $err)
{
echo $err.'<br />';
}
}
?>
</p>
<form enctype="multipart/form-data" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
<?php
$num = 0;
while($num < $num_uploads)
{
echo '<div><input name="userfile[]" type="file" /></div>';
$num++;
}
?>
<input type="submit" value="Upload" />
</form>
</body>
</html>
Hope this helps!
So I have this issue with my errors not showing up when I test to see if they are showing up when they are supposed to. When I select an file, my script is only supposed to accept image files as well as nothing bigger than 2MB. I haven't written the part that actually uploads the images to the database and the albums that I created but regardless, I should get some sort of error instead of just passing anything through..I need help! Thanks in advance!
Here is the file that processes the image and will eventually upload:
<?php
include 'init.php';
if(!logged_in()){
header('Location: index.php');
exit();
}
include 'template/header.php';
?>
<h3>Upload Image</h3>
<?php
if(isset($FILES['image'], $_POST['album_id'])){
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$image_ext = strtolower(end(explode('.', $image_name)));
$album_id = $_POST['album_id'];
$errors = array();
if (empty($image_name) || empty($album_id)){
$errors[] = 'Something is missing';
} else {
if(in_array($image_ext, $allowed_ext) === false){
$errors[] = 'File type not allowed';
}
if($image_size > 2097152){
$errors[] = 'Maximum file size is 2MB';
}
if(album_check($album_id) === false){
$errors[] = 'Couldn\'t upload to that album';
}
}
if(!empty($errors)){
foreach ($errors as $error){
echo $error, '<br />';
}
} else {
// upload image
}
}
$albums = get_albums();
if(empty($albums)){
echo '<p>You don\'t have any albums. Create an album</p>';
} else {
?>
<form action="" method="post" enctype="multipart/form-data">
<p>Choose a file:<br /><input type="file" name="image" /></p>
<p>
Choose an album:<br />
<select name="album_id">
<?php
foreach ($albums as $album){
echo '<option value="', $album['id'], '">', $album['name'], '</option>';
}
?>
</select>
</p>
<p><input type="submit" value="Upload" /></p>
</form>
<?php
}
include 'template/footer.php';
?>
I think my issue is around my errors but I'm not sure, again any help is appreciated! Thanks!
-TechGuy24
Change if(isset($FILES['image'], $_POST['album_id'])){
To if(isset($_FILES['image'], $_POST['album_id'])){