Codeigniter : Multiple File Uploading - php

I tried many multiple file uploaders which can be integrated with codeigniter like
pulpload
jquery file upload
Even though they work perfectly in the pure php environment, i could not make them work in codeigniter framework. I tried this for two days.. tried many articles which was in the github and blogs..
But i could not made it in codeigniter framework..
If anyone can tell me it by step by step or if there is a tutorial for that, please help me.
I am a newbi to codeigniter..
New:
I downloaded the blueimp Jquery-File-Upload plugin, and followed this link as it is..
https://github.com/blueimp/jQuery-File-Upload/wiki/Latest-jQuery-File-Upload-easy-integration-with-codeigniter
When I select a file and click upload in chrome it says:
Error SyntaxError: Unexpected token <
In firefox it says:
Error SyntaxError: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I examined the difference between using it on my server and on the demo server, on my server in firebug the POST return is the entire index.html...
but on the demo server it returns JSON data..
Here is the modified section of js/main.js that I changed:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'upload/do_upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
The only thing I changed was making index.html to have the form action point to my script (upload/do_upload)

controller
function add()
{
if(isset($_POST['submit']))
{
$length = count($_FILES['image']['name']);
$filename = $_FILES['image']['name'];
$tempname = $_FILES['image']['tmp_name'];
$allimage = array();
foreach($filename as $key =>$value)
{
move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'
.$filename[$key]);
$allimage[] = $filename[$key];
}
if(!empty($allimage))
{
$allimage = json_encode($allimage);
}
else
{
$allimage = '';
}
$data['image'] = $allimage;
$this->db->insert('table_name',$data);
$this->session->set_flashdata('message','<div class="alert alert-success">Record has been successfully saved.</div>');
}
}

Related

Getting 409 error when calling php from my React application

I am trying to call a simple php file from my React application which will send an email with the details from a contact form. For some reason when the React code executes the fetch of the PHP file, it returns a 409. However, if I manually post the URL into another tab it works as expected, and subsequent calls from my React application then work as expected!
This is my React code:
var url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg
console.log(url)
console.log('sending')
fetch(url,
{
'headers': {
'Accept': 'text/html',
'Content-Type': 'text/html'
},
'method': 'GET',
})
.then(
(result) => {
console.log(result.status)
if (result.status === 200) {
console.log('success')
this.togglePop();
this.setState({
name: "",
email: "",
phone: "",
message: "",
terms: false,
})
} else {
console.log('failed')
this.setState({ openError: true })
}
},
(error) => {
console.log('ERROR')
console.log(error)
this.setState({ openError: true })
}
)
And this is my PHP file:
<?php
//header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html');
// error handler function
function customError($errno, $errstr) {
error_log($errstr);
http_response_code(500);
}
// set error handler
set_error_handler("customError");
http_response_code(200);
// send email
mail($_GET["to"],$_GET["subject"],$_GET["msg"],"From: donot.reply#site.co.uk","-f donot.reply#site.co.uk");
error_log($_GET["subject"].":\n".$_GET["msg"], 0);
echo 'OK';
?>
I have spent several days trying to figure out why this is happening. My htaccess file seems OK as once I have made one succesful call to the PHP file it works after that!
It's not a CORS issue as the file is on the same domain.
Anyone got any ideas?
You are sending the wrong request to the server, and that's why you get a 409 error. You should encode the URL params before sending a request
const url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg;
const encoded = encodeURI(url);
console.log(encoded)
// expected correct URI: "/backend/sendmail.php?subject=New%20Website%20Enquiry&to=info#site.co.uk&msg="
You can read more about it here

Receive JSON response from AJAX POST request?

