where to display $_SESSION variable below - php

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

Related

How to add user_id at the beginning of filename when upload to server

How to an add user_id ($_POST['pk']) at the beginning of the filename when I upload an image to server with the below function update_customer().
With this I can easily discover the correct files of a specific user.
Result should be:
filename = $_POST['pk'].'-'.$_POST['name']
function update_customer() {
if(isset($_POST['name']) && isset($_POST['pk'])) {
//print_r($_FILES['image']);exit;
$filename = '';
if(isset($_FILES['image']) && $_FILES['image']['tmp_name'] && $_FILES['image']['error'] == 0) {
$filename = $_FILES['image']['name'];
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/wp-content/uploads/agent_company_logos/';
$wp_filetype = wp_check_filetype_and_ext( $_FILES['image']['tmp_name'], $_FILES['image']['name'] );
if($wp_filetype['proper_filename'])
$_FILES['image']['name'] = $wp_filetype['proper_filename'];
if ( ( !$wp_filetype['type'] || !$wp_filetype['ext'] ) ) {
$arrErrors['file'] = __('File type not allowed', 'agent-plugin');
}
else {
move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir.$_FILES['image']['name']);
}
if(!empty($arrErrors) && count($arrErrors) == 0) {
die (json_encode(array('file' => agent_get_user_file_path($_FILES['image']['name']), 'caption' => '', 'status' => 1)));
}
//echo $_FILES['image']['name'];
}
$updated = $GLOBALS['wpdb']->update($GLOBALS['wpdb']->prefix.'agent_customer', array('company_logo' => $filename), array('user_id' => $_POST['pk']));
$dir = wp_upload_dir();
echo $dir['baseurl'] . '/agent_company_logos/'.$filename; exit(0);
}
echo 0;
die();
}
you can use
$basname = $_POST['pk'].basename($file);

It is not appending the variable

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'] : "";
}

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 ?>'];

multi image upload wrong quantity on file-upload

