Handle tmp file in form upload and pass the file to other form before uploaded - php

I need help badly , can't fix it to working like i want..!
I have two forms , one is contact form , and the other is image upload inside the contact form,the forms using AJAX for proccsesing.
I dont want to move_upload_file unless the all form(contact)is submited. so so far its all working, exept when i try to pass the file over the contact form and use#move_upload_file it wont move the file to the server.
I using this way to transfer the file and when i am doing var_dump its working perfect :
if ($proc == "question")
{
// Handle some normal form 'contact us'.
// ... Some proccses code when submited via ajax ...
$fileElementName = 'ImageBrowse';
//This session coming from other proccses form down if isset.
if(isset($_SESSION['imgfilename']) && !empty($_SESSION['imgfilename'])){
//Then i handle it with list to make the rest of the proccses.
list($uploadFilename,$_FILES['ImageBrowse']) = $_SESSION['imgfilename'];
//unset session for security.
unset($_SESSION['imgfilename']);
}
var_dump($_FILES['ImageBrowse']);
// will print the file array perfect.
//Trying now to move_uploaded_File
if(#move_uploaded_file($_FILES['ImageBrowse']['tmp_name'],$uploadsDirectory.$uploadFilename)){
echo 'Uploaded!';
}else{
echo 'Not Uploaded';
}
// and here is the problem , it wont move uploaded file , even if there is array of the file..
}
else if ($proc == "sendQuestionUploadImg")
{
// Handle img upload via ajax.
$fileElementName = 'ImageBrowse';
$uploadsDirectory = '../uploads/';
$allowedTypes = array
(
'image/jpeg',
'image/jpg',
'image/pjpeg',
'image/pjpeg',
'image/png',
'application/x-rar-compressed'
);
// ... Some more proccses code when submited via ajax ...
// In the end if goes well...
// I want to pass the file array to the other if above.
if (isset($msg) && !empty($msg))
{
// I insert the file array into session for take the rest of the proccses in above form if.
$_SESSION['imgfilename'] = array($uploadFilename,$_FILES['ImageBrowse']);
//If i use here , it will work.
if(#move_uploaded_file($_FILES['ImageBrowse']['tmp_name'],$uploadsDirectory.$uploadFilename)){
echo 'Uploaded!';
}else{
echo 'Not Uploaded';
}
//
}
else
{
#unlink($_FILES[$fileElementName]);
}
As you see i pass the whole file array into session, and call it above in the other if proccses for more proccses, when i using #move_upload_file inside the $proc == "sendQuestionUploadImg" it will work perfect and will upload the file , but if i try to use #move_upload_file inside the other if it won't any one know why?

To clear one thing out: if you have a $_FILES array without error, the file is uploaded already and stored in a temporary folder on the server ini_get('upload_tmp_dir');
The function move_uploaded_file() just moves the temporary file to a location of your choice safely.
http://php.net/manual/en/function.move-uploaded-file.php
If this fails, your php process most likely is not able to write to the destination folder.
To debug this
enable error reporting:
ini_set( 'error_reporting', E_ALL );
remove the error suppressing # in front of your move_uploaded_file function
use a tool like Firebug to see the Ajax response
http://ajaxian.com/archives/ajax-debugging-with-firebug

Related

I want to store the filename in session for storing file name in a database on another button click. But my session return empty

while using dropzone file upload plug in in php session is not assigning file string.
actually i want to store multipe file in session in array form and upload the file in folder after that another form action fetch file in variable and store it to database with all form data.
but i get allways session blank.
upload.php
<?php
session_start();
if (!isset($_SESSION['fileupload']) && empty($_SESSION['fileupload'])) {
$_SESSION['fileupload'] = '';
}
if (isset($_FILES['blog_Image']) && !empty($_FILES['blog_Image'])) {
// echo "<pre>";
// print_r($_FILES['blog_Image']);
$_SESSION['fileupload'] == "uploaded";
}
if (isset($_POST['btnsavedata'])) {
echo $_SESSION['fileupload'];
}
?>
output:
its return empty.
i want to store file name in session and store in database on another page.. or button click...

Include_once failed to open stream

I've been studying the issue for a while, can't find an answer.
Working on a PHP/mySQL project on XAMPP. The simplified structure is as follows:
--admin.php
--views
--admin
--editor-html.php (includes the editor form)
--controllers
--admin
--editor.php (includes form processing)
Code for editor.php:
<?php
if (!empty($_POST)) {
var_dump($_POST);
}
//or this instead
// $buttonClicked = isset ($_POST['action']);
// if ($buttonClicked) {
// $buttonType = $_POST ['action'];
// $getData = ($buttonType === "save");
// if ($getData) {
// var_dump($_POST);
// }
// }
$editorOutput = include_once "views/admin/editor-html.php";
return $editorOutput;
?>
The form's action="controllers/admin/editor.php".
At first when I open admin.php the editor form is showing. When the form is submitted, I get the $_POST data from the editor form printed, but the include_once "views/admin/editor-html.php" throws a "failed to open stream" error (despite the fact that before submitting the editor form was showing fine).
If I replace the $_POST handling from controllers/admin/editor.php to admin.php, and point form's action="admin.php", everything works fine.
Please let me know if more info is needed.
1.) In the file structure you describe above, the filepath from editor.php to editor-html.php should be ../../views/admin/editor-html.php
2.) Also, this...
$editorOutput = include_once "views/admin/editor-html.php";
return $editorOutput;
... IMO is too much. Just use this instead:
include_once "../../views/admin/editor-html.php";

