Codeigniter form validation for file - php

I'm using codeigniter for my project and I need to read contents of files. So,I need validation to check whether the file is selected or not.
Here is my code in controller
$this->form_validation->set_rules(
'estimation_file',
'Project Estimation File',
'required'
);
But while choosing a file it shows error saying - The Project
Estimation File field is required

In codeigniter you cannot check the validation of two dimension array or file field with form_validation, instead you can check it after posting the data.
$this->form_validation->set_rules('validation_check','any required field','required');
if($this->form_validation->run()==FALSE)
{
// your code before posting...
}
else
{
// check the file posting
if($_FILES['estimation_file']['name']!='')
{
// if file selected or not empty
}
else
{
// if file not selected | empty | redirect
}
}
do not forget to write enctype="multipart/form-data" within the form field, otherwise your file field will not pass the value of two dimension array.
<form method="post" enctype="multipart/form-data" name="upload_form" action="">
<input type="hidden" name="validation_check" value="TRUE" />
<input type="file" name="estimation_file" value="" />
<input type="submit" value="Post" />
</form>

Related

How to insert random default image into database with Laravel?

I am developing a Laravel application.Its have a form which have image upload field and its also not a required field. Now i want to do if anyone submitting form without uploading image then a default random image will be inserted into database from public/images/default directory. How can i do that with Laravel? I have 10 images of that directory (ex: 1b.png, 2b.png, 3b.png....)
<form method="POST" action="{{ route($base_route.'.eventEdit', ['event_id' => $event->event_code]) }}" accept-charset="UTF-8" id="general_form" novalidate="novalidate">
<input name="name" type="text" value="something" class="name">
<input name="name" type="file" value="DefaultImageName" class="image">
<button class="btn btn-default"> Submit </button>
</form>
Add this code to your controller action
$images = scandir(public_path('images/default'));
$image = $request->file('DefaultImageName', $images[mt_rand(0, count($images -1))]);
I would't advise storing images in the database. The approach I take is usually, I store in the database a name, alias and path to the file.
You can do this depending on the pattern you're using on the application, but for your situation, what I'd do is create a mutator that validates whenever you're going to insert a record, if certain field is empty, it does something (if you're using eloquent I assume).
https://laravel.com/docs/5.2/eloquent-mutators
public function setImageAttribute($value)
{
if (empty($value)) {
$this->attributes['image'] = //fetch your image and apply your logic
} else { 
$this->attributes['image'] = value;
}
}
Otherwise, I'd create a formrequest that validates if a certain field is empty, I place some content in it (and this way, when it reaches the insertion code it already contains an image)
https://laravel.com/docs/5.2/validation

PHP - accessing a form-submitted file for validation

I've been doing form validation using $_POST for text entries. Now I have to validate uploaded files through the HTML type='file' forms. I'm having trouble accessing them through $_POST or $_FILES. Is there a different way to do this? I need to get the file so that I can check the MIME type using getimagesize() or mime_content_type()
Here are the relevant bits from my form:
<form action='submission.php' method='POST'>
<p>Upload photo of professor</p>
<input type="file" name="pic" accept="image/*>
<p>Upload video of professor</p>
<input type="file" name="video" accept="video/*">
<p><input type="submit" onclick="validate()"></p>
</form>
submission.php is supposed to call on a validation function to check that the MIME type is image, if I can get the file.
function validateimage(&$errors, $field_list, $field_name, $pattern) {
if (isset($field_list[$field_name])) {
if (!preg_match($pattern, mime_content_type($field_list[$field_name]))) {
$errors[$field_name] = 'Please upload an image file';
}
} else {
$errors[$field_name] = 'Required field';
}
}
After adding enctype="multipart/form-data" to my field and setting $field_list to $_FILES it almost works. However, it appears isset($_FILES['pic']) is always true, as when I try to submit with no upload, I get this warning:
validateimage($errors, $_FILES, 'pic', '/^image/i');
Warning: mime_content_type(): Empty filename or path in /Applications/XAMPP/xamppfiles/htdocs/cs4ww3/Assignment 3/validate.inc.php on line 36
In order for $_FILES to be populated with the submitted files, in your html you need to set enctype attr on your form to multipart/form-data:
<form action='submission.php' method='POST' enctype="multipart/form-data">
...
</form>