i like to upload some images to a directory with the help of arrays. therefore i have this code:
$allowedExtensions = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$maxSize = 2097152;
$Dir = "a/b/c/d";
$storageDir = "a/b/c/d/tmp_images";
//Arrays
$errors2 = $output = array();
if(!empty($_FILES['image'])){
// Validation loop (I prefer for loops for this specific task)
for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {
$fileName = $_FILES['image']['name'][$i];
$fileSize = $_FILES['image']['size'][$i];
/*$fileErr = $_FILES['image']['error'][$i];*/
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// Dateiendung überprüfen
if (!in_array($fileExt, $allowedExtensions)) {
$errors2[$fileName][] = "format $fileExt in $fileName is not accepted";
}
// check filesize
if ($fileSize > $maxSize) {
$errors2[$fileName][] = "maxsize of 2MB exceeded";
}
}
/*// Handle validation errors here
if (count($errors) > 0) {
echo "Fehler beim Upload des Bildmaterials:";
echo ($errors); ->gibt "Array" aus
}*/
if (is_dir($Dir)){
mkdir($storageDir, 0755);
}else{
mkdir($Dir, 0755);
mkdir($storageDir, 0755);
}
// Fileupload
for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {
// Get base info
$fileBase = basename($_FILES['image']['name'][$i]);
$fileName = pathinfo($fileBase, PATHINFO_FILENAME);
$fileExt = pathinfo($fileBase, PATHINFO_EXTENSION);
$fileTmp = $_FILES['image']['tmp_name'][$i];
// Construct destination path
$fileDst = $storageDir.'/'.basename($_FILES['image']['name'][$i]);
for ($j = 0; file_exists($fileDst); $j++) {
$fileDst = "$storageDir/$fileName-$j.$fileExt";
}
// Move the file
if (count($errors2) == 0) {
if (move_uploaded_file($fileTmp, $fileDst)) {
...
}
}
the problem with that code is the following: in case of uploading two or more files with an accepted ending it will echo out:
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access abc2.png in /a/b/xxx.php on line xxx
which refers to that line:
if (move_uploaded_file($fileTmp, $fileDst)) {
this message will be shown for each picture except the first one. so i have no clue what i do wrong. i would really appreciate if there is someone who could help me out. i really would appreciate. thanks a lot.
First of, I would name the uploaded fields seperatly. E.g. name the first field <input name="image_1" type="file" /> and the second <input name="image_2" type="file" />. Then you can iterate over the $_FILES array instead:
foreach($_FILES as $fileId => $file){
//make sure it's a file you want (optional)
if(!preg_match("/^image\_\d+$/",$fileId){
continue;
}
//the rest of your code from the for loop
}
Secondly, you need to make sure that your form's enctype is multipart/form-data.
Does any of this help?
Your code is very similar to my answer at limiting the checking condition while uploading swf files
This is how you should implement such ..
FULL Script
<?php
error_reporting ( E_ALL );
$allowedExtensions = array (
'jpg',
'jpeg',
'png',
'bmp',
'tiff',
'gif'
);
$maxSize = 2097152;
$dirImage = "photos/tmp_images";
$errors = $output = array ();
if (isset ( $_FILES ['image'] )) {
foreach ( $_FILES ['image'] ['tmp_name'] as $key => $val ) {
$fileName = $_FILES ['image'] ['name'] [$key];
$fileSize = $_FILES ['image'] ['size'] [$key];
$fileTemp = $_FILES ['image'] ['tmp_name'] [$key];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
if (empty ( $fileName ))
continue;
// Dateiendung überprüfen
if (! in_array ( $fileExt, $allowedExtensions )) {
$errors [$fileName] [] = "format $fileExt in $fileName is not accepted";
}
if ($fileSize > $maxSize) {
$errors [$fileName] [] = "maxsize of 2MB exceeded";
}
if (! mkdir_recursive ( $dirImage, 0777 )) {
$errors [$fileName] [] = "Error Creating /Writing Directory $dirImage ";
}
// Construct destination path
$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 )) {
// ...
$output [$fileName] = "OK";
}
}
}
}
function mkdir_recursive($pathname, $mode) {
is_dir ( dirname ( $pathname ) ) || mkdir_recursive ( dirname ( $pathname ), $mode );
return is_dir ( $pathname ) || mkdir ( $pathname, $mode );
}
if (! empty ( $errors )) {
echo "<pre>";
foreach ( $errors as $file => $error ) {
echo $file, PHP_EOL;
echo "==============", PHP_EOL;
foreach ( $error as $line ) {
echo $line, PHP_EOL;
}
echo PHP_EOL;
}
echo "</pre>";
}
if (! empty ( $output )) {
echo "<pre>";
echo "Uploaded Files", PHP_EOL;
foreach ( $output as $file => $status ) {
echo $file, "=", $status, PHP_EOL;
}
echo "</pre>";
}
?>
<form method="post" enctype="multipart/form-data">
<label for="file">Filename 1:</label> <input type="file" name="image[]"
id="file" /> <br /> <label for="file">Filename 2:</label> <input
type="file" name="image[]" id="file" /> <br /> <label for="file">Filename
3:</label> <input type="file" name="image[]" id="file" /> <br /> <input
type="submit" name="submit" value="Submit" />
</form>
Why are you accessing the $_FILES superglobal array as a three dimensional array?
if you want the file name of the file uploaded from an <input type="file" name="image"/> all you have to do is $name = $_FILES[ 'image' ][ 'name' ] there is no need for the [ $i ] at the end.
You need to loop over the entries in $_FILES like this:
foreach ( $_FILES as $inputName => $fileData )
{
// $inputName is be 'image` for the first input and so on,
// $fileData will be an array of the attributes [ 'name', 'tmp_name', ... ]
}
I'm not sure if this may solve it for you, but you can try to convert these into "normal" $_FILES values.
$arr_files = #$_FILES['image'];
$_FILES = array();
foreach(array_keys($arr_files['name']) as $h)
$_FILES["image_{$h}"] = array( 'name' => $arr_files['name'][$h],
'type' => $arr_files['type'][$h],
'tmp_name' => $arr_files['tmp_name'][$h],
'error' => $arr_files['error'][$h],
'size' => $arr_files['size'][$h]);
And then run the loop like normal.
See previous related answer

Categories