How can I download file in codeigniter? - php

I am trying to download file in my codeigniter web application using javascript and codeigniter controller, it shows the file contents in ASCII format but not download the file directly
view.php
Download
<img src="<?php echo site_url()."/../images/uploads/".$jobno."/thumb_".$prd_row->filename; ?>" alt="Loading Image..." >
<input type="checkbox" name="img_check" id="img_check" class="img_check" image="<?php echo $prd_row->filename ?>">
<script type="text/javascript">
function prd_download(ele)
{
var selected_images = $(".img_check:checked");
var job_no = $("#product_table").attr("jobno");
var image_name = new Array();
for(i = 0; i < selected_images.length; i++)
{
image_name[i] = $(selected_images[i]).attr('image');
}
$.get('<?php echo site_url('project_controller/file_download') ?>', {file_name : image_name, jobno : job_no});
}
</script>
controller.php
function file_download()
{
$url_para = $_GET['file_name'];
$job_no = $_GET['jobno'];
$this->load->helper('download');
$data = file_get_contents(site_url().'/../images/uploads/'.$job_no."/".$url_para[0]);
$name = 'myphoto.jpg';
force_download($name, $data);
}
I had tried by changing path also, but its not working...

I made changes in my javascript
<script type="text/javascript">
function prd_download(ele)
{
var selected_images = $(".img_check:checked");
var job_no = $("#product_table").attr("jobno");
var image_name = new Array();
for(i = 0; i < selected_images.length; i++)
{
image_name[i] = $(selected_images[i]).attr('image');
}
window.location.href = "<?php echo site_url('project_controller/file_download') ?>?file_name="+ image_name +"&jobno="+ job_no;
}
</script>
In javascript I called controller directly, cause $.get function treat like call back...
Now its working fine...! :) :D

Related

How to get an id in front of file for upload