checking if the file upload is chosen or not in codeigniter

I have a form with input type file and its not compulsory to upload . But after the submit action occurs I want to check in the controller section if the file input is empty or not. I have a following view page and controller but the method is not working for me .
This is the form fillup page
<form enctype="multipart/form-data" method="post"
action="<?php echo site_url('welcome/do_upload');?>">
username:<input type="text" name="username">
<p>upload file</p>
<input type="file" name="image">
<input type="submit" name="submit" value="submit">
</form>
and this is the controller where am trying to check if the file is selected to upload or not .
if(isset($_FILES['image'])){
echo( "image selected");
} else {
echo("image not selected");
}
the output of the result is always the "image selected" though I don't select any image
The error is when you submit the FORM
$_FILES['image'] will always be created no matter what thus making your conditions true.
You are checking for the wrong conditions here, what you want to do is when a user uploads a file. You might want to do is to check if the $_FILES['image']['name'] length is > 0 or the $_FILES['image']['size'] is > 0.
example, code not for production, just for testing.
if ( strlen($_FILES['image']['name']) > 0){
//yeahhhh!
}

store the $_POST form data if page fail to submit

I am using codeigniter. I am currently having a very simple form (nothing but input fields) that submits to the controller for processing.
That all doesn't matter, but what I am asking about is that I have an upload file in the form also. so the upload function will check for file size and type and so on and gives error if not complying. when that happens and I choose another file that matches the requirement, I submit but nothing goes to next page but the uploaded file and its details while the other fields are not posted or are blank.
It is as if the post is not cached and when I select new file to upload and its okay, it checks $_POST of those fields and they are empty. How can I check for that so that to make sure all fields contain values?
Thank you and more than happy to help elaborating.
To repopulate the fields you can use the set_value function.
set_value()
Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form.
First you check if the form validation and upload was successful.
If both are successful we redirect the user to a new page.
If one of these is unsuccessful we add the error message to your data array which we can access in our view and display our form.
Controller
public function signup()
{
// Data array
$data = array();
// Load form validation libary
$this->load->library('form_validation');
// Load upload library and set configuration
$config['upload_path'] = './uploads/';
$this->load->library('upload', $config);
// Set the required fields
$this->form_validation->set_rules('first_name', 'First name', 'required');
if ($this->form_validation->run() == TRUE)
{
// If upload was succesfull
if ($this->upload->do_upload())
{
$upload_data = $this->upload->data();
// Build array to store in database
$save_data = array(
'first_name' => $this->input->post('first_name'),
'image' => $upload_data['file_name']
);
// Send data to your model to process
$this->your_model->save($save_data);
// Redirect to success page
redirect('registration_succes');
}
else
{
// Upload failed, set error
$data['error'] = $this->upload->display_errors();
}
}
else
{
// Form validation failed, set error
$data['error'] = validation_errors();
}
// Display the form by default or on error
$this->load->view('myform', $data);
}
In our view we repopulate the fields with the submitted values using the set_value function.
View ( myform )
<?php echo form_open_multipart('signup');?>
<fieldset>
<?php if( isset($error) && ! empty($error) ): ?>
<div class="error"><?php echo $error; ?></div>
<?php endif; ?>
<p>
<label>First name</label>
<input type="text" name="first_name" value="<?php echo set_value('first_name'); ?>" />
</p>
<p>
<label>File</label>
<input type="file" name="userfile" size="20" />
</p>
<p>
<input type="submit" />
</p>
</fieldset>
</form>

how to submit a from with validation in PHP?

