How to view files as a normal array - php

My main issue is that I have two different file upload links and both are for different purposes.For ex: a) Is a license b)Is a photo so I need to upload both in different locations.So what I wanted is to be able to address file properties as a numeric array instead of an associative array.I am also open to suggestions as to how to distinguish between the two files.
Here is the input code sample:
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload">
</i>Upload License
</label>
<input id="file-upload" name="files[]" type="file">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload">
</i>Upload Photo
</label>
<input id="file-upload" name="files[]" type="file">
Here is the upload script(NOTE-I have also tried using array_values())
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$tmpname = array_values($_FILES['files']['tmp_name']);
$filename = array_values($_FILES['files']['name']);
$filesize = array_values($_FILES['files']['size']);
$filetype = array_values($_FILES['files']['type']);
$date12 = date('Y-m-d');
//for photo
$file_name2 = $filename[0];
$ext2 = pathinfo($file_name2, PATHINFO_EXTENSION);
$file_name22= $name.".".$ext2;
$file_size2 = $filesize[0];
$file_tmp2 = $tmpname[0];
$file_type2 = $filetype[0];
$extensions = array("jpg","jpeg","png","pdf","zip","rar");
$type = "photo";
$desired_dir = "user_data";
if(in_array($ext2,$extensions ) === false)
{
$errors2 = "Extension not allowed!";
}
else
{
//Added file size limit
if($file_size2 > 2097152)
{
$errors2 = 'File size must be less than 2 MB';
}
if(empty($errors2) == true)
{
// Inserting info into database for easy retrieval
$query1 = $this->pdo->prepare("
INSERT into upload_data (NAME,EMAIL,FILE_NAME,FILE_SIZE,FILE_TYPE,date1,file_ext,type)
VALUES('$name','$email','$file_name22','$file_size2','$file_type2','$date12','$ext2','$type')
");
$query1->execute();
if(is_dir($desired_dir) == false)
{
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name22) == false)
{
move_uploaded_file($file_tmp,"user_data/".$type.$file_name22);
}
else
{
//rename the file if another one exist
$new_dir = "user_data/".$file_name22.time();
rename($file_tmp2,$new_dir) ;
}
echo "
<script>
Materialize.toast('Successfully Uploaded!', 8000)
</script>";
}
else
{
echo "
<script>
Materialize.toast($errors, 8000)
</script>";
}
}
Thank you

In order to upload files in a form, your form needs enctype="multipart/form-data".
name the different inputs differently, for example license and photo. Then you can access the files in php with $_FILES['license'] and $_FILES['photo'].

Related

How To Get Video File Size?

