I have a form that generates multiple single file uploads. They currently upload fine but the upload file keeps overwriting $_SESSION['file'][0] in the array .
<?php
if(isset($_SESSION['UploadCount'])){
for($i=0;$i<=$_SESSION['UploadCount'];$i++){ ?>
<div class="form-group col-md-6">
<span class="control-label">Upload:</span>
<div class="form-control file-input">
<label for="Attachment">
<span class="btn btn-primary">
<input type="file" name="Attachment<?php echo $i; ?>" value="<?php echo $i; ?>"id="Attachment" onchange="this.form.submit();"/>
Choose File
</span>
</label>
<input class="file-name" type="text" readonly="readonly" placeholder="<?php if(isset($_SESSION['file'][$i])){ echo $_SESSION['file'][$i]; } else { echo "No file selected"; } ?>" />
</div><br>
<?php if(isset($_SESSION['UploadError'][$i])){ ?><span class="error"><?php echo $_SESSION['UploadError'][$i]; ?></span><?php } ?>
</div>
<div class="form-group col-md-12">
<label for="Topic" class="control-label">Topic Description</label>
<textarea class="form-control" name="Topic" cols="20" rows="3"><?php if(isset($_SESSION['Topic'])){ echo $_SESSION['Topic']; } ?></textarea>
</div><?php } } ?>
The php to do upload is:
for($i=0;$i<=$_SESSION['UploadCount'];$i++){
if(isset($_FILES["Attachment".$i]["name"])){
if($_FILES["Attachment".$i]["name"])
{
$uperror = "";
include ($_SERVER['DOCUMENT_ROOT'].'/Core/MultiUpload.php');
if($uperror==""){
$_SESSION['file'][$i] = basename($_FILES["Attachment".$i]["name"]);
$_SESSION['stored'][$i] = $target_file;
} else {
$_SESSION['UploadError'][$i] = $uperror;
}
header( "Location: ".$hostname."/consultation/?page=".$Page."&assign=".$Assign ) ;
exit;
}
}
}
MultiUpload.php file is:
<?php
$uploadfoldercheck = "../Uploads/".$_SESSION['CompanyName']."/";
$uploadfoldercheck = str_replace(' ', '_', $uploadfoldercheck);
if (!file_exists($uploadfoldercheck))
{
mkdir($uploadfoldercheck, 0755, true);
$copy_index = $uploadfoldercheck."/index.php";
copy('../Uploads/index.php', $copy_index);
}
$filename = "../Uploads/".$_SESSION['CompanyName']."/".$_SESSION['UserID']."/";
$filename = str_replace(' ', '_', $filename);
if (!file_exists($filename))
{
mkdir($filename, 0755, true);
$copy_index = $filename."/index.php";
copy('../Uploads/index.php', $copy_index);
}
$target_file = $filename . basename($_FILES["Attachment".$i]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
$uperror = "Sorry, file already exists:".$target_file;
$uploadOk = 0;
}
// Check file size
if ($_FILES["Attachment"]["size"] > 2000000) {
$uperror = "File to large. Max 2MB.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "pdf" ) {
$uperror = "Sorry, only PDF files are allowed.";
$uploadOk = 0;
}
if($uploadOk=="1")
{
if (move_uploaded_file($_FILES["Attachment".$i]["tmp_name"], $target_file)) {
} else {
$uperror = "Unable to load File!";
}
}
?>
Upload count gets initiliased:
if(!isset($_SESSION['UploadCount'])){
$_SESSION['UploadCount']=3;
}
Related
I want to start off with that this will be my first post on Stackoverflow, so thanks for helping me in advance.
I'm trying to make a form in which i can enter a name, artist, genre and upload an audio file into a folder.
I have it all setup except for the query doesn't work.
Here is the form:
<form action="upload" method="post" enctype="multipart/form-data">
<label for="musicName" class="col-sm-2 col-form-label col-form-label-lg">Title:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="musicName" id="musicName" required />
</div>
<label for="musicArtist" class="col-sm-2 col-form-label col-form-label-lg">Artist:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="musicArtist" id="musicArtist" required />
</div>
<label for="musicGenre" class="col-sm-2 col-form-label col-form-label-lg">Genre:</label>
<div class="col-sm-10">
<select class="form-control" name="musicGenre" id="musicGenre" required >
<option value="hiphop">Hip Hop</option>
<option value="trap">Trap</option>
<option value="pop">Pop</option>
<option value="edm">EDM/Dance</option>
<option value="rock">Rock</option>
<option value="rnb">RnB</option>
<option value="jazz">Jazz</option>
<option value="country">Country</option>
<option value="metal">Metal</option>
<option value="blues">Blues</option>
<option value="reggae">Reggae</option>
<option value="classical">Classical</option>
</select>
</div>
<label for="fileToUpload" class="col-sm-2 col-form-label col-form-label-lg"></label>
<div class="col-sm-10">
<label for="fileToUpload" class="uploadArea">drop a file to upload<div id="selectedFiles"><p></p></div></label>
<input type="file" name="fileToUpload" id="fileToUpload" class="hidden" multiple>
</div>
<label for="submitSong" class="col-sm-2 col-form-label col-form-label-lg"></label>
<div class="col-sm-10">
<input type="submit" value="Upload Image" id="submitSong" name="submitSong" class="btn btn-primary">
</div>
Then first i do all my checks etc.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$file_name = $_FILES["fileToUpload"]["name"];
$file_tmp = $_FILES["fileToUpload"]["tmp_name"];
$file_size = $_FILES["fileToUpload"]["size"];
$file_type = $_FILES["fileToUpload"]["type"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submitSong"])) {
$check = filesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
echo "<script>
alert(`File is not an audio file.`);
window.location.href=`music`;
</script>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "<script>
alert(`Sorry, file already exists.`);
window.location.href=`music`;
</script>";
$uploadOk = 0;
}
$filesize = 5000000;
// Check file size
if ($_FILES["fileToUpload"]["size"] > $filesize) {
echo "<script>
alert(`Sorry, your file exceeds the limit of" . $filesize . " `);
window.location.href=`music`;
</script>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "mp3" && $imageFileType != "wav" && $imageFileType != "flac" ) {
echo "<script>
alert(`Sorry, only Mp3, Wav & Flac files are allowed.`);
window.location.href=`music`;
</script>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "<script>
alert(`Sorry, your file was not uploaded.`);
window.location.href=`music`;
</script>";
And then at last i upload the file and the attributes that came with it
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
if(isset($_POST[`submitSong`]))
{
$song_title = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicName`]));
$song_artist = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicArtist`]));
$song_genre = mysqli_real_escape_string($mysqli, htmlentities($_POST[`musicGenre`]));
$current_time = `CURRENT_TIMESTAMP`;
$sql = "INSERT INTO songs (song_name, song_artist, song_genre, uploaded_at, song_link, user_id VALUES
($song_title, $song_artist, $song_genre, $current_time, $file_tmp," . $_SESSION[`userid`] . ")";
// ($song_title, $song_artist, $song_genre, $current_time, $file_tmp," . $_SESSION[`userid`] . ")";
$result = $mysqli->query($sql);
var_dump($result);
// echo "<script>
// alert(`You have succesfully uploaded: ". basename( $_FILES["fileToUpload"]["name"]). " !`);
// window.location.href=`music`;
// </script>";
}
} else {
echo "<script>
alert(`Sorry, there was an error uploading your file.`);
window.location.href=`music`;
</script>";
// echo "Sorry, there was an error uploading your file.<br />";
}
}?>
Any help would be appreciated!
I am getting these errors if I try to upload multiple files in array file type.. But if I try to upload just one picture it uploads :\
THis is my html
<form action="" method="post" enctype="multipart/form-data">
<label for="product1"> Image 1 </label> <input type="file" name="productimages1[]" id="product1" />
<label for="product1"> Image 2 </label> <input type="file" name="productimages2[]" id="product1" />
<label for="product1"> Image 3 </label> <input type="file" name="productimages3[]" id="product1" />
<label for="product1"> Image 4 </label> <input type="file" name="productimages4[]" id="product1" /> <br />
<input type="submit" name="save" />
</form>
And php for this is
$image1 = $_FILES['productimages1']['name'];
$image1temp = $_FILES['productimages1']['tmp_name'];
$image2 = $_FILES['productimages2']['name'];
$image2temp = $_FILES['productimages2']['tmp_name'];
$image3 = $_FILES['productimages3']['name'];
$image3temp = $_FILES['productimages3']['tmp_name'];
$image4 = $_FILES['productimages4']['name'];
$image4temp = $_FILES['productimages4']['tmp_name'];
$target_dir = "../uploads/store/products/";
$result = array();
//$result = mergeArrays($codes, $name, $price, $discount, $description, $category, $quantity, $image1, $image2, $image3, $image4,$image1temp,$image2temp,$image3temp,$image4temp);
$result = mergeArrays2($image1temp,$image2temp,$image3temp,$image4temp,$image1,$image2,$image3,$image4);
foreach($result as $row)
{
$target_file1 = $target_dir . basename($row["name1"]);
$uploadOk = 1;
$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);
$target_file2 = $target_dir . basename($row["name2"]);
$uploadOk = 1;
$imageFileType2 = pathinfo($target_file2,PATHINFO_EXTENSION);
$target_file3 = $target_dir . basename($row["name3"]);
$uploadOk = 1;
$imageFileType3 = pathinfo($target_file3,PATHINFO_EXTENSION);
$target_file4 = $target_dir . basename($row["name4"]);
$uploadOk = 1;
$imageFileType4 = pathinfo($target_file4,PATHINFO_EXTENSION);
if (move_uploaded_file($row['tmp_name1'], $target_file1))
{
echo "\n"."The file ". basename( $row['name1']). " has been uploaded.";
}
else
{
echo "Sorry, there was an error uploading your file." ."<<".$imageFileType1. ">>" .$target_file1 . "...".$row["name1"]."...".$row["tmp_name1"];
}
if (move_uploaded_file($row['tmp_name2'], $target_file2))
{
echo "\n"."The file ". basename( $row['name2']). " has been uploaded.";
}
else
{
echo "Sorry, there was an error uploading your file." ."<<".$imageFileType2. ">>" .$target_file2 . "...".$row["name2"]."...".$row["tmp_name2"];
}
if (move_uploaded_file($row['tmp_name3'], $target_file3))
{
echo "\n"."The file ". basename( $row['name3']). " has been uploaded.";
}
else
{
echo "Sorry, there was an error uploading your file." ."<<".$imageFileType3. ">>" .$target_file3 . "...".$row["name3"]."...".$row["tmp_name3"];
}
if (move_uploaded_file($row['tmp_name4'], $target_file4))
{
echo "\n"."The file ". basename( $row['name4']). " has been uploaded.";
}
else
{
echo "Sorry, there was an error uploading your file." ."<<".$imageFileType4. ">>" .$target_file4 . "...".$row["name4"]."...".$row["tmp_name4"];
}
$img1 = basename($row["name1"]);
$img2 = basename($row["name2"]);
$img3 = basename($row["name3"]);
$img4 = basename($row["name4"]);
}
the function mergeArray2 is this
function mergeArrays2($image1temp,$image2temp ,$image3temp,$image4temp,$image1, $image2, $image3, $image4)
{
$result = array();
$i=0;
foreach($image1temp as $key=>$image1temps) {
$result[] = array('tmp_name1'=> $image1temps, 'tmp_name2'=> $image2temp[$key],'tmp_name3'=> $image3temp[$key],'tmp_name4'=> $image4temp[$key],'tmp_name1'=> $image1temp[$key],'name1'=> $image1[$key],'name2' => $image2[$key],'name3'=> $image3[$key],'name4'=> $image4[$key]);
}
return $result;
}
i am creating a page called events i have created a form which submits on post file, this is my form code, `
Adding Staff
<div class="box">
<label>Heading</label>
<input type="text" name="heading" id="heading"/>
</div>
<div class="box" style="margin-left: 120px">
<label>Description 1</label>
<textarea cols="30" rows="5" name="description_1" id="description_1"></textarea>
</div>
<div class="box">
<label>Description 2</label>
<textarea cols="30" rows="5" name="description_2" id="description_2"></textarea>
</div>
<div class="clear"> </div>
<div class="box">
<label>Upload Images</label>
<input type="file" name="picture" id="picture"/>
<label>Is Rename <input type="checkbox" name="is_rename"> </label>
</div>
<div class="clear"> </div>
<div class="box" style="width: 100px; margin-left: 350px;">
<input style="padding: 4px" type="submit" name="submit" value="submit">
</div>`
This is my post
<?php
ob_start();
session_start();
include_once "../../classes/addClasses.php";
$heading = $_POST['heading'];
$description_1 = $_POST['description_1'];
$description_2 = $_POST['description_2'];
$picture = $_POST['picture'];
$target_dir = "../../../uploads/";
$target_file = $target_dir . basename($_FILES["picture"]["name"]);
print_r($_FILES);
if( isset( $_POST['is_rename'] ) )
$file_name = time().'-'.basename($_FILES["picture"]["name"]);
else
$file_name = basename($_FILES["picture"]["name"]);
if(empty($_FILES['picture']['name'])){
echo "please select a file to upload";
?>
<script>window.location.href="http://localhost/learner-pack/admin/admin/add_events.php?error=empty"</script>
<?php
}
$target_file = $target_dir . $file_name;
if (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["picture"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
if (file_exists($target_file)) {
echo "Sorry, file '".$file_name."' already exists.";
}elseif (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file " . $file_name . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
/*$created_by = $_POST['created_by'];
$updated_by = $_POST['updated_by'];
$current_date = $_POST['current_date'];
$updated_date = $_POST['updated_date'];
$visitor_counter = $_POST['visitor_counter'];*/
if($admin->addingEvents($heading,$description_1,$description_2, $file_name))
{
header('Location: ../view_events.php?added=true');
}
else
{
echo "Error";
}
?>
please help me to store multiple images in table using one field and retireve them to view on events page when i fetch one row so that all images on that row are fetchable
I have this weird problem with my code:
There are three input file tags. These are upload scenarios and their results:
All three files simultaneously - success
Only picture - Success
Only audio - Failure
Only video - Failure
One picture and one audio - picture succeeds, audio fails
One picture and one video - picture succeeds, video fails
One audio and one video - one of them succeeds
<?php
session_start();
if(!isset($_SESSION["username"])){
header('Location: index.php');
}
if(isset($_POST["year"])){
ini_set('display_errors',1);
error_reporting(E_ALL);
var_dump($_FILES);
$year = $_POST["year"];
$height = $_POST["height"];
$weight = $_POST["weight"];
$school = $_POST["school"];
$class = $_POST["class"];
$target_dir_img = "./pictures/";
$target_dir_aud = "./audios/";
$target_dir_vid = "./videos/";
$uploadOk = 1;
$target_files = array();
$target_img = basename($_FILES['uploadedFiles']['name'][0]);
var_dump($target_img);
if(strcmp($target_img,'')){
$imageFileType = pathinfo($target_img,PATHINFO_EXTENSION);
$newImageName = $target_dir_img . $_SESSION['username']."_".$_POST['year'].".". $imageFileType;
if($imageFileType != "jpg" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
else {
$target_files[] = $newImageName;
}
}
// Allow certain file formats
$target_aud = basename($_FILES['uploadedFiles']['name'][1]);
var_dump($target_aud);
if(strcmp($target_aud,'')) {
$audioFileType = pathinfo($target_aud, PATHINFO_EXTENSION);
$newAudioName = $target_dir_aud . $_SESSION['username']."_".$_POST['year'].".". $audioFileType;
if($audioFileType != "mp3") {
echo "Sorry, only MP3 files are allowed.";
$uploadOk = 0;
}
else {
$target_files[] = $newAudioName;
}
}
$target_vid = basename($_FILES['uploadedFiles']['name'][2]);
var_dump($target_vid);
if(strcmp($target_vid,'')){
$videoFileType = pathinfo($target_vid, PATHINFO_EXTENSION);
$newVideoName = $target_dir_vid . $_SESSION['username']."_".$_POST['year'].".". $videoFileType;
if($videoFileType != "mp4") {
echo "Sorry, only MP4 files are allowed.";
$uploadOk = 0;
}
else {
$target_files[] = $newVideoName;
}
}
var_dump($target_files);
// 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 {
for($i=0; $i<sizeof($target_files); $i++){
if (move_uploaded_file($_FILES['uploadedFiles']['tmp_name'][$i], $target_files[$i])) {
echo "The file ". basename( $_FILES['uploadedFiles']['name'][$i]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
<h1>Welcome <?php echo $_SESSION["username"]; ?>!</h1>
<h2>Data</h2>
<form action="" method="POST" enctype="multipart/form-data">
<p><label>Select Year : </label>
<select id="year" name="year">
<?php
for($i=1901; $i<=2020; $i++){
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select></p>
<p><label>Height : </label>
<input type="text" id="height" name="height" placeholder="Height" /></p>
<p><label>Weight : </label>
<input type="text" id="weight" name="weight" placeholder="Weight" /></p>
<p><label>School : </label>
<input type="text" id="school" name="school" placeholder="School" /></p>
<p><label>Class : </label>
<input type="text" id="class" name="class" placeholder="Class" /></p>
<p><label>Choose picture : </label>
<input type="file" id="picture" name="uploadedFiles[]" accept="image/jpeg, image/jpg" /></p>
<p><label>Choose Audio : </label>
<input type="file" id="audio" name="uploadedFiles[]" accept="audio/mp3" /></p>
<p><label>Choose Video : </label>
<input type="file" id="video" name="uploadedFiles[]" accept="video/mp4" /></p>
<input type="submit" id="submit" name="submit" value="submit" /></p>
</form>
Any inputs on how it may be happening?
I'm trying to upload a mp4 file with php, and I succeed it, but after that, the file can't be run with VLC, even though it could be run before upload. The error message says that the file can't be opened gives me the path of the file and ends with (Bad File Descriptor).
I've made the following configurations in php.ini file:
file_uploads = On
upload_max_filesize = 25M
post_max_size = 25M
Here is my code:
if ($_FILES["video"]["name"] == "") {
$error = "No video imported.";
}
else {
if (file_exists("uploads/" . $_FILES["video"]["name"])) {
$error = "The file already exists.";
}
else if ($_FILES["video"]["type"] != "video/mp4") {
$error = "File format not supported.";
}
else if ($_FILES["video"]["size"] > 26214400) {
$error = "Only files <= 25ΜΒ.";
}
else {
move_uploaded_file($_FILES["video"]["tmp_name"], "uploads/" . $_FILES["video"]["name"]);
}
}
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
<fieldset>
<div class="area">
<label for="path">Select file:</label>
<input class="upload" type="file" name="video"></input>
<span><?php echo $error; ?></span><br />
</div>
</fieldset>
<input type="submit" name="insert" value="upload"></input>
</form>
You had a syntax error on line 4 & 5. It should be
} elseif (file_exists("uploads/" . $_FILES["video"]["name"])) {
Not:
} else {
if (file_exists("uploads/" . $_FILES["video"]["name"])) {
This code has been tested and is working.
<?php
if ($_FILES["video"]["name"] == "") {
$error = "No video imported.";
} elseif (file_exists("uploads/" . $_FILES["video"]["name"])) {
$error = "The file already exists.";
} elseif ($_FILES["video"]["type"] != "video/mp4") {
$error = "File format not supported.";
} elseif ($_FILES["video"]["size"] > 26214400) {
$error = "Only files <= 25??.";
} else {
move_uploaded_file($_FILES["video"]["tmp_name"], "uploads/" . $_FILES["video"]["name"]);
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
<fieldset>
<div class="area">
<label for="path">Select file:</label>
<input class="upload" type="file" name="video"></input>
<span><?php echo $error; ?></span><br />
</div>
</fieldset>
<input type="submit" name="insert" value="upload"></input>
</form>