create folder using a form with a given name - forms

Im trying to make a html form that can create a folder on the server with a given name in the html form. So fare I have this code:
<?
if (isset($_POST['createDir'])) {
//get value of inputfield
$dir = $_POST['dirname'. var_dump($_POST)];
//set the target path ??
$targetfilename = PATH . '/' . $dir;
if (!file_exists($dir)) {
mkdir($dir, 0777, true); //create the directory
}
}
print_r($_POST); exit;
?>
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>" name="myform" id="myform">
<input name="dirname" id="dirname" >
<input type="submit" name="dirname" value="dirname" title="Continue to the next step">
</form>
The debug say: Array ( )
the script is nothing i have wrote but trying to put thing together to get it working but have not fix this for days now. Please advice.

Don't use PHP short opening tags (<?). Use the long form (<?php). You risk getting tangled up in the wrong language processor.
You're looking for $_POST['createDir'] coming back from the form, but I don't see a form element with name="createDir".
What is $_POST['dirname'. var_dump($_POST)] supposed to do?
What is PATH?
Play it safe by giving a type= for dirname input element.

Related

How to retrieve an uploaded file from an HTML form

I have an HTML form, which can contain an infinite number of file inputs, declared like so in a twig template:
<form action="my_route">
{% for file in files %}
<label>Current file: {{ file.name }}</label><br>
<label>File to replace (optional): </label>
<input name="{{ file.id }}" type="file"><br>
{% endfor %}
<button type="submit">Send</button>
</form>
The aim of this form is to let user change the files generated by the server, with new files.
My question is, how can i retrieve the sent files, inside my controller ?
I have already tried to retrieve the files from the request object, like so:
$request->get("the_id"); But, it only gives me the file name as a string, not as a file.
Please note that if rendering the form using Symfony functions (createForm, renderForm, ...) make the task easier, I can use them; I've just not yet found a way to use them in this case.
Normally, this is how to retrieve data from a submitted file in Symfony:
if ($form->isSubmitted() && $form->isValid()) {
/**#var UploadedFile $file */
$file = $form->get('file_id')->getData();
if ($file) {
//do your action
}
}
However, since you said there are “infinite” files, you might need something like this:
$file_ids=[/*The array of ids that you retrieve from the DB when making your form*/]
...
if ($form->isSubmitted() && $form->isValid()) {
foreach ($file_ids as $file_id){
/**#var UploadedFile $file */
$file = $form->get($file_id)->getData();
if ($file) {
//do your action
}
}
}

PHP: If value is empty, to not sumbit target filepath to database