I need to get this script to check if the uploaded file is a video file or not and whether the file size is too big or not over the limit. Therefore, need to replace the getimagesize with something else that gets the video file size. How can I accomplish this? Which function to use here? getvideosize function does not exist.
This is where I am stuck.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications/";
//Make Directory under $user in 'uploads/videos/id_verifications'
Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir($directory_path . $user, "$mode", TRUE); //IS THIS LINE
CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
$file = $_FILES["id_verification_video_file"]["name"];
// in PHP 4, we can do:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle,$file); // e.g. gives "video/mp4"
// in PHP 5, we can do:
$file_info = new finfo(FILEINFO_MIME); // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives
"video/mp4"
switch($mime_type) {
case "video/mp4":
// my actions go here...
}
// Let's assume that the name attribute of the file input field I have
used is "id_verification_video_file"
$tempFile = $_FILES['id_verification_video_file']['tmp_name']; // path of
the temp file created by PHP during upload. I MOST LIKELY GOT THIS LINE
WRONG AT THE END PART. HOW TO CORRECT THIS ?
$videoinfo_array = getimagesize($tempFile); // returns a false if not a
valid image file
if ($videoinfo_array !== false) {
$mime_type = $videoinfo_array['mime'];
switch($mime_type) {
case "video/mp4":
// your actions go here...
move_uploaded_file("$file_tmp", "$directory_path" . "$user/" .
"$file_name"); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded successfully!";
exit();
}
}
else {
echo "This is not a valid video file";
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
Best I done so far is above. I'd appreciate if you guys can add the correct lines where they should be and add comments so I can easily spot your changes and learn from the corrections.
EDIT:
Folks, I managed to fix a lot of things on my current update. But, one new problem. The move_uploaded_file() is failing. Why is that ? Do have a look. I actually wrote my questions to you in my code's comments in CAPITAL. If you could kindly answer these questions then I'd be grateful and hopefully we could close this thread as SOLVED asap.
<?php
//Required PHP Files.
include 'header_account.php'; //Required on all webpages of the Site.
?>
<?php
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications";
//Make Directory under $user in
'uploads/videos/id_verifications' Folder if it doesn't exist.
if(!is_dir("$directory_path/$user")) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir("$directory_path/$user", $mode, TRUE); //IS THIS
LINE CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]
["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
echo "File Type: $file_type<br>"; //Outputs: "". WHY $file_type SHOWS
BLANK VALUE WHEN UPLOADING VIDEO FILES ? WORKS WITH OTHER FILES, LIKE
JPEG.
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
echo "File Name: $file_name<br>"; //Outputs: "id_check.mp4"
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
echo "File Extension: $file_extension<br>"; //Outputs: "mp4"
if(file_exists($directory_path . "$user/" . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE NEXT ONE ?
//if(file_exists($directory_path . $user . '/' . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE PREVIOUS ONE ?
{
$Errors[] = "Error: You have already uploaded a video
file to verify your ID!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed
limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;
$max_file_size_allowed =
"$max_file_size_allowed_in_bytes";
//Create a fileinfo respource.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Apply the fileinfo resource and the finfo_file()
function to the uploading given file.
$mime = finfo_file($finfo,$file_name);
//Close the fileinfo resource.
finfo_close($finfo); echo "Mime: $mime<br>"; //exit;
//Outputs: video/mp4
//Verify File Extension.
//if(!in_array($file_extension, $allowed_file_extensions))
die("Error 1: Select a valid video file format. Select an Mp4 file.");
//Verify MIME Type of the File.
if(!in_array($mime, $allowed_file_extensions)) die("Error 2:
Select a valid video file format. Select an Mp4 file.");
elseif(!in_array($file_type, $allowed_file_extensions))
die("Error 3: There was a problem uploading your file $file_name! Make
sure your file is an MP4 video file. You may try again."); //IS THIS LINE
CORRECT ?
//Verify File Size. Allowed Max Limit: 1MB.
if($file_size>$max_file_size_allowed) die("Error 4: Your
Video File Size is larger than the allowed limit of:
$max_file_size_allowed_in_megabytes.");
//Move uploaded File to newly created directory on the
server.
if(!move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name")) die("Error 5: Your file failed to
upload! Try some other time.");
else
{
move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name"); //WHY IS NOT THIS LINE OF CODE
MOVING THE FILE TO DESTINATION ?
//Notify user their Id Verification Video File was
uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded
successfully!";
exit();
}
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3>
</p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
I get echoed when trying to upload an mp4 file:
Error 3: There was a problem uploading your file id_check.mp4! Make sure your file is an MP4 video file. You may try again.
Should I set the folder permissions to 0644 from 0777 ? I am being told I should not allow any files to be executable in the folder by users (file uploaders) and so I should set it to readable & writeable only to "0644". I need your expert opinion on this.

Escap XSS attack and face deformation when uploading file in php

I have a form that users can upload files like html, css, php, java, js, txt, javascript and other files which i included
But my problem is how can i prevent xss attack or face deformation after successful upload
Example when user upload files like this
<input type='text'> //This will show input instead of in plain text
body{display:none!important;} // My document body off
So i tried to make this php script, it worked very fine while viewing in my site but when i try to open the file in my notepadd++ i don't like the look can anyone suggest me how i can do this better outside my code or fix mine
<?php
session_start();
if(!class_exists('DBController')){ require_once("../../_inc/dbcontroller.php"); }
if(isset($_FILES['fileuploader'])){
include_once('../fileextension.php');
$test = true;
$FileName = $_FILES['fileuploader']['name'];
$tmp_name = $_FILES['fileuploader']['tmp_name'];
$uploadPath = __DIR__ . '/'.$FileName;
$currentBas = '';
$defaultProjecName = '';
$exetype = pathinfo($FileName, PATHINFO_EXTENSION);
$extension = strtolower($exetype);
if(in_array($extension,$afile)){
$FTypeof = 'file';
}
else if(in_array($extension,$aimg)){
$FTypeof = 'image';
}
else{
$FTypeof = 'unknown';
}
$FDiscripT = 'No available '.($FTypeof == 'unknown') ? '' : $FTypeof.' discription';
//Here i move the selected file in a directory
$moveResult = move_uploaded_file($tmp_name, $uploadPath);
if ($moveResult != true) {
unlink($uploadPath);
}else{
// If file was moved then open file and get the content
if(file_exists($uploadPath)){
$fileUploadname = $uploadPath;
$filechecker = fopen($fileUploadname, "a+");
$mesure = filesize($fileUploadname);
if($mesure == 0){
$sizechecker = 1;
}
else{
$sizechecker = filesize($fileUploadname);
}
$get_content_file = fread($filechecker, $sizechecker);
fclose($filechecker);
//Then here i use htmlentities to encote the file content
if(!empty($get_content_file)){
$sanitize_file = htmlentities($get_content_file);
$sanitize_file_status = true;
}
if($sanitize_file_status == true){
//Now i put the content back the the file
try{
$openForWrite = fopen($uploadPath, 'w');
$recreateNewfile = fwrite($openForWrite, $sanitize_file);
fclose($openForWrite);
if($recreateNewfile){
//Then insert the other information to database
if($test == false){
$makefile_db = new DBController();
$makefile_db->prepare("INSERT INTO jailorgchild(jailowner,jailchildbasname,prodefault,jailchillink,jailchilddate,filediscription,contentType)
VALUES(:jailowner,:jailchildbasname,:SubDif,:jailchillink,:jailchilddate,:FDiscripT,:contentType)");
$makefile_db->bind(':jailchildbasname', $currentBas);
$makefile_db->bind(':SubDif', $defaultProjecName);
$makefile_db->bind(':jailchillink', $FileName);
$makefile_db->bind(':jailowner', $_SESSION['username']);
$makefile_db->bind(':jailchilddate', date('Y-m-d H:i:s'));
$makefile_db->bind(':FDiscripT', $FDiscripT);
$makefile_db->bind(':contentType', $FTypeof);
$makefile_db->execute();
$filewasmake = $makefile_db->rowCount();
$makefile_db->free();
}
echo '<pre>';
echo $sanitize_file;
//echo 'Unclean Content <br/>'. $get_content_file;
}
}catch(PDOException $e){
echo "Error:" . $e->getMessage();
}
}else{
unlink($uploadPath);
}
}
}
}
?>
HTML FORM
<form method="post" action="testuploader.php" enctype="multipart/form-data">
<input type="file" name="fileuploader">
<input type="submit" value="load">
</form>
OUTPUT IN NOTEPAD++
<?php if(isset($_GET['postid'])){ echo '<h5 style="color:
#2f2f2f;">Related Articles</h5><br/>'; <?php } }?>
So if another user download it and the file look like that i don't think is good please i need help

PHP upload multiple images

This code used to work and now I can't figure why it won't upload, I don't receive errors, I also don't receive any echo's or var_dumps back at all, it's simply like the button only refreshes the page. (Just for clarification there is alot more code doing alot of stuff, but this is the cause of my issue as I isolated it into another project with below code, which gave me the same results).
All it is meant to be doing is creating a folder named by the "ItemName", then it should be moving the images into that new named folder.
Thank you in advance, this problem has been hindering me for a few days now...
HTML PAGE
<form id="newsell" enctype="multipart/form-data" method="post">
<input type="text" class="css-input" name="ItemName" value="">
<input name="file[]" type="file" id="file" multiple />
<input type="submit" name="Upload" class="css-input1" value="Upload">
<?php
if ($_POST['Upload']) {
require_once("random.php");
}
?>
random.php
$MyLocation = "MyName"; // this comes from db, for this case just hardcode
$ItemName1 = htmlspecialchars($_POST["ItemName");
$ItemName = strip_tags($ItemName1);
$parentDir = "C:/wamp/www/HOME/uploadimages/".$MyLocation;
echo "Does it exist...." . $parentDir . "/" . $ItemName;
if(!is_dir($parentDir)) { // Check if the parent directory is a directory
echo "Apologies, something has gone wrong.";
RandError(); // POPUP
die();
}
if(!is_writable($parentDir)) { // Check if the parent directory is writeable
echo "Apologies, something has gone wrong.";
RandError(); // POPUP
die();
}
if(mkdir($parentDir . "/" . $ItemName) === false) { // Create the directory
echo "File apparently exists...." . $parentDir . "/" . $ItemName;
ExistingSaleName(); // POPUP
die();
}
// die('Created directory successfully'); // Success point
echo "AFTER INSERTION";
movefiles();
}
function movefiles() {
$MyLocation = "MyName";
echo "In movefiles";
$ItemName1 = htmlspecialchars($_POST["ItemName"]);
$ItemName = strip_tags($ItemName1);
extract($_POST);
if (extract($_POST) === null) { // trying to fault find here, but never returns anyway due to some kind of bug as at one point it was returning a null value
echo "PROBLEM...";
}
$error=array();
$extension=array("jpeg","jpg","png");
$res = ("C:/wamp/www/HOME/uploadimages/". $MyLocation. "/" . $ItemName);
foreach($_FILES["file"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["file"]["name"][$key];
$file_tmp=$_FILES["file"]["tmp_name"][$key];
if (!(($_FILES["file"]["type"][$key] == "image/png") || ($_FILES["file"] ["type"][$key] == "image/jpeg") || ($_FILES["file"]["type"][$key] == "image/jpg"))) {
die("Only the .jpg / .jpeg / .png file's were uploaded.");
} else {
echo "SHIT";
}
var_dump($file_tmp);
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
$count;
//check if file exist
if (!file_exists($res . "/" . $file_name)) {
sleep(2);
if (isset($_FILES["file"]["tmp_name"][$key])) {
move_uploaded_file($_FILES["file"]["tmp_name"][$key], $res);
++$count;
if ($count >=5) {
// go_to(); // This goes onto the next function
die ("First 5 images are uploaded, <br/> 5 images maximum.");
}
} else {
echo "It exited HERE...";
}
} else {
ExistingSaleName();
die();
}
}
}
I have create simple code to upload multiple images. Changes it yours.
<?php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>

Error in uploading files in yii2 move_upload function

Am doing multiple file upload in the controller but the file doesn't get uploaded
controller code: for the upload
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
I have tried var_dump($images['name'] and everything seems okay the move file does not upload the file
Check what you obtain in $_FILES and in $_POST and evaluate your logic by these result...
The PHP manual say this function return false when the filename is checked to ensure that the file designated by filename and is not a valid filename or the file can be moved for some reason.. Are you sure the filename generated is valid and/or can be mooved to destination?
this is the related php man php.net/manual/en/function.move-uploaded-file.php
Have you added enctype attribute to form tag?
For example:
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>

Upload in Google Chrome not working

I am creating simple file upload (for pictures). I tried in Opera and in FireFox and uploading is working fine. But when I upload via Google Chrome, picture is not uploaded. Can you please tell me where is problem:
here is php script that is used for storing picture in database
<?php
$id=$_SESSION['user_id'];
$user_id=$_SESSION['user_id'];
$album_id=$_POST['album'];
$max_size = 500; // Sets maxim size allowed for the uploaded files, in kilobytes
// sets an array with the file types allowed
$allowtype = array('bmp', 'gif', 'htm', 'html', 'jpg', 'jpeg', 'mp3', 'pdf', 'png', 'rar', 'zip');
// if the folder for upload (defined in $updir) doesn't exist, tries to create it (with CHMOD 0777)
/*if (!is_dir($updir)) mkdir($updir, 0777);*/
/** Loading the files on server **/
$result = array(); // Array to store the results and errors
// if receive a valid file from server
if (isset ($_FILES['files'])) {
// checks the files received for upload
$file_name=$_FILES['files']['name'];
$file_type=$_FILES['files']['type'];
$file_size=$_FILES['files']['size'];
$file_tmp=$_FILES['files']['tmp_name'];
for($f=0; $f<count($_FILES['files']['name']); $f++) {
$file_name = $_FILES['files']['name'][$f];
$random_name=rand();
// checks to not be an empty field (the name of the file to have more then 1 character)
if(strlen($file_name)>1) {
// checks if the file has the extension type allowed
$type=explode('.', $file_name);
$type=end($type);
if (in_array($type, $allowtype)) {
// checks if the file has the size allowed
if ($_FILES['files']['size'][$f]<=$max_size*1000) {
// If there are no errors in the copying process
if ($_FILES['files']['error'][$f]==0) {
$query = mysql_query("SELECT username from users WHERE id = '$id' ");
while($run=mysql_fetch_array($query)){
$username=$run['username'];
}
$query = mysql_query("SELECT album.name an from album WHERE album.id = '$album_id' ");
while($run=mysql_fetch_array($query)){
$album_name=$run['an'];
}
mysql_query("INSERT INTO photos VALUE ('', '$album_id', '$random_name.jpg', '$user_id')");
// Sets the path and the name for the file to be uploaded
// If the file cannot be uploaded, it returns error message
if (move_uploaded_file ($_FILES['files']['tmp_name'][$f],"./users/".$username."/".$album_name."/".$random_name.".jpg")) {
/*$result[$f] = ' The file could not be copied, try again';*/
$result[$f] = '<b>'.$file_name.'</b> - OK';
}
else {
$result[$f] = ' The file could not be copied, try again';
}
}
}
else { $result[$f] = 'The file <b>'. $file_name. '</b> exceeds the maximum allowed size of <i>'. $max_size. 'KB</i>'; }
}
else { $result[$f] = 'File type extension <b>.'. $type. '</b> is not allowed'; }
}
}
// Return the result
$result2 = implode('<br /> ', $result);
echo '<h4>Files uploaded:</h4> '.$result2;
}
?>
and here is form that is used for picture uploading:
<form id="uploadform" action="uploaderimg.php" method="post" enctype="multipart/form-data" target="uploadframe" onSubmit="uploading(this); return false">
<br>
Select album:
<select name="album">
<?php
$query=mysql_query("SELECT id, name, user_id FROM album WHERE user_id = '$id'");
while($run=mysql_fetch_array($query)){
$album_id=$run['id'];
$album_name=$run['name'];
$album_user = $run['user_id'];
echo "<option value='$album_id'>$album_name</option>";
}
?>
</select>
<br /><br />
<h1>Chose your photo/s</h1>
<br>
<input type="file" name="files[]" />
<input type="submit" value="UPLOAD" id="sub" />
</form>
EDIT:
THis is error according to PHP(it's in first script that store uploaded file):
Notice: Undefined index: album in..
After conversing with the OP, the problem lay in this line:
<form id="uploadform" action="uploaderimg.php" method="post" enctype="multipart/form-data" target="uploadframe" onSubmit="uploading(this); return false">
Where onSubmit="uploading(this); return false" was at fault.

Categories