yii Cmultifile upload values not set on updation form while editing/updating

Please Help Me.
Get uploaded images while updating/editing in yii
In CRUD operation
when i upload files in cmultifile working fine while creation and deletion, but my problem is during the updating of that particular form.
If any suggestion to keep that drop down field and files in Cmultifile always set based on database values.
Please Help me for CMultiFileUpload widget...getting files from database as selected
Hers my code
In Form
used this widget
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'upload-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
)); ?>
<?php $this->widget('CMultiFileUpload',
array(
'model'=>$model,
'attribute' => 'Document',
'accept'=>'jpg|gif|png|doc|docx|pdf',
'denied'=>'Only doc,docx,pdf and txt are allowed',
'max'=>4,
'remove'=>'[x]',
'duplicate'=>'Already Selected',
)
);?>
In Controller
public function actionCreate()
{
$model = new Upload;
echo Yii::app()->basePath.'/Images/';
if(isset($_POST['Upload']))
{
if($filez=$this->uploadMultifile($model,'Document','/Images/'))
{
$model->Document=implode(",", $filez);
}
$model->attributes=$_POST['Upload'];
if ($model->save())
{
$this->redirect(array('view', 'id' => $model->idUpload));
}
}
$this->render('create', array(
'model' => $model,
));
}
//Function for uploading and saving Multiple files
public function uploadMultifile ($model,$attr,$path)
{
/*
* path when uploads folder is on site root.
* $path='/uploads/doc/'
*/
if($sfile=CUploadedFile::getInstances($model, $attr)){
foreach ($sfile as $i=>$file){
// $formatName=time().$i.'.'.$file->getExtensionName();
$fileName = "{$sfile[$i]}";
$formatName=time().$i.'_'.$fileName;
$file->saveAs(Yii::app()->basePath.$path.$formatName);
$ffile[$i]=$formatName;
}
return ($ffile);
}
}
File fields are different then classic text fields... it's because a file field does not only have the filename in the field... but a file to be uploaded to... you can think of them as they are connected... so you cannot pre-populate a file field with the file name.
To explain the workflow:
a user enters some non-valid data for any other field, chooses the file to be uploaded and submits the form
at the submit time the HTTP protocol sends the form data togetherwith the chosen file to the server
at that time in your action you can access the file with $_FILE that resides in some temporary server folder
now... if the validation fails you (we) are displaying (rendering) again the input form, in other words we are sending to the client browser a new form to be shown with the validation errors
so as the users gets this new form even if you could pre-populate the previous chosen file name... you cannot in any way pre-populate the file content to be uploaded
There are few solutions that I can think of
use ajax/client validation so to be sure that when the form is submited, all the fields will pass the validation.
make the picture upload separate (that is the reason why most software like forums have the avatar/profile picture upload in a separate form)
There is some more advanced solutions but they resemble the above second method... like having the whole form with the file upload together and then when the file is selected to upload that file with ajax even before the form is submited... but that is the most complicated and has some more thinking about it as the user can decide to not submit the form but the picture is already uploaded.
Posted From : File Field
I Solved using javascript
append the file of that record and hide when selects new file.
hence as per now not found perfect solution.
Hers the code
To Display Files
<?php
if($model->register_id != Null || $model->register_id != "")
{
$attribute=CHtml::encode($model->medical_documents);
$file = str_getcsv($attribute ,",");
?> <div id="UploadedFiles"> Uploaded Files: <?php
foreach($file as $i=> $record)
{ ?>
<div>
<span title="File Path :<?php echo Yii::app()->baseURL . "/Documents/" . $file[$i]; ?>">
<?php echo $file[$i];?>
</span>
</div>
<?php } }?>