I have a very slight problem where I am not able to figure out how to get my target filepath not submit to the mysql database when the field value is empty. Right now, if I leave the image field empty, it still submits the filepath ($folder) to the database. I would like for when the field is left empty, to not send the filepath to mysql.
Form.php
<form enctype="multipart/form-data" action="add.php" method="POST">
HAZARD: <input name="haz1" value="hazard1" type="text" /><br>
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
IMAGE: <input type="file" name="photo"><br>
<input type="submit" name="action" value="Load">
</form>
Add.php
<?php
$folder = "images/";
$target1 = $folder . basename( $_FILES['photo']['name']);
$photo = $target1;
require("../db.php");
$haz1 = $_POST['haz1'];
mysql_query("INSERT INTO testimg VALUES (null,'$haz1','$photo')") ;
move_uploaded_file($_FILES['photo']['tmp_name'], $target1);
?>
I've tried
if (isset($_POST['photo']) ? $_POST['photo'] : null) echo $target1 == null);
I've tried other ways of isset as well but doesn't seem to work. Is there any other way i can accomplish this? Appreciate any help please. Thank you!
(Just a note, I have removed excess code above just to keep it short. I am taking care of SQL injection)
I would strongly suggest JavaScript, then users do not need to reload the page if it is empty. The JavaScript will check if it is empty for you. If it is you can make it so they cannot submit at all.
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
This is an example above, if you would like better walk through go here
JQuery has libraries that you can use to do fancy things if it is left blank, just search for JQuery form validation for more tools.
Hope this helps!
Try using the inbuild HTTP_POST_FILE in PHP:
if (isset($_FILES['photo']) ? $_FILES['photo'] : null)
You could wrap the mysql code inside of an if function too:
if (isset($_FILES['photo']) {
//Do mySQL processing in here
}
A couple of points:
Require is at the top of a PHP script. It's nicer to see all requires
first.
I have used an inline if statement to determine what to set $photo
(elimintating need for $target1)
I have also moved the apostrophes into the assignment of $photo as
returning 'null' comapred to null (without the quotation marks) is
very different in SQL.
If $photo is not null at the end of the script then it moves the
updated file.
Please see the corrected code below:
<?php
require("../db.php");
$folder = "images/";
$photo = (isset($_FILES['photo']) ? "'" . $folder . basename( $_FILES['photo']['name']) . "'" : null);
$haz1 = $_POST['haz1'];
mysql_query("INSERT INTO testimg VALUES (null,'$haz1',$photo)") ;
if ($photo != null) { move_uploaded_file($_FILES['photo']['tmp_name'], $photo); }
?>

storing radio button value and presetting after refresh- cgi visiblity issue

I have a html table that has 2 radio buttons for every row and a save button. I want to store the value of the radio button when saved and preset the value when the page is revisited.This is the html code I have written
<form action='table_extract.cgi' method = 'get'>
<td><input type='radio' name='signoff' value = 'approve'>Approve<br>
<input type='radio' name='signoff' value='review'>Review</td>
<td><input type='submit' name='button' value='Save'/></td></form>
This is what is in table_extract.cgi
#!usr/local/bin/perl
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
use warnings;
print <<END;
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
END
my $regfile = 'signoff.out';
my $sign;
$sign = param('signoff');
open(REG,">>$regfile") or fail();
print REG "$sign\n";
close(REG);
print "param value :", param('signoff');
print <<END;
<title>Thank you!</title>
<h1>Thank you!</h1>
<p>signoff preference:$sign </p>
END
sub fail {
print "<title>Error</title>",
"<p>Error: cannot record your registration!</p>";
exit; }
This is just first part of the problem. I was not able to find any output in console or in poll.out. Once I read the values, I need to preset the values to the radio buttons that was saved by the user in the previous visit.
The problem is in the HTML, your submit button has two type attributes. When I repaired this, the form worked for me.
You are doing too much work to save the form. See chapter SAVING THE STATE OF THE SCRIPT TO A FILE in the documentation.

Perl WWW::Mechanize::Firefox and input type file

Cross-post http://perlmonks.org/?node_id=981067
I have a problem using WWW::Mechanize::Firefox to upload a file to a site with a form using an input type file, like this :
<form enctype="multipart/form-data" action="uploader.php" method="POST" id="formular">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="image0" type="file" id="image0"/><br />
<input type="submit" value="Upload File" />
The content of uploader.php is the following :
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['image0']['name']);
if(move_uploaded_file($_FILES['image0']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['image0']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file,". basename( $_FILES['image0']['name'])." please try again!";
}
?>
And the code I use for uploading the file is the following :
#!/usr/bin/perl
use strict;
use warnings;
use WWW::Mechanize::Firefox;
my $bot = WWW::Mechanize::Firefox->new( autoclose => 0,activate =>1);
$bot->get('http://127.0.0.1/file/index.html');
$bot->form_id('formular');
$bot->field('image0','IMAGE.JPG');
$bot->submit;
There is no error at execution, and the form is submited but without nothing in image0.
The version of WWW::Mechanize::Firefox I use is 0.66 my perl version is : v5.10.0 built for MSWin32-x86-multi-thread
Thanks
Why not try adding the whole path to the image file and a key/value pair in the field() method something like
my $image_path = "/home/images/IMAGE.JPG";
$bot->field(image0=>$image_path);
$bot->submit();
Also, assuming that WWW::Mechanize::Firefox inherits all of LWP::UserAgents methods, include the code below just before the $bot->submit();
$bot->add_handler("request_send", sub { shift->dump; return });
$bot->add_handler("response_done", sub { shift->dump; return });
This will enable logging in your code. Keep an eye on the Request and response codes in the log file something like 'HTTP 200 OK' or 'HTTP 302 Found'. These are standard HTTP response codes so you'll know that you are getting the correct responses back.

dojo file upload using zend framework problem

I am struggling with a bit of dojo that is needed to upload a file. Now the file upload form sits within a dojo dialog box, so is hidden until the user selects an 'upload file' button.
This button can be clicked on anywhere on the site, so I've created a controller to handle the upload.
At the moment I am just trying to get it to work, and in my head script I have the following:
<?php $this->headScript()->captureStart(); ?>
function sendForm(){
//Hide the file input field
dojo.style('inputField',"display","none");
//Show the progress bar
dojo.style('progressField',"display","inline");
dojo.byId('preamble').innerHTML = "Uploading ...";
dojo.io.iframe.send({
url: "<?php echo $this->baseUrl(); ?>/fileprocssing/loadfile/",
method: "post",
handleAs: "text",
form: dojo.byId('StartFrm'),
handle: function(data,ioArgs){
var fileData = dojo.fromJson(data);
if (fileData.status == "success"){
//Show the file input field
dojo.style(dojo.byId('inputField'),"display","inline");
dojo.byId('fileInput').value = '';
//Hide the progress bar
dojo.style(dojo.byId('progressField'),"display","none");
dojo.byId('uploadedFiles').innerHTML += "success: File: " + fileData.details.name
+ " size: " + fileData.details.size +"<br>";
dojo.byId('preamble').innerHTML = "File to Upload: ";
}else{
dojo.style(dojo.byId('inputField'),"display","inline");
dojo.style(dojo.byId('progressField'),"display","none");
dojo.byId('preamble').innerHTML = "Error, try again: ";
}
}
});
}
<?php $this->headScript()->captureEnd() ?>
With the the basic upload for like this
<form id="StartFrm" enctype="multipart/form-data"
name="cvupload"
action="<?php echo $this->baseUrl();?>/fileprocssing/loadfile/"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<!-- wrapping these in spans to be able to modify
parts of this form depending on what the
dojo.io.iframe.submit() does -->
<span id="preamble">File to Upload:</span><br>
<span id="inputField">
<input type="file" id="fileInput" name="uploadFile">
</span>
<span id="progressField" style="display:none;">
<div dojoType="dijit.ProgressBar" style="width:200px" indeterminate="true"></div>
</span>
<br/>
<button value="upload" dojoType="dijit.form.Button"
onclick="sendForm()">Upload</button>
</form>
What I would like to know is how I can get the JSON data object from /fileprocssing/loadfile/ that contains upload data information if the form is called from /somecontroller/someaction/ ?? and when the file has been processed automatically redirect to something like /fileprocesing/reviewdata/
At the moment the action that I have looks like this
public function loadfileAction() {
$log = Zend_Registry::getInstance()->get('log');
$log->log('in loadfileaction', Zend_Log::DEBUG);
$log->log($_FILES['uploadFile']['name'], Zend_Log::DEBUG);
$uploadedFile = array(
'details' => $_FILES['uploadFile'],
'status' => 'success'
);
$log->log($fileUploadData->toJson(), Zend_Log::DEBUG);
$foo = "{'status':'success',details: {name:'".
$_FILES['uploadFile']['name'].
"',size:".
$_FILES['uploadFile']['size'].
"}}";
$log->log($foo, Zend_Log::DEBUG);
$this->view->fileData = $foo;
}
I've handcrafted the JSON data for the time being but will use Zend_Dojo_Data but at the moment I am just trying to get this working.
I have to confess that I don't know dojo that well, but trying to get my head around it in the shortest possible time.
Thanks in advance.
dojo.io.iframe.send requires the response data to be wrapped in a TEXTAREA tag. This is the only/easiest cross browser way to successfully access and load the response data, and is a requirement. It looks like you are sending plain JSON back from the action.
You can also adjust your handleAs to be "json" and skip the intermediate dojo.fromJson(data) call, it will be passed to you as a JSON object (provided the response is wrapped in the aforementioned TEXTAREA)