I'm setting up a system for users to upload profile pictures to the server. These profile pictures are cropped with Croppie, then sent with a POST request for processing to a PHP file.
This PHP file receives a response from the server if the image was accepted, or if there was an error.
I'm having difficulty passing this JSON response back to an AJAX variable, so I can show it to end-users.
I've set up a with the ID of "json" where the response should be shown. However, all that is being displayed is 'undefined'.
When displaying the 'response' variable without .msg, it displays the image URI - so it doesn't appear to be taking the requests made in the PHP script.
Here's what I've tried:
AJAX
$('.crop_image').on('click', function(ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response) {
$.ajax({
type: 'POST',
url: "core/account-mechanisms/push-profile-test.php?action=upload",
data: {
"image": response
},
});
$("#json").html('<div style="margin-top:15px;" class="alert alert-success">'
+ response.msg + '</div>');
})
});
PHP (start of script)
# Mechanism to upload image
if (isset($_POST['image'])) { # Check if image data is being sent by POST
$c_finalCheck = true;
$cropped_image = $_POST['image']; # Assign cropped_image from data received
$image_array_1 = explode(";", $cropped_image); # Create image with correct encoding
$image_array_2 = explode(",", $image_array_1[1]);
$cropped_image = base64_decode($image_array_2[1]);
$c_imgValid = getimagesize($c_fileCheck); # Set result of image validity and size check
if ($c_fileCheck == false) { # Run image validity check with response
$response['msg'] = 'Sorry, your image isn\'t valid. Please try again.';
$c_finalCheck = false;
header("Content-Type:application/json");
echo json_encode($response);
}
you are sending the Ajax Post to your Server, but you are not using the Ajax response. Instead you are displaying the response of your croppie call.
You need to do something like this:
$('.crop_image').on('click', function(ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response) {
$.ajax({
type: 'POST',
url: "core/account-mechanisms/push-profile-test.php?action=upload",
data: {
"image": response
},
}).done(function(data) {
$("#json").html('<div style="margin-top:15px;" class="alert alert-success">' + response + '</div>');
});
})
});
I did not try it but it should give you the right direction.
Here the jquery Api reference: Ajax

JQuery File Upload Custom Path Problems

I am using JQuery File Upload plugin to make add the possibility to upload files to my website.
The upload script is in a page like "index.php?cartella_id=x" (x is a number that indicated a album ID).
I would like to store files like this:
server/php/files
- directory 1/
- - Image x
- - Image y
- directory 2/
- - Image z
- - Image z(2)
I basically want to create a different directory for each album.
Storing the images like I want is not hard because I pass $cartella_id by using a hidden input in the form like this
<input type="hidden" name="cartella_id" value="<?php echo $cartella_id; ?>">
In the server/php/index.php file I check if the user is logged in and if the album exists like this
session_start();
if(!isset($_SESSION["username"])) {
die();
}
if(isset($_REQUEST["cartella_id"])) {
$cartella_id = (int) $_REQUEST["cartella_id"];
$sql = "SELECT * FROM cartelle WHERE cartella_id = $cartella_id";
$query = mysql_query($sql);
if($cartella = mysql_fetch_array($query)) {
$upload_dir = '/files/'.$cartella_id.'/';
} else {
die();
}
} else {
die();
}
And in the UploadHandler.php page I edit the 'upload_dir' and 'upload_url' options.
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/'.$_REQUEST["cartella_id"].'/',
'upload_url' => $this->get_full_url().'/files/'.$_REQUEST["cartella_id"].'/',
Upload works fine... the problem is that if I refresh the upload page I can't see already-uploaded files like the script would show me when no custom path is specified. I can use $_SESSION to fix this problem but I don't like this solution and the Delete buttons wouldn't work in any case.
I studied the PHP code a lot and I've also googled a lot but I couldn't find a solution that works for me.
How do I send custom variables when the script is checking for existing files (I couldn't find that piece of code)?
How do I make the Delete buttons work?
Thanks in advance
So I solved the first problem (make files visible even after reloading the page) by editing js/main.js.
I edited this:
url: $('#fileupload').fileupload('option', 'url'),
to this
url: ($('#fileupload').fileupload('option', 'url') + "?cartella_id="+ document.getElementById('cartella_id').value),
Still have to make the delete buttons work though.
I had the same problem and i solved it enabling the user-directories and overriding the methods in the class UploadHandler as suggested here:
jQuery-File-Upload PHP-user-directories
I added an extra parameter to the delete url.
My index.php :
<?php
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler {
protected function get_user_id() {
return $_REQUEST['recordId'];
}
protected function set_additional_file_properties($file) {
$file->deleteUrl = $this->options['script_url']
.$this->get_query_separator($this->options['script_url'])
.$this->get_singular_param_name()
.'='.rawurlencode($file->name)
.'&recordId='.$_REQUEST['recordId']
;
$file->deleteType = $this->options['delete_type'];
if ($file->deleteType !== 'DELETE') {
$file->deleteUrl .= '&_method=DELETE';
}
if ($this->options['access_control_allow_credentials']) {
$file->deleteWithCredentials = true;
}
}
}
$upload_handler = new CustomUploadHandler(array(
'user_dirs' => true,
));
and i changed the url in
my main.js:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'server/php/index.php?recordId=' + recordId,
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
});
}
i have not edited the UploadHandler.php