How to print function result, if worked print -- yes, else ERROR

I am writing a small data entry form. Data gets entered in html form by user & then into csv file on server. Consider the following snippet, that i wrote to do this
if(!empty($_POST)) {
$handler = fopen('database.csv','a') or exit("Error: Unable to open file!");
fputcsv($handler,$_POST);
fclose($handler);
}
?>
Pretty simple!
The only "fancy" task is display a message to confirm that the entry has been added to the database(Entry added), clearing the form ready for the next entry. Or incase of error, display error message(Doh! Write failed ). I can use OR statement but that would only be invoked incase of an error.
Any idea how to do this?
[UPdate]
Thanks for excellent replies everyone! I added conditional statement as everyone suggested
if(!empty($_POST)) {
$handler = fopen('database.csv','a') or exit("Error: Unable to open file!");
if(fputcsv($handler,$_POST)) {
echo 'everything okay, add next record';
}
else {
exit('Error: Record add failed. Try again or contact admin');
}
fclose($handler);
}
if(!empty($_POST)) {
$handler = fopen('database.csv','a');
if ($handler === FALSE) {
exit("Error: Unable to open file!");
} else {
fputcsv($handler,$_POST);
fclose($handler);
echo "everything A-ok";
}
}
You can include a 3-state switch that:
) does data entry and re-displays the cleared form;
) displays the error and re-populates the form so user can fix it;
) default to no data entry, clear form
Use a post or session variable to specify the action to take, default to no action if the variable is not set or does not validate.

how to stop further php parsing, but continue page load

I have an image upload page (single page). When submitted it check filesize and type, exiting on each if they violate the rules. Problem is the entire page stops.
How can i stop the remainder of the php (or break out of current <? ?>) from being processed and just load the rest of the page?
You should move your code into a function, then you can just return from it.
function processImage($img)
{
if (imageIsTooLarge($img))
return false;
doOtherStuff();
return true;
}
$ok = processImage($someImage);
if you don't want to pollute the namespace with extra functions and whatnot, this is the perfect situation for a do { ... } while (0); loop.
do {
// processing
if (!check_file_size($image)) {
echo 'The image is too big';
break;
}
if (!check_file_type($image)) {
echo 'The image is of the wrong type';
break;
}
echo $image;
} while (0);
The do-while(0) loop is the unsung hero of getting conditional exits from some sort of processing without having to write a function and function call into your code. While the gains will be negligible, this will also prevent the PHP parser from having to create an extra symbol and then look it up again for little-to-no reason.
EDIT: it also prevents you from getting into gigantic if-block pyramids when your conditionals get too large. If you wrap it in an if block, and each subsequent condition inside a dependant if-block, you eventually have this giant, hard-to-follow mess of indentation (assuming you format your code) with closing braces that can be difficult to trace to their opening blocks; using do { ... } while (0); keeps everything at the same logical indentation level.
You could, for simplicities sake, wrap the code in an if() statement.
// continue parsing image if filesize not greater than maxsize
if ($filesize <= $max_size) {
// contine parsing image if filetype is fine
if (in_array($extension, array('jpg','jpeg','gif')) {
// remainder of your PHP code goes in here for parsing image upload
}
}
All your HTML should be below this block of PHP.
By exiting do you literally mean exit()? If so consider generating an error message for the user and displaying that, you can just discard the file that is uploaded.
if(image is too large) {
$err = "The image you uploaded is too large";
}
if(image wrong file type) {
$err = "You have not uploaded a valid image file";
}
if(!isset($err) {
proceesImage();
}
// echo out $err to user
Use The New goto function:
<?php
//code is executed
goto a;
//code is not executed
echo "Not Executed";
a:
//code is executed
echo "Executed";
?>

Categories