cakephp, how to upload images - php

In my cake view, I have the following form:
<form enctype="multipart/form-data" action="<?php echo $this->base; ?>/reviews/upload/" method="post" target="_blank">
<input type="file" id="file" name="file" />
<input type="submit" />
</form>
In the ReviewsController, in the upload() method there is:
public function upload() {
var_dump($this->request->data);
}
but it's always empty! I already tried "this->request", "this->data" but it's always empty.
What am I doing wrong?

Try doing it cake way,
echo $this->Form->create("Review", array("action" => "upload", "type" => "file"));
echo $this->Form->input("my-file", array("type" => "file"));
echo $this->Form->end();
In your reviews controller
public function upload() {
debug($this->request->data);
}
Using debug over var_dump and print_r as advantage that debug can be turned off in production mode application wide by setting lowering the debug level to 0 in core.php

Try changing the name of the input to somethinge else then file. Had problems with that before!

Related

An Error Was Encountered in CI forms

Iam a newbie in Codeigniter , Iam learning it from watching videos , the instructor did the same what I did , But it gives me an error like this "The action you have requested is not allowed." ,and it worked with him, I don't know why, any help ! .
this is my Controller code
public function index(){
if($this->input->post('submit')){
echo $this->input->post('first_name');
}
$this->load->view('forms');
}
this is my View code
<form method="POST">
<input type="text" name="first_name" />
<input type="submit" name=submit" />
</form>
Use form_open() helper which automatically adds hidden input with CSRF value.
So your view should be:
<?php echo form_open('action_url'); ?>
<input type="text" name="first_name" />
<input type="submit" name=submit" />
<?php echo form_close(); ?>
Disabling CSRF protection also works but it's a bad idea.
you almost right, you need to add some parts like action in your form, and isset or empty in your controller like
class Test_form extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function index(){
$this->load->view('form_test');
}
//using your example. good
public function check_form(){
if( isset($this->input->post('first_name', TRUE))){
echo "success <br>$$this->input->post('fisrt_name', TRUE)";
}
else{
echo "error";
}
}
//using form_validation. best
public function check_form_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'first Name', 'trim|required|xss_clean');
if( ! $this->form_validation->run()){
echo "error <br>" . validation_errors();
}
else{
echo "success <br>$$this->input->post('fisrt_name', TRUE)";
}
}
}
form_test.php
first method
<form method="post" action="<?= base_url()?>index.php/test_form/check_form">
<input type="text" name="first_name">
<input type="submit" value="test">
</form>
<hr>
second method
<form method="post" action="<?= base_url()?>index.php/test_form/check_form_validation">
<input type="text" name="first_name">
<input type="submit" value="test">
</form>

Uploaded file not available for processing?

Problem:
When I choose the file and submit the form, it goes to the processing page, but apparently doesn't send the file array, just the name of the file.
Goal:
Accept and upload file to appropriate directory.
Environment:
Local
OSX / MAMP Pro
PHP / Laravel 4
Upload Controller:
public function uploadLogo() {
$locals['route'] = route('saveProfileLogo');
return View::make('upload_file', $locals);
}
Upload View:
<form method="get" action="{{{$route}}}" enctype="multipart/form-data" class="grid-form">
<label>File</label>
<input type="file" name="fresh_file" />
<input type="submit" class="btn btn-primary" value="Start Upload" />
</form>
Save Controller:
public function saveLogo() {
// Always fails
// if (!Input::hasFile('fresh_file'))
// return 'No file provided.';
// Always shows: array(1) { ["fresh_file"]=> string(21) "Angular Mountains.jpg" }
// dd(Input::all());
Input::file('fresh_file')->move(public_path() . '/files');
return View::make('upload_file_response');
}
You should use the method="post" in the form, not get, that's why you see the file as a string.

Submiting a form using PHP