First of all I'm very new to PHP and a bit better with Jquery. I managed to build an upload iFrame to upload images to a dropbox account for a webshop.
So somebody puts a T-shirt in the cart and then needs to upload some artwork. Customer clicks "upload" and is send to an iFrame which have the dropbox upload script. The url of the iFrame is something like this -> http://webshop.com/dropbox/index.html?id=10102013-88981
So far so good. The problem is however that when two people upload a file with the same name, the first file is being updated. So I need to have an unique id in front of the file. That unique id is the parameter at the end of the url.
So the question is how to get the id at the end of the url and how to place it in front of the uploaded image?
Ideal would be either a prefix for the file name or store everything in it's own folder.
I tried several things but my knowledge is limited, so any help greatly appreciated.
The upload script:
//Start the upload code.
........
......
if(sizeof($_FILES)===0){
echo "<li>No files were uploaded.</li>";
return;
}
foreach ($_FILES['ufiles']['name'] as $key => $value) {
if ($_FILES['ufiles']['error'][$key] !== UPLOAD_ERR_OK) {
echo $_FILES['ufiles']['name'][$key].' DID NOT upload.';
return;
}
$tmpDir = uniqid('/tmp/DropboxUploader-');
if (!mkdir($tmpDir)) {
echo 'Cannot create temporary directory!';
return;
}
$tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
if (!move_uploaded_file($_FILES['ufiles']['tmp_name'][$key], $tmpFile)) {
echo $_FILES['ufiles']['name'][$key].' - Cannot rename uploaded file!';
return;
}
try {
$uploader = new DropboxUploader($drop_account, $drop_pwd );
$uploader->upload($tmpFile, $drop_dir);
echo "<li>".$_FILES['ufiles']['name'][$key]."</li>" ;
// Clean up
if (isset($tmpFile) && file_exists($tmpFile))
unlink($tmpFile);
if (isset($tmpDir) && file_exists($tmpDir))
rmdir($tmpDir);
} catch(Exception $e) {
$error_msg = htmlspecialchars($e->getMessage());
if($error_msg === 'Login unsuccessful.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Unable to log into Dropbox</li>';
return;
}
if($error_msg === 'DropboxUploader requires the cURL extension.' ) {
echo '<li style="font-weight:bold;color:#ff0000;">Application error - contact admin.</li>';
return;
}
echo '<li>'.htmlspecialchars($e->getMessage()).'</li>';
}
}
UPDATE AS REQUESTED
The form:
<form class="formclass" id="ufileform" method="post" enctype="multipart/form-data">
<fieldset>
<div><span class="fileinput"><input type="file" name="ufiles" id="ufiles" size="32" multiple /></span>
</div>
</fieldset>
<button type="button" id="ubutton">Upload</button>
<button type="button" id="clear5" onclick="ClearUpload();">Delete</button>
<input type="hidden" name="id" id="prefix" value="" />
</form>
Upload.js (file is downloadable as free script on the internet):
(function () {
if (window.FormData) {
var thefiles = document.getElementById('ufiles'), upload = document.getElementById('ubutton');//, password = document.getElementById('pbutton');
formdata = new FormData();
thefiles.addEventListener("change", function (evt) {
var files = evt.target.files; // FileList object
var i = 0, len = this.files.length, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (isValidExt(file.name)) { //if the extension is NOT on the NOT Allowed list, add it and show it.
formdata.append('ufiles[]', file);
output.push('<li>', file.name, ' <span class="exsmall">',
bytesToSize(file.size, 2),
'</span></li>');
document.getElementById('listfiles').innerHTML = '<ul>' + output.join('') + '</ul>';
}
}
document.getElementById('filemsg').innerHTML = '';
document.getElementById('filemsgwrap').style.display = 'none';
document.getElementById('ubutton').style.display = 'inline-block';
document.getElementById('clear5').style.display = 'inline-block';
}, false);
upload.addEventListener('click', function (evt) { //monitors the "upload" button and posts the files when it is clicked
document.getElementById('progress').style.display = 'block'; //shows progress bar
document.getElementById('ufileform').style.display = 'none'; //hide file input form
document.getElementById('filemsg').innerHTML = ''; //resets the file message area
$.ajax({
url: 'upload.php',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (results) {
document.getElementById('ufileform').style.display = 'block';
document.getElementById('progress').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'block';
document.getElementById('filemsg').innerHTML = '<ul>' + results + '</ul>';
document.getElementById('listfiles').innerHTML = '<ul><li>Select Files for Upload</ul>';
document.getElementById('ufiles').value = '';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
formdata = new FormData();
output.length = 0;
}
});
}, false);
} else {
// document.getElementById('passarea').style.display = 'none';
document.getElementById('NoMultiUploads').style.display = 'block';
document.getElementById('NoMultiUploads').innerHTML = '<div>Your browser does not support this application. Try the lastest version of one of these fine browsers</div><ul><li><img src="images/firefox-logo.png" alt="Mozilla Firefox" /></li><li><img src="images/google-chrome-logo.png" alt="Google Chrome Firefox" /></li><li><img src="images/apple-safari-logo.png" alt="Apple Safari" /></li><li><img src="images/maxthon-logo.png" alt="Maxthon" /></li></ul>';
}
document.getElementById('multiload').style.display = 'block';
document.getElementById('ufileform').style.display = 'block';
}());
function ClearUpload() { //clears the list of files in the 'Files to Upload' area and resets everything to be ready for new upload
formdata = new FormData();
output.length = 0;
document.getElementById('ufiles').value = '';
document.getElementById('listfiles').innerHTML = 'Select Files for Upload';
document.getElementById('ubutton').style.display = 'none';
document.getElementById('clear5').style.display = 'none';
document.getElementById('filemsgwrap').style.display = 'none';
}
function getExtension(filename) { //Gets the extension of a file name.
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isValidExt(filename) { //Compare the extension to the list of extensions that are NOT allowed.
var ext = getExtension(filename);
for(var i=0; i<the_ext.length; i++) {
if(the_ext[i] == ext) {
return false;
break;
}
}
return true;
}
Change this line
$tmpFile = $tmpDir.'/'. $_POST['id'] . '-' . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
Note the $_POST['id'] which was added
EDIT: Changed to $_POST
Also in your form which you are posting add
<input type="hidden" name="id" value="<?=$_GET['id']; ?>" />
You could simply at time() to your file name.
http://php.net/manual/de/function.time.php
$tmpDir. '/' . time() . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);