I want to submit this form through PHP. with validation for required field and validation for phone number and email field also
<form action="" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_LastName">
Last Name</label>
<input id="txt_LastName" type="text" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_Phone">
Phone</label>
<input id="txt_Phone" type="text" title="First Name. This is a required field" />
</div>
<div class="row requiredRow">
<label for="txt_Email">
Email</label>
<input id="txt_Email" type="text" class="required" title="Email. This is a required field" />
</div>
<div class="row">
<input type="submit" value="" class="button" />
</div>
</form>
In your method attribute inside your form, you need to declare either post or get.
Since your action attribute is "" it will submit to the page itself rather than redirecting to another page, so you can have your code that checks for validation in the same PHP file. First validation that is often checked is if the variable has a value by using isset:
if(isset($_POST['txt_Phone'])) { ... }
This just checks that the Phone number field does not contain empty data. I strongly suggest you perform other validation checks on the POST array so you do not have any users posting malicious code.
You can use functions like htmlspecialchars to prevent user-supplied text depending on what you plan to do with the values
Here are some references to help you along the way in the order they should be viewed.
Form Validation using PHP - PHP and MySQL Tutorial
PHP Advance Form Validation Tutorial
PHP Tutorial Part 2: Form Validation
Your form tag needs a target in the action field and a method in the method field (either GET or POST). So make the action your PHP script.
<form name="input" action="form_submit.php" method="get">
As for field validation, you will either have to parse that inside of the PHP and return a response or use Javascript in the browser to check on the fly.
Here is the shcema of such a script:
if ($_SERVER['REQUEST_METHOD']=='POST') {
//data validation:
$err="";
if (valid_phone($_POST['phone'])) $err="Wrong phone no";
if (!$err) {
//record data:
$sql="...";
query($sql);
Header("Location: ".$_SERVER['REQUEST_URI']); //redirect and exit
exit;
}
}
?>
<html>
<head></head>
<body>
<? if ($err) ?> <font color=red><b><?=$err?></b></font>
<form method="POST" id="get-protected">
here goes your form
Okay, firstly, I like to set the form action to <?=$_SERVER['REQUEST_URI']?> to submit it back to the current page, but leaving it as you have it will work fine too.
Secondly, you need to give all your <input>s a name attribute. This is the variable name that PHP will see.
When your users get an error (something doesn't validate correctly) you don't want all the data they entered to disappear. That means you have to set the value attributes of each input to what they had previously entered. Thus, your form starts to look like this:
<form action="<?=$_SERVER['REQUEST_URI']?>" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" name="first_name" value="<?=htmlspecialchars($_POST['first_name'])?>" />
</div>
...
<div class="row">
<input type="submit" name="submit" value="" class="button" />
</div>
</form>
If you didn't know <?= is a basically a shortcut for <?php echo but it will only work if your server has short tags enabled. Some people prefer to type it out the long way (in case they want to switch servers later, or for future-compatibility, or because they're nutbars), but I say screw them, I'm lazy.
This page that has the form on it, has to saved with a .php extension (well, technically it doesn't have to, but that's another story). Then you need to handle you form validation. You have to code that up yourself. It might look something like this (put it above your form somewhere)
<?php
if($_POST['submit']) {
$errors = array()
if(empty($_POST['first_name'])) $errors[] = 'please enter your first name';
if(empty($errors)) {
// save the data to database or do whatever you want with it
header('redirect:succcess.php');
} else {
foreach($errors as $e) {
echo $e;
}
}
}
?>
It's been a while since I've coded in PHP so forgive me if there are syntax errors. That's the jist of it anyway, I'm sure you can find validation libraries out there if you Google. Might take some of the grunt work out of trying to validate email addresses and such.
Using Javascript you can do the validation for this form.For each condition you can use return true and return false,based on the condition.Then you can submit the value.
Using action attribute in form tag the values will be submitted to that file.

Categories