I am trying to submit a form using PHP. I am trying to grab the value from two file inputs in my form, yet when I try to index them with my PHP code, I keep getting an error.
The error I get:
Undefined index: profile-pic in C:\xampp\htdocs\shareitme\form-test.php on line 5
Undefined index: cover-pic in C:\xampp\htdocs\shareitme\form-test.php on line 6
My Code:
<?php
if (isset($_POST['submit'])) {
$profile_pic= time() . $_FILES['profile-pic']['name'];
$cover_pic= time() . $_FILES['cover-pic']['name'];
}
?>
<form id="editprofile" method="post" action="<?php echo $_SERVER['PHP_SELF']
?>">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" name="profile-pic"/>
<input type="file" name="cover-pic"/>
<input type="submit" name="submit" value="submit"/>
</form>
I know I have the names right, what am I doing wrong?
For uploading a file include enctype="multipart/form-data" in your form, like below:
<form id="editprofile" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']
?>">
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
For more info on forms : http://www.w3schools.com/tags/att_form_enctype.asp
For renaming a uploaded file, it better to upload it to server with move_uploaded_file and than rename it.
try:
<?php
if (isset($_REQUEST['go']) && $_REQUEST['go'] == "1") {
$profile_pic= time() . $_FILES['profile-pic']['name'];
$cover_pic= time() . $_FILES['cover-pic']['name'];
}
?>
<form id="editprofile" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" name="profile-pic"/>
<input type="file" name="cover-pic"/>
<input type=hidden name="go" value="1">
<input type="submit" name="submit" value="submit"/>
</form>
Whenever you are want to upload file. you need to add enctype in from.
`enctype="multipart/form-data"'
This should work
<form id="editprofile" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']
?>">
What you're trying to do here, if I'm not mistaken, is upload images on your server, right? You can simply use a third-party upload tool for that. I'd recommend AjaxUpload as it is based on AJAX and pretty easy to implement.
For simplicity, I'm applying the upload functionality on one image. You can simply put it inside a function and reuse it.
<p id="showMsg"></p>
<input type="file" name="profile-pic" id="profilePic" />
JQuery:
$("#profilePic").ajaxUpload({
url : $_SERVER['PHP_SELF'],
name: "file",
onSubmit: function() {
$('#showMsg').html('Uploading ... ');
},
onComplete: function(result) {
$('#showMsg').html('File uploaded with result' + result);
}
});
PHP:
<?php
if (isset($_FILES))
{
$file = $_FILES['file'];
move_uploaded_file($_FILES["file"]["tmp_name"], 'upload_dir/' . $_FILES["file"]["name"]); // This function will upload the image to 'upload_dir' folder. You can modify it as per your requirements.
}
?>
1) if you are using file type then your form attribute should be enctype="multipart/form-data".
<form id="editprofile" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
2) Before using your post value it is best practice to check whether its setted or not.
$pic=isset($_FILES['profile-pic']['name']) ? $_FILES['profile-pic']['name'] : '';
Use enctype="multipart/form-data" in form tag.
Whenever you want to post binary datas you must have to set this enctype attribute.

$_FILES['file'] does not work for a simple procedure

Unable to upload an image
The problem is that the image does not get set as `$_FILES['file'].
The code is very simple but still cannot get the obvious outcome.
Have marked the unexpected trouble with 3* i.e. '*'
I don't know what I am doing wrong.
Thanks in advance, your suggestions and comments are much appreciated.
Happy Coding!
<--- NOTE: HTML form below PHP --->
<?php
//CHECK: Submit
if(isset($_POST['submit']))
{
echo 'form submitted <br />';
//CHECK: File by POST
if(isset($_POST['file']))
{
echo $_POST['file'] . '<br />';
unset($_POST['file']);
}
//CHECK: File if 'isset' $_FILES
if(isset($_FILES['file']))
{
print_r($_FILES['file']);
}
else
{
echo '$_FILES not set!';
}
}
?>
<!-- HTML FORM -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="5M">
Image: <input type="file" name="file" size="50" id="file" />
<br /><br />
<input style="margin-left:15%;" type="submit" name="submit" value="Upload"/>
</form>
Please correct your form action you missed `echo :-
<?php echo $_SERVER['PHP_SELF']; ?>
^
As your comment, your are getting error 2 that means:-
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was
specified in the HTML form.
Please refer this solution as well File upload ['ERROR']= 2
Following correction are needed.
1 - Add an echo in action="<?php $_SERVER['PHP_SELF']; ?>" as action="<?php echo $_SERVER['PHP_SELF']; ?>"
2 - Why your are finding file in $_POST, need a check to it
if(isset($_POST['file'])){
echo $_POST['file'] . '<br />';
unset($_POST['file']);
}
3 - You have commented your out put is from line print_r($_FILES['file']);
Array (
[name] => imagename.jpg
[type] => [tmp_name] =>
[error] => 2
[size] => 0
)
tmp_name not getting blank that means your file is not creating its temporary file to upload.
So, check temp upload file path in php.ini make sure it is working
different value in name attribute
Image: <input type="file" name="fileupload" size="50" id="file" />
<?php
if(isset($_POST["submit"]))
{
$name=$_FILES['fileupload']['name'];
$name=$_FILES['fileupload']['tmp-name'];
$name=$_FILES['fileupload']['size'];
}
?>

Can't upload files with CodeIgniter 2.1.0

I'm having problems uploading files with CodeIgniter 2.1.0, as I recieve the $_FILES array empty.
This is the form:
<form enctype="multipart/form-data" action="<?= base_url()?>nicUpload/test" method="POST">
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
The action in the rendered form takes the value: http://localhost/nicUpload/test.
This is the controller:
<?php
class NicUpload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function test() {
echo count($_FILES);
}
}
?>
The result is 0, I would expect 1.
I tried doing the same without CodeIgniter:
index.php:
<!doctype html>
<html>
<head></head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
</body>
</html>
upload.php:
<?php
echo count($_FILES);
?>
and I get the expected result (1). So it's not a php configuration problem.
** UPDATE **
I should have said it earlier, but if I use CodeIgniter's Upload class it fails in this lines of CI's system/libraries/Upload.php:
// Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]))
{
$this->set_error('upload_no_file_selected');
return FALSE;
}
as $_FILES is empty.
Ok, thanks to Sena I found the problem. I was using the method described here to use i18n, so when I was uploading to http://localhost/nicUpload/test I was being redirected to http://localhost/spa/nicUpload/test, in that redirections the information in $_FILES was getting lost. So I just had to add nicUpload to the $special array in MY_Lang.php:
private $special = array (
"admin",
"auth",
"nicUpload"
);
That fixed it, once $_FILES had the proper information I could use the proper method to upload files (the method that Sena mentioned).

Categories