How to grab a part of text from source code of a page

I want to grab a part of source code that i received using file_get_contents
<script type="text/javascript">
//<![CDATA[
var minFlashVersion = '9,0,124';
var playerWidth = 760;
var playerHeight = 554;
var playerFallbackFile = 'URL';
</script>
I want to grab that URL part of var playerFallbackFile = 'URL';
Can you please help me how to do that in php ?
This:
$data = file_get_contents('http://stackoverflow.com/questions/19236942/');
if (preg_match("/var playerFallbackFile = '(.*?)'/", $data, $match))
{
echo $match[1]; // "URL"
}
else
{
die('playerFallbackFile not found');
}

how do I loop a php variable within a javascript script

I created a form with a text field that has Spry Validation (ie javascript). The user can select the number of rows in the form from 1 to 10. I need the code below to also expand but I'm not familiar enough with javascript to make it work.
$divkey is the variable that controls how many rows are in the form.
Original
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["change"], maxChars:20});
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
so I need the line 'var sprytextfield1...' to repeat based on $divkey with the next line being 'var sprytextfield2...' and so on. Can someone please rewrite this so it will work?
Trying to use php
<script type="text/javascript">
<?php for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Trying to use javascript
<script type="text/javascript">
var numwrestler = <?php echo $wrestlerkey; ?>;
var sprytextfield = [];
for (var i = 0; i < numwrestler; i++) {
var num = i+1;
var sprytextfield[num] = new Spry.Widget.ValidationTextField("sprytextfield"+num, "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
I'd recommend that you use a Javascript array for this type of task.
Your code is mostly correct, but the var in your for loop is incorrect, and the creation of the num variable instead of just using i is redundant.
<script type="text/javascript">
var sprytextfield = new Array();
var numwrestler = <?php echo $wrestlerkey; ?>;
for(var i = 0; i < numwrestler; i++){
sprytextfield[i] = new Spry.Widget.ValidationTextField("sprytextfield"+(i+1), "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Be sure that your PHP variable(s) are defined in the file before you include them in your script.
In your PHP code, you never define the variable divkey, by deafault the value will be 0.
Try:
<script type="text/javascript">
<?php $divkey = 10; for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Please, note that the variable that you are using as index $num in every iteration of the loop will be increasing 2, because of the i++ and the $num=$i+1

cannot click items echoed by another page using ajax - $(document).on is not working

updated
i'm having 2 pages. An index page connected to a js file. This js file containing ajax code fetching data from database.
this is my js file
$(document).ready(function() {
// getting links from db andshow sub_menu div //
$(".menu_item").mouseover(function(){
$(this).addClass("selected").children().slideDown(500,function(){
var id = $(".selected").attr("id");
var ajax= false;
ajax = new XMLHttpRequest();
var qst = "?id="+id;
ajax.open("GET","ajax/get_sub_cats.php"+qst);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
$(".sub_menu[title="+id+"]").html(ajax.responseText);
}
}
ajax.send(null);
});
});
// hiding sub_menu div //
$(".menu_item").mouseout(function(){
$(this).removeClass("selected").children(".sub_menu").slideUp(500);
});
// keeping sub_menu div visible on mouse over //
$(".sub_menu").mouseover(function() {
$(this).stop();
});
// clicking sub menu link in the menu //
$(document).delegate("a#subCatLink","click",function(){
alert("test");
});
// document ready end
});
and this is get_sub_cats php file used to fetch links from db
<?php
require('../_req/base.php');
$id = $_REQUEST['id'];
$getSubcatsQ = "select * from sub_cats where Main_Cat_ID = '$id'";
$getSubcatsR = mysql_query($getSubcatsQ);
$numrows = mysql_num_rows($getSubcatsR);
while($row = mysql_fetch_array($getSubcatsR)){
?>
<a id="subCatLink" href="products.php?id=<?php echo $row['Sub_Cat_ID']; ?>"><?php echo $row['Sub_Cat_Name']; ?></a><br />
<?php
}
mysql_close($connect);
?>
clicking links coming from the other php file using ajax is not working at all
Sorry, maybe this will help, maybe not. But...
Why don't you use something like this:
jQuery
$(".menu_item").mouseover(function(){
var id = $(".selected").attr("id");
var qst = "?id="+id;
var html = '';
$.getJSON('ajax/get_sub_cats.php'+qst, function(data){
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<a id="subCatLink'+data[i].Sub_Cat_ID+'" href="products.php?id='+data[i].Sub_Cat_ID+'">'+data[i].Sub_Cat_Name+'</a>';
}
$(".sub_menu[id="+id+"]").html(html);
});
});
PHP
require('../_req/base.php');
$return = array();
$id = $_REQUEST['id'];
$sql = "select * from sub_cats where Main_Cat_ID = '$id'";
$result = mysql_query($sql);
while($ln = mysql_fetch_array($result)){
$return[] = $ln;
}
echo json_encode($return);
ok try this
$(document).delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
});
That should, as a test, show the href for every link on your page. If that works, put all the links you want to show in a div. Then call it with
$('#divID').delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
})

