I am a newbie with codeigniter and I want to build a website using codeigniter framework. From first, it look fine I can use database, validation, email, session and then I try to attach a file and send with email :
$this->email->attach('/path/ofyour/constan/file.anything');
thats work too.
since that is a website I want my client to choose file they want to upload.
I try many method, and many of them tell to upload a file to server root and get the file_data, use file_data[file_patch]
$this->email->attach('file_data[file_path]');
the problem is:
since code igniter cant upload multiple data I must use plugin. I tried and its PAIN
I thing its not effective, upload data to server root and then to email?
it better to just get file_path of upload file and send them to email, how?
I build it with jquery mobile, what must I do?
Update
ok i decide to use uploadify i search every website and then i found here and my code is
uploadify.php
<?php
/*
* Functions taken from CI_Upload Class
*
*/
function set_filename($path, $filename, $file_ext, $encrypt_name = FALSE)
{
if ($encrypt_name == TRUE)
{
mt_srand();
$filename = md5(uniqid(mt_rand())).$file_ext;
}
if ( ! file_exists($path.$filename))
{
return $filename;
}
$filename = str_replace($file_ext, '', $filename);
$new_filename = '';
for ($i = 1; $i < 100; $i++)
{
if ( ! file_exists($path.$filename.$i.$file_ext))
{
$new_filename = $filename.$i.$file_ext;
break;
}
}
if ($new_filename == '')
{
return FALSE;
}
else
{
return $new_filename;
}
}
function prep_filename($filename) {
if (strpos($filename, '.') === FALSE) {
return $filename;
}
$parts = explode('.', $filename);
$ext = array_pop($parts);
$filename = array_shift($parts);
foreach ($parts as $part) {
$filename .= '.'.$part;
}
$filename .= '.'.$ext;
return $filename;
}
function get_extension($filename) {
$x = explode('.', $filename);
return '.'.end($x);
}
// Uploadify v1.6.2
// Copyright (C) 2009 by Ronnie Garcia
// Co-developed by Travis Nickels
if (!empty($_FILES)) {
$path = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
//$client_id = $_GET['client_id'];
$file_temp = $_FILES['Filedata']['tmp_name'];
$file_name = prep_filename($_FILES['Filedata']['name']);
$file_ext = get_extension($_FILES['Filedata']['name']);
$real_name = $file_name;
$newf_name = set_filename($path, $file_name, $file_ext);
$file_size = round($_FILES['Filedata']['size']/1024, 2);
$file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES['Filedata']['type']);
$file_type = strtolower($file_type);
$targetFile = str_replace('//','/',$path) . $newf_name;
move_uploaded_file($file_temp,$targetFile);
$filearray = array();
$filearray['file_name'] = $newf_name;
$filearray['real_name'] = $real_name;
$filearray['file_ext'] = $file_ext;
$filearray['file_size'] = $file_size;
$filearray['file_path'] = $targetFile;
$filearray['file_temp'] = $file_temp;
//$filearray['client_id'] = $client_id;
$json_array = json_encode($filearray);
echo $json_array;
}else{
echo "1";
}
i dont relly know what is going on here, like i said i am a newbie but i know something that $json_array, that array hold my data $filearray, that is data file uploaded. mission one complete
now my controller: upload.php
<?php
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
}
/*
* Display upload form
*/
function index()
{
$this->load->view('view');
}
/*
* Handles JSON returned from /js/uploadify/upload.php
*/
function uploadify()
{
//Decode JSON returned by /js/uploadify/upload.php
$file = $this->input->post('filearray');
$data['json'] = json_decode($file);
$this->load->view('uploadify',$data);
}
}
/* End of File /application/controllers/upload.php */
my plan is send the data in onComplete function
my view :view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<<head>
<meta charset="UTF-8">
<title>Uploadify and Codeigniter Tutorial</title>
<?php
$this->load->helper('html');
echo link_tag('http://uploadify_tutorial/uploadify/uploadify.css');
echo '<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>';
echo '<script src="http://localhost/uploadify_tutorial/uploadify/swfobject.js" type="text/javascript"></script>';
echo '<script src="http://localhost/uploadify_tutorial/uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>';
$uploadpath="";
$uploadpath=str_ireplace($_SERVER['DOCUMENT_ROOT'],"", realpath($_SERVER['SCRIPT_FILENAME']));
$uploadpath=str_ireplace("index.php","",$uploadpath);
?>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#upload").uploadify({
uploader: '<?php echo base_url();?>uploadify/uploadify.swf',
script: '<?php echo base_url();?>uploadify/uploadify.php',
cancelImg: '<?php echo base_url();?>uploadify/cancel.png',
folder: '/uploads',
scriptAccess: 'always',
multi: true,
'onError' : function (a, b, c, d) {
if (d.status == 404)
alert('Could not find upload script.');
else if (d.type === "HTTP")
alert('error '+d.type+": "+d.status);
else if (d.type ==="File Size")
alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
else
alert('error '+d.type+": "+d.text);
},
'onComplete' : function (event, queueID, fileObj, response, data) {
//Post response back to controller
$.post('<?php echo site_url('upload/uploadify');?>',{filearray: response},function(info){
$("#target").append(info); //Add response returned by controller
});
}
});
});
</script>
</head>
<body>
<h1>Uploadify Example</h1>
<?php echo form_open_multipart('upload/index');?>
<p>
<label for="Filedata">Choose a File</label><br/>
<?php echo form_upload(array('name' => 'Filedata', 'id' => 'upload'));?>
Upload File(s)
</p>
<?php echo form_close();?>
<div id="target">
</div>
</body>
</html>
my view : uploadify
<html>
<ul>
<li>Extension: <?php echo $json->{'file_ext'};?></li>
<li>File Size: <?php echo $json->{'file_size'};?></li>
<li>File Path: <?php echo $json->{'file_path'};?></li>
</ul>
</html>
and then parsing that json_array variable to my view, that is the plans, but in reality that code doesn work the data is undefined
an error Trying to get property of non-object i use this code here, I suppose the problem is with json
i just want to use the data file uploaded if anyone can solve that problem please share it or send me CI+uploadify program to my email, if anyone expert about CI and Uploadify plugin please make the tutorial step by step how to use it, step by step, i think it would be great help for newbie like me
thanks....
my email :saya.dean#gmail.com
I'm not really clear on where you are running into a problem. 'that variable' will be the files you uploaded, yes? Create an array of the filepaths as they get uploaded and when the upload is done cycle through each for email attachment.
Have you checked other answers on the site? Maybe take a look here. But CI's documentation clearly states that you can use:
$this->email->attach('/path/to/that_file.jpg');
multiple times.
Update:
You can either try using the onUploadSuccess function in uploadify to append each file name to something that you can use later...
'onUploadSuccess' : function(file, data, response) {
alert('The file name is ' + file.name);
...
OR from within uploadify.php. From there you can store what you need for attaching after.
In your case I'd stick with modifying the uploadify.php. You'll have to give it a shot and post some code if you are stuck, but there are plenty of places to get some ideas like here and here
Related
I have a JSON file and in it consists of site data. This site data is for a homepage (I decode the JSON into variables so I can echo them out within the HTML).
Here is my code:
<?php
//start json stuff
$path = "../assets/json/home.json";
$fileexists = file_exists($path);
if ($fileexists) {
$json_d = file_get_contents($path,TRUE);
$json = json_decode($json_d,TRUE);
} else {
die("Error retrieving site data - please refresh the page. If that doesn't work, please report a problem, here and come back later.");
}
if(isset($_POST['submit'])) {
$navtitle = $_POST['navtitle'];
$title = $_POST['title'];
$json_arr = array('navtitle' => $navtitle, 'title' => $title);
$json_enc = json_encode($json_arr);
$json_result = file_put_contents($path, $json_enc);
if($json_result) {
echo "<script>alert('WORKING!');</script>";
} else {
echo "<script>alert('NO WORKING!');</script>";
}
}
?>
So, I have created the array, encoded the array and placed it in the file (I think) but I do not see any changes.
NOTE: I have added the <meta http-equiv="expires" content="0"> meta tag to force the website/browser to grab the home.json file everytime the page is loaded in.
Thank you for any help.
I have tried to get the image from gallery and upload the selected image to server using webservices in titanium.
I have used below code. But am getting the debug error : HTTP error And also it shows the alert box like "There was an error during the connection"
This code is working fine in my development server.But it is not working in my client server. What's the reason ? why my code is not working in my client server ?
The file upload is working fine when upload the file from android device.But it's not working while upload a file from iphone device.Can you please give me a idea to resolve this issue ?
Why am getting this error on my console window.
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var request = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}
else{
alert(this.responseText);
}
},
onerror: function(e){
Ti.API.debug(e.error);
alert("There was an error during the connection");
},
timeout:20000,
});
var uploadabc = event.media.imageAsResized(400 , 400);
request.open("POST",url+"client/manager/at_manager_create_common_file.php");
var params = ({"manager_id": manager_id,"file": uploadabc,});
// var params = ({"manager_id": manager_id,"file": event.media,});
request.send(params);
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]
});
}
EDIT:
this is php file :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$manager_id = $data['manager_id'];
$file_name = $data['file_name'];
$source = base64_decode($data['source']);
include "db_connect.php";
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT * from at_common_files WHERE user_id = '$manager_id' and file_name = '$file_name'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$response='{"Error":"1","Message":"Filename already existed"}';
echo $response;
} else {
$upload_dir = 'common_files/'.$manager_id."_".$file_name;
file_put_contents($upload_dir,$source);
$qugery = mysql_query("insert into at_common_files (user_id,file_name) values ($manager_id, '$file_name') ");
$response = '{"Error":"0","Message":"Successfully file is created"}';
echo $response;
}
?>
EDIT:
As am getting the below error :
: [DEBUG] HTTP error
: [INFO] IN ERROR {"type":"error","source":{"cache":false},"code":404,"error":"HTTP error","success":false}
if i have call the same url and pass a manager_id alone , am getting the results fine.if i have passing the manager_id and file, this time only am getting the Http error. i can't find a exact issue.Because the same titanium code and php code (development server)is working fine and the image is uploading to development server folder. but i have moved the same php file to my client server.now it is not working . also the same web service url is working fine in browser and android.it's not working in iphone only.so that exactly i can't find where is the issue ? can you please give me a solutions.
EDIT :
please refer the below link:
http://developer.appcelerator.com/question/174462/image-not-uploading-from-iphone#comment-224007
I have facing a exact same issue.could you please give me a solution.
i have found many questions like this (e.g. The 'Passive' connection '<appname>' access to protected services is denied).
the answer is always:
"This error is what's known as a "Red Herring". It's a clue that's misleading. The HID isn't a real error that affects your app. There should be other messages that may indicate what's going on."
so look if there is a other error massege which describes your problem.
for example try to escape the filename you are using within the sql statements:
$file_name = mysql_real_escape_string($data['file_name']);
Make sure your device is connected to the internet and then try it like this:
Titanium:
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info('IN ERROR ' + JSON.stringify(e));
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}else{
alert(this.responseText);
}
};
xhr.open('POST', url+"client/manager/at_manager_create_common_file.php");
xhr.send({
media: event.media,
manager_id: manager_id
});
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]*/
});
}
PHP:
<?php
//this function returns a random 5-char filename with the jpg extension
function randomFileName()
{
$length = 5;
$characters = 'abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string . '.jpg';
}
//create the random filename string and uploads target variables
$randomString = randomFileName();
$target = 'common_files/'.$randomString;
if(move_uploaded_file($_FILES['media']['tmp_name'], $target))
{
echo "success";
}
else
{
echo "moving to target failed";
}
?>
For more info check this link: http://code.tutsplus.com/tutorials/titanium-mobile-build-an-image-uploader--mobile-8860
If it works like this you will have to add your logic again (resizing and manager_id)
I want to build a one page utility/prototype that will do the following:
provide the admin user with a drop down box. when they select an option and then click on a submit button, i want to be able to COPY a file from /var/www/mysite/abc.txt to /var/www/mysecondsite/abc.txt
I've written the php / html to display the form, but can I use jquery/ajax to call a function on the same php file?
Here's my code:
<?php
$listofcountries='';
echo "<h2>Select a site</h2>";
echo " <script src='http://myserver/myapp/assets/js/jquery-1.8.1.min.js'></script>";
if ($handle = opendir(dirname(__FILE__)."/secrets/")) {
echo "<input type=text list=site >";
echo "<datalist id=site >";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
//ignore temporary files, and directories.
if ( (strpos($entry, "~") === false) && !(trim($entry)==".") && !( $entry=="..") ){
//echo "$entry\n<BR>";
$country=getCountryName($entry);
echo "<option>".$country;
}
}
}
closedir($handle);
echo "</datalist>";
echo "<input type=submit id='changert'><BR>";
echo "<script>";
echo "$(document).ready(function(){";
echo " $('#changert').live('click', function() {";
echo " alert('in the changert function'); ";
echo " });";
echo " }); "; //end document ready
echo "</script> "; //end javascript
function getCountryName($fileame)
{
$pattern = '/([a-z]*).([a-z]*).([a-z]*).php/i';
preg_match_all($pattern, $fileame, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
return $match[1];
}
}
in the real version, this solution will be part of a codeigniter solution... so i'll have a proper MVC.
But for now, I'd like to be able to contain all the logic in one file.
Can you tell me how i can do this?
jQuery is just JavaScript so it's all on the client. Any server-side file copying would still need to be handled by your PHP. Simplest solution is just to make an AJAX request on button click which hits your PHP API and passes a token or something so non-session users aren't copying files maliciously.
$('#myButton').on('click', function(e) {
$.ajax({
url : '/copyFile.php',
data : {
fileName : $('#mySelectMenu').val(),
token : someTokenYourPHPInjectedIntoYourJS
},
type : 'POST',
success : function (data) {
// yay
}
});
});
You should check PHP Documentation at: http://mx2.php.net/manual/en/function.copy.php
There's an exaple to copy a file.
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
Remember this directories must exists and be visible to each other (inside the same web server)
Add an Ajax call on your user interface,
$.ajax({
url: 'copy.php',
success: function(data) {
if(data == 'true'){
alert('The file has been copied');
}
}
});
Create a second php file to handle the file copy on request
/* copy.php */
<?php
$result = copy('/dir1', '/dir2');
echo $result?'true':'false';
Of curse, this is over-simplified, you have to do some error-handling input-checking and security improvements, but I just wanted to illustrate the way to go.
I am using the Jquery Form plugging to try and upload a picture to my mysql DBMS. I use the JqueryForm ajaxForm() call to do this. It calls a php file on my server and that script puts the file into the database. I then attempt to get that file out of the database in the same script. I guess the nuts and bolts of how I do it is irrelevant. I really want to know how I would get a picture back from an ajax call using the AjaxForm call from the jqueryForm pluggin. Does anybody have an example of how to do this using that pluggin? I am a little lost...
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$(document).ready(function () {
$('#profilepicbutton').live('change', function () {
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#registerpt3").ajaxForm({
target: '#preview',
success: function (data) {
$("#preview").html('');
$("#preview").append("<img src=" + data + "></img>");
}
}).submit();
});
});
</script>
Now, On the jquery form pluggin site, there is a page in particular that has instructions for file uploads...
http://jquery.malsup.com/form/#file-upload
The example that they give is a little blank...
<textarea>
for (var i=0; i < 10; i++) {
// do some processing
}
</textarea>
Now, what am I supposed to do with that? Why am I looping through some data structure? If you look on there page, you will see they are remarkable brief in their instructions of what to do. Anybody have any tutorials or advice? Thanks.
UPDATE PHP Code
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['profilepicinput']['name'];
$size = $_FILES['profilepicinput']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['profilepicinput']['tmp_name'];
$fp = fopen($tmp, 'r');
$data = fread($fp, filesize($tmp));
$data = addslashes($data);
fclose($fp);
values('$email', '$tmp')");
if(mysql_query("insert into Personal_Photos (Email, Pics) values('$email', '$data')"))
{
$query="select Pics, MAX(ID) from Personal_Photos where Email='$email'";
$result=mysql_query($query) or die("Error: ".mysql_error());
$row=mysql_fetch_array($result);
$mime = 'image/yourtype';
$base64 = base64_encode($contents);
$uri = "data:$mime;base64,$base64";
header("Content-type: image/jpg");
print($row['Pics']);
}
else
{
die('Invalid query: ' . mysql_error());
echo "failed";
}
}
else
echo "Image file size max 1 MB. Image Size:"+$size;
}
else
echo "Invalid file format..";
}
else
echo "Please select image..! Bull shit".$email;
exit;
}
If I understand your question right, you can create a so called data URI.
In PHP it's quite simple:
$mime = 'image/yourtype';
$base64 = base64_encode($contents);
$uri = "data:$mime;base64,$base64";
And pass this as string in the ajax reponse to be directly entered as you outlined in your question.
Hopefully this helps, I'm not fluent with jqueryform.
I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.