It is not appending the variable - php

I want to append the name of the file which has been uploaded using the $_POST method to post the $_FILES['fileImage']['name'] from the php script. Problem is that after the file has been uploaded, I don't see the filename appended, it just shows a blank. Why is it not appending the file's name after succesful upload of the file?
If anyone could provide a coded example then it would be very helpful.
Below is Javascript code:
<?php
session_start();
$output = array();
if(isset($_POST['fileImage'])){
$idx = count($_POST['fileImage']) -1 ;
$output[] = isset($_POST['fileImage'][$idx]) ?
$_POST['fileImage'][$idx]['name'] : "";
}
?>
<script>
function stopImageUpload(success) {
var imageNameArray = <?php echo json_encode($output); ?>;
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (var i = 0; i < imageNameArray.length; i++) {
$('.listImage').append(imageNameArray[i] + '<br/>');
}
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
</script>
Below is the php script which uploads the file and this script is on a seperate age from the Javascript function:
<?php
session_start();
$result = 0;
$errors = array ();
$dirImage = "ImageFiles/";
if (isset ( $_FILES ['fileImage'] ) &&
$_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {
$fileName = $_FILES ['fileImage'] ['name'];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
if (count ( $errors ) == 0) {
if (move_uploaded_file ( $fileTemp, $fileDst )) {
$result = 1;
}
}
}
$_SESSION ['fileImage'][] = array('name' => $_FILES ['fileImage']['name']);
?>

Because you're looking in $_POST for a variable which is in $_SESSION. Try changing it to:
$output = array();
if(isset($_SESSION['fileImage'])){
$idx = count($_SESSION['fileImage']) -1 ;
$output[] = isset($_SESSION['fileImage'][$idx]) ?
$_SESSION['fileImage'][$idx]['name'] : "";
}

Related

Rename files while uploading with php

I have a html form + php for uploading 3 pdfs similarly. while uploading i have to cut the names of the files. For instance instead of AB_2020_02_02.pdf i want to have it changed in AB.pdf - for all three files simultaneously. I tried with rename($original_filename, substr($original_filename, 2) . '.pdf'); Any other ideas?
This is the entire code:
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
rename($original_filename, substr($original_filename, 2) . '.pdf');
$target = $target_dir . basename($original_filename);
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>
$target_dir = '';
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$rename = explode('_',$original_filename);
$target = $target_dir . $rename[0].".pdf";
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
Rename directly in move_uploaded_file(...)
<?php
// Set Upload Path
$target_dir = '';
$_FILES = substr($_FILES, 2, strlen($_FILES) - 12);
if( isset($_FILES['fileUpload']['name'])) {
$total_files = count($_FILES['fileUpload']['name']);
for($key = 0; $key < $total_files; $key++) {
// Check if file is selected
if(isset($_FILES['fileUpload']['name'][$key])
&& $_FILES['fileUpload']['size'][$key] > 0) {
$original_filename = $_FILES['fileUpload']['name'][$key];
$target = $target_dir . substr($original_filename, 2).'.pdf' ;
$tmp = $_FILES['fileUpload']['tmp_name'][$key];
move_uploaded_file($tmp, $target);
}
}
}
?>

Codeigniter File Upload Permit Only For Images not For Others

I have to file upload operation consecutive, first for images like gif|jpg|jpeg|png|svg and the second psd|rar|zip|doc|word|txt|xlsx|pdf
First one is working just fine, i can upload all images but the second, i can not upload any of these types but when i try to upload image on second segment it works.
if (isset($_FILES['content_images']['name'])) {
$count_files = count($_FILES['content_images']['name']);
for ($i = 0; $i < $count_files; $i++) {
$_FILES['image']['name'] = $_FILES['content_images']['name'][$i];
$_FILES['image']['type'] = $_FILES['content_images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['content_images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['content_images']['error'][$i];
$_FILES['image']['size'] = $_FILES['content_images']['size'][$i];
$config_images['upload_path'] = "./public/site/images/contents";
$config_images['allowed_types'] = 'gif|jpg|jpeg|png|svg';
$config_images['max_size'] = 5000;
$config_images['max_width'] = 7680;
$config_images['max_height'] = 4320;
$this->load->library("upload", $config_images);
if (!$this->upload->do_upload('image')) {
echo $this->upload->display_errors();
exit;
} else {
$data = $this->upload->data();
$path_images[] = "public/site/images/contents/".$data['file_name'];
}
}
}
if (isset($_FILES['content_files']['name'])) {
$count_files=count($_FILES['content_files']['name']);
for ($i = 0; $i < $count_files; $i++) {
$_FILES['file']['name'] = $_FILES['content_files']['name'][$i];
$_FILES['file']['type'] = $_FILES['content_files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['content_files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['content_files']['error'][$i];
$_FILES['file']['size'] = $_FILES['content_files']['size'][$i];
$config_files['upload_path'] = "./public/site/files/contents";
$config_files['allowed_types'] = 'psd|rar|zip|doc|word|txt|xlsx|pdf';
$config_files['max_size'] = 5000;
$config_files['max_width'] = 7680;
$config_files['max_height'] = 4320;
$this->load->library("upload",$config_files);
if (!$this->upload->do_upload('file')) {
foreach($path_images as $p){
unlink($p);
}
echo $this->upload->display_errors();
exit;
} else {
$data=$this->upload->data();
$path_files[] = "public/site/files/contents/".$data['file_name'];
}
}
}
I found the solution
For help :
You should load the library at the top for 1 time only, and then u should initialize it inside 'if condition'.
When you load upload library and config array inside first condition, when you pass to second condition upload library had already loaded and uses the first condition's config array.
$this->load->library("upload");
if(isset($_FILES['content_images']['name'])){
$count_files=count($_FILES['content_images']['name']);
for($i = 0;$i<$count_files;$i++){
$_FILES['image']['name'] = $_FILES['content_images']['name'][$i];
$_FILES['image']['type'] = $_FILES['content_images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['content_images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['content_images']['error'][$i];
$_FILES['image']['size'] = $_FILES['content_images']['size'][$i];
$config_images['upload_path'] = "./public/site/images/contents";
$config_images['allowed_types'] = 'gif|jpg|jpeg|png|svg';
$config_images['max_size'] = 5000;
$config_images['max_width'] = 7680;
$config_images['max_height'] = 4320;
$this->upload->initialize($config_images);
if(!$this->upload->do_upload('image')){
echo $this->upload->display_errors();
exit;
}else{
$data=$this->upload->data();
$path_images[] = "public/site/images/contents/".$data['file_name'];
}
}
}
if(isset($_FILES['content_files']['name'])){
$count_files=count($_FILES['content_files']['name']);
for($i = 0;$i<$count_files;$i++){
$_FILES['file']['name'] = $_FILES['content_files']['name'][$i];
$_FILES['file']['type'] = $_FILES['content_files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['content_files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['content_files']['error'][$i];
$_FILES['file']['size'] = $_FILES['content_files']['size'][$i];
$config_files['upload_path'] = "./public/site/files/contents";
$config_files['allowed_types'] = 'psd|rar|zip|doc|word|txt|xlsx|pdf';
$config_files['max_size'] = 5000;
$config_files['max_width'] = 7680;
$config_files['max_height'] = 4320;
$this->upload->initialize($config_files);
if(!$this->upload->do_upload('file')){
foreach($path_images as $p){
unlink($p);
}
echo $this->upload->display_errors();
exit;
}else{
$data=$this->upload->data();
$path_files[] = "public/site/files/contents/".$data['file_name'];
}
}
}

How to loop through all values in the array

I am not very good with loops but I want to loop through every one of the session file values in the array. How is the foreach loop written in this situation and does it go in the php script or in the javascript code?
Below is the full php script where it uploads a file:
<?php
session_start();
$result = 0;
$errors = array ();
$dirImage = "ImageFiles/";
if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {
$fileName = $_FILES ['fileImage'] ['name'];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
$filePrifix = basename ( $fileName, "." . $fileExt );
$i = 0;
while ( file_exists ( $fileDst ) ) {
$i ++;
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $filePrifix . "_" . $i . "." . $fileExt;
}
// Move the file
if (count ( $errors ) == 0) {
if (move_uploaded_file ( $fileTemp, $fileDst )) {
$result = 1;
}
}
}
$_SESSION ['fileImage'][] = $_FILES ['fileImage']['name'];
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>
Below is the javascript function which contains the json code:
function stopImageUpload(success){
var imageNameArray = <?php echo json_encode(isset($_SESSION ['fileImage']) ? $_SESSION ['fileImage'] : null); ?>;
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (imagename in imageNameArray)
{
$('.listImage').append(imagename + '<br/>');
}
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
$(sourceImageForm).find('.imagef1_upload_process').css('visibility','hidden');
$(sourceImageForm).find('.imagef1_cancel').css('visibility','hidden');
$(".sbtnimage").removeAttr("disabled");
$(".sbtnvideo").removeAttr("disabled");
$(".sbtnaudio").removeAttr("disabled");
return true;
}
$_SESSION ['fileImage'][] = $_FILES ['fileImage']['name'];
Put that somewhere near the end of your PHP code.
var imageNameArray = <?php echo json_encode(isset($_SESSION ['fileImage']) ? $_SESSION ['fileImage'] : null); ?>;
Change your Javascript imagename to that.
Then make a loop:
for (imagename in imageNameArray)
{
if (success == 1)
{
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append(imagename + '<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
}

It displays a blank web page when I open it

When I open up the web page, it just shows a blank page. Do you know why it is doing this? Could it be because of the [] in the $_SESSION? There is no javascript errors on error console and I don't php errors on screen.
Below is the javascript code where the appending occurs:
<?php
session_start();
$idx = count($_SESSION ['fileImage'] - 1);
$output = isset($_SESSION ['fileImage'][$idx]) ? $_SESSION ['fileImage'][$idx]['name'] : "";
?>
function stopImageUpload(success){
var imageNameArray = ['<?php echo $output ?>'];
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for(var i=0;i<imageNameArray.length;i++)
{
$('.listImage').append(imageNameArray[i]+ '<br/>');
}
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is the php script where it uploads a file which is on another page from the javascript function above:
<?php
session_start();
$result = 0;
$errors = array ();
$dirImage = "ImageFiles/";
if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {
$fileName = $_FILES ['fileImage'] ['name'];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
if (count ( $errors ) == 0) {
if (move_uploaded_file ( $fileTemp, $fileDst )) {
$result = 1;
}
}
}
$_SESSION ['fileImage'][] = array('name' => $_FILES ['fileImage']['name']);
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>
$idx = count($_SESSION ['fileImage'] - 1);
should be
$idx = count($_SESSION ['fileImage']) -1 ;
var imageNameArray = new Array();
imageNameArray = <?php echo $output ?>;
should become
var imageNameArray = ['<?php echo $output ?>'];

where to display $_SESSION variable below

I am trying to retrieve a name of the file uploaded and append it into .list. The problem is that the file name it is retrieving from the $_SESSION variable is always the last file updated and then it doesn't change.
For example if I upload these files below in the server:
desert.jpg
tulips.jpg
lighthouse.jpg
desert_2.jpg
Then the file names it should append from $_SESSION should be:
desert.jpg
tulips.jpg
lighthouse.jpg
desert_2.jpg
But instead it is appending this below for file names retrieved from $_SESSION on screen:
desert.jpg
desert.jpg
desert.jpg
desert.jpg
How can it be fixed so that when a file is uploaded onto the server, it's file name is appended onto .list?
Below is the javascript function where $_SESSION variable is in the json code which displays the name of the file on the screen by appending it onto .list:
function stopImageUpload(success){
var imagename = <?php echo json_encode(isset($_SESSION ['fileImage']['name']) ? $_SESSION ['fileImage']['name'] : null); ?>;
if (success == 1){
$('.listImage').append(imagename + '<br/>');
}
else {
$('.listImage').append('No File');
}
return true;
}
Below is the php code where it uploads the file:
<?php
session_start();
$result = 0;
$errors = array ();
$dirImage = "ImageFiles/";
$allowedTypes = array (
"image/jpeg",
"image/gif",
"image/pjpeg",
"image/jpg",
"image/png",
"image/tif"
);
if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {
$fileName = $_FILES ['fileImage'] ['name'];
$fileSize = $_FILES ['fileImage'] ['size'];
$fileTemp = $_FILES ['fileImage'] ['tmp_name'];
$fileType = $_FILES ['fileImage'] ['type'];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
if (empty ( $fileName ))
continue;
if (! in_array ( $fileType, $allowedTypes )) {
$errors [] = "File Type is not accepted";
}
if(!is_writable($dirImage ))
{
$errors [] = "File Destination not writeable";
}
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
$filePrifix = basename ( $fileName, "." . $fileExt );
$i = 0;
while ( file_exists ( $fileDst ) ) {
$i ++;
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $filePrifix . "_" . $i . "." . $fileExt;
}
// Move the file
if (count ( $errors ) == 0) {
if (move_uploaded_file ( $fileTemp, $fileDst )) {
$result = 1;
}
}
}
$_SESSION ['fileImage'][] = $_FILES ['fileImage']['name'];
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>
On seperate page I have a JSON which retrieves the $_SESSION:
function stopImageUpload(success){
var imagename = <?php echo json_encode(isset($_SESSION ['fileImage']) ? $_SESSION ['fileImage'] : null); ?>;
if (success == 1){
$('.listImage').append(imagename + '<br/>');
}
else {
$('.listImage').append('<br/>');
}
return true;
}
$_SESSION ['fileImage'][] = $_FILES ['fileImage']['name']; instead of $_SESSION ['fileImage']['name'] = $_FILES ['fileImage']['name'];

Categories