ajaxFileUpload on xhr.setRequestHeader is not a function

In my footer.php I have this code which i needed for my api references
<script type="text/javascript">
/** Override ajaxSend so we can add the api key for every call **/
$(document).ajaxSend(function(e, xhr, options)
{
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
});
</script>
It works fine in my project without any error but when I started working on file upload and I'm using ajaxfileupload to upload file, I got this error whenever i upload the file.
TypeError: xhr.setRequestHeader is not a function
xhr.setRequestHeader("KEY", "123456POIUMSSD");
Here is my ajaxfileuplod program code:
<script type="text/javascript">
$(document).ready(function() {
var DocsMasterView = Backbone.View.extend({
el: $("#documents-info"),
initialize: function () {
},
events: {
'submit' : 'test'
},
test: function (e) {
e.preventDefault();
var request = $.ajaxFileUpload({
url :'./crew-upload-file',
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
data : {
'title' : $('#title').val()
},
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
refresh_files();
$('#title').val('');
}
alert(data.msg);
}
});
request.abort();
return false;
}
});
var x = new DocsMasterView();
});
</script>
Can anyone here fix my problem. Any suggestion/advice in order to solve my problem.
As I understand from your comments, setRequestHeaders works fine with regular ajax calls. At the same time it is not available when ajaxFileUpload is used. Most likely that is because transport method does not allow to set headers (for instance, in case when iframe is used to emulate upload of files in ajax style) . So, possible solution is to place a key into your form data:
$(document).ajaxSend(function(e, xhr, options)
{
if(xhr.setRequestHeader) {
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
else
options.data["<?php echo $this->config->item('rest_key_name');?>"] = "<?php echo $this->session->userdata('api_key')?>";
});
Note: I'm not sure if options.data is a correct statement, just do not remember structure of options object. If proposed code does not work - try to do console.log(options) and how
to get an object with data that should be posted (it might be something like options.formData, I just do not remember exactly)
And on server side you will just need to check for key in headers or form data.

AJAX sending a base64 image to an external server

I'm trying to send a base64 image generated on one server and sent to a PHP file on another. So far all I'm getting cross origin errors on the client side and the server with the PHP file doesn't seem to receiving anything.
Here's the code:
Server 1 JS :
function shareDesign() {
$('#twitter').on('click', function() {
//console.log('?image='+encodeURIComponent(canvasExport)+'&designName=test')
$.ajax({
type: 'POST',
url: 'http://mysite.com/share_page.php',
dataType: 'text',
data: {
image : canvasExport ,
designName:'test'
} ,
success: function(data) {
console.log(data);
}
})
})
}
Server 2 PHP:
$image = $_POST['image'];
$designName = $_POST['designName'];
$sHTML_Header = "<html><head><title>SHare design test</title></head><body>";
$sHTML_Content = '<div id="test"><img src="'.$image.'"/> This design is called : '.$designName.'</div>' ;
$sHTML_Footer = "</body></html>";
echo "parseResponse({'status' :'success'})";
Addition:
I need this to work on mobile, is this possible? Also I do not have any server control on the JS server it's on adobe business catalyst.

Categories