Dynamic loading JavaScript from AJAX - fails?

I have a problem with dynamic loading of javascript function from Ajax.
I want to update some part of HTML with Ajax. Let's say I want to place a button and to attach a javascript function to that button dynamically.
For example:
...
<head>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function f_OnLoadMain()
{
fParseBrowserInfo();
getJSFromServer();
getHTMLFromServer();
}
</script>
</head>
<body onload="f_OnLoadMain()">
<div id="AjaxArea" width="100%" height="100%" align="left" valign="top" >
<!-- Updated with ajax -->
</div>
</body>
</html>
----- getJSFromServer() - calls to php code:
<?php
$somesource = '
function Clicked(){
alert("Clicked");
}
';
class TestObject{
public $source = "";
function TestObject()
{
$this->source = "";
}
function setSource($source){
$this->source = $source;
}
}
$ti = new TestObject();
$ti->setSource($somesource);
echo(json_encode($ti));
?>
the script is inserted with:
var oHead = document.getElementsByTagName('HEAD').item(0);
if (oScript){
oHead.removeChild(oScript);
}
oScript = document.createElement("SCRIPT");
oScript.type = 'text/javascript';
oScript.text = oScript.source;
oHead.appendChild( oScript);
And getHTMLFromServer() - call php :
<?php
$error = 0;
$someText = '
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
';
class TestObject{
public $src = "";
public $error = 0;
function TestObject()
{
$this->error = 0;
$this->src = "";
}
function setSrcString($sample){
$this->src = $sample;
}
}
$ti = new TestObject();
$ti->error = $error;
$ti->setSrcString($someText);
echo(json_encode($ti));
?>
Then the content is updated with:
var dynamicArea = document.getElementById("AjaxArea");
if(dynamicArea != null)
{
dynamicArea.innerHTML = obj.src;
}
And that works fine!
So, when the page loads the button is displayed ok, BUT pressing button doesn't call function Clicked().
Someone knows how to fix it?
Regards!
i guess you have to escape your apostrophe:
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
you see: onclick="Clicked()"
Together with: function Clicked(){ alert("Clicked"); }
It renders to: onclick="alert("clicked")"
Try to escape your apostrophe :)
Regards

Categories