PHP success on file upload - php

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!

Related

PHP Image Type Validation

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';
}
}

Unable to upload mp3 file

I have already change php.in config where have set max_size = 256M but it still does not allow me to upload. I dont know where i am going wrong.....i am able to upload image file, pdf file ,documentary file but not mp3. php.in settings didnt work for me...please anybody can guide me. Below is my php code
Thanks in advance!
<?php
//Concept of file upload
if(isset($_POST['submit']))
{
$file = $_FILES['files']['name'];
$type = $_FILES['files']['type'];
$file_tmp = $_FILES['files']['tmp_name'];
$size = $_FILES['files']['size'];
$file_err = $_FILES['files']['error'];
if($size!=null)
{
if($_FILES['files']['size'] <= 10000000 && $_FILES['files']['type'] == "audio/mpeg")
{
$path = "D:/";
$path = $path.basename($file);
if(!is_uploaded_file($file))
{
$flag = move_uploaded_file($file_tmp, $path);
if($flag == true)
{
echo "Moved Success";
}
else
{
echo "Some problem";
}
}
else
{
echo "Already Uploaded";
}
}
else
{
echo "Not audio file";
}
}
else if($size > 10000000)
{
echo "Size exceeded";
}
else if($size == null)
{
echo "Please select a file";
}
else
{
echo "Error".$file_err;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="basic.php" method="post" enctype="multipart/form-data">
<input type="file" name="files"/>
<input type="submit" value="upload" name="submit"/>
</form>
</body>
</html>
If you are trying to upload an mp3 file, the type of the $_FILES must be
&& $_FILES["file"]["type"] == "audio/mp3"
not
&& $_FILES['files']['type'] == "audio/mpeg"

Cannot interact with uploaded images from my website

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!

passing variable value php

there is 2 pages , one is the main and the other included to it
the main page
<?php
$var_value = 7;
$_SESSION['varname'] = $var_value;
include 'upload_image.php';
?>
and the included page
<?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['image_n'], $_POST['image_description'])) {
$image_name = $_FILES['image']['name'];
$bytes = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];
$image_n = $_POST['image_n'];
$image_description = $_POST['image_description'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif', 'rar', 'pdf');
//$image_ext = strtolower(end(explode('.', $image_name)));
$image_ext = pathinfo($image_name, PATHINFO_EXTENSION);
$album_id = $_SESSION['varname'];
$errors = array();
if (empty($image_name) || empty($album_id) || empty($image_n) || empty($image_description)) {
$errors[] = 'Something is missing';
} else {
if (strlen($album_name) > 55 || strlen($album_description) > 255) {
$errors[] = 'One or more fields contains too many characters';
}
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 {
$byte = formatSizeUnits($bytes);
upload_image($image_temp, $image_ext, $album_id, $image_n, $image_description, $byte);
header('Location: view_album.php?album_id='.$album_id);
exit();
}
}
$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">
<div class="choose">
<p>Choose a file:<br /><input type="file" name="image" /></p>
</div>
<div class="des">
<p>Name*:<br /><input type="text" name="image_n" maxlength="55"/></p>
<p>Description*:<br /><textarea name="image_description" rows="6" cols="35" maxlength="255"></textarea></p>
<p><input type="submit" value="Upload" /></p>
</div>
</form>
<div class="foot">
<?php
}
include 'template/footer.php';
?>
</div>
the form at the end of the second page does not load .. but when i delete the first line at the main page $var_value = 7 ; the form at the end load .. i don't know what is the problem or there is other way to set the album value in the main and pass it to the included page
If there are no problems found in $album_id, which is set from $var_value, the included file does:
$byte = formatSizeUnits($bytes);
upload_image($image_temp, $image_ext, $album_id, $image_n, $image_description, $byte);
header('Location: view_album.php?album_id='.$album_id);
exit();
So it never gets to the part that displays the form.
The second code is included? If so than you can just use
$album_id = $var_value
Instead of:
$album_id = $_SESSION['varname'];
in the second peace of code... No need for an session.

image uploading errors

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'])){

Categories