http://www.shedlimited.debrucellc.com
The site allows users to upload an image, via PHP script(ajaxupload.php) which is stored in $uploaded_img , inside of the php script. I want to pass the PATH of my newly stored image to a JS file, and the only way I've found to do it is by writing the value to a text file, which is extreme overkill
file_put_contents("testFile.txt", "");
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $upload_image;
fwrite($fh, $stringData);
$stringData = "\n";
fwrite($fh, $stringData);
fclose($fh);
At the same time, I have an external .js file running which loads my html5 Canvas etc,
I set a global variable sourcer , inside the external .js file, which I'm able to access and update from my index.php by reading the URL from the file which I wrote the url to in my php script.:
jQuery.get('scripts/testFile.txt', function(data) {
sourcer = data;
});
Is there any way that I can pass the URL value to sourcer without having to manually insert it in a text file?
Add a block to your head on your php template.
<script type="text/javascript">
var uploaded_img = '<?php echo json_encode($uploaded_img); ?>';
</script>
The json encode makes sure the variable is properly encoded, even if it is an object or array.
If it is purely an ajax thing. Just return the filename in your ajax response.
So post to your ajax upload, and make your ajax script return a json object with the filename.
So in your upload script, at he bottom:
header('Content-type: application/json');
echo json_encode(array('filename'=>$uploaded_img));
And read the response.filename in javascript.
What about using a session variable to store the uploaded image AND an ajax response to work with ?
I see an advantage to use both : you can use the value directly on the upload page right after the image is uploaded. And for the session var, it will ensure that the server side is always able to get the value if you ever need to access it from another context.
Related
After numerous various tests with uploading files throught HTTP POST Request, it looks that HTTP PUT Requests are the most suitable for very large files +1GB upload.
The below listed simple code I have tested for HTTP PUT file upload request works well:
JavaScript:
var req = createRequest();
req.open("PUT", "PHP/filePutLoad.php");
req.setRequestHeader("Content-type", "text/plain");
req.onload = function (event)
{
console.log(event.target.responseText);
}
req.send(aUploadedFile.file_object);
PHP:
include 'ChromePhp.php';
require_once 'mysqlConnect.php';
ini_set('max_execution_time', 0);
ChromePHP::log( '$_PUT :' . print_r($_PUT));
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");
/* Read the data 1 KB at a time and write to the file */
while ($data = fread($putdata, 1024))
fwrite($fp, $data);
/* Close the streams */
fclose($fp);
fclose($putdata);
However, I have difficulties delivering arguments and variables with the file being uploaded from JavaScript to PHP. For example, I need to deliver upload target folder, where the new data needs to be stored, ID of the uploader, etc..
Is there a way to combine HTTP PUT Request with HTTP POST to submit arguments?
What are my options if I wish to deliver parameters from JavaScript to PHP along HTTP PUT file upload?
Thank you.
using PUT also, it works when you append the parameters in the query string. I'm also looking for another way for this. Although, this is a workaround I'm using currently
curl -X PUT "http://www.my-service.com/myservice?param1=val1" --data #file.txt
I have a button. By clicking the button, I want to export some data shown on the webpage to a file for downloading.
I am doing this in this way: I have a export.php. I send the data as the parameter to PHP file (another parameter is filename), and PHP server create a file and write the data, and then send file. Code is like:
$filename = $_GET['filename'] . '.csv';
$export = $_GET['export'];
$writer = fopen($filename, 'w') or die('cannot create');
fwrite($writer, $export . "\n");
fclose($writer);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($filename));
readfile($filename);
unlink($filename);
exit();
For cases that the data are short, it works fine. But if the data are long, since the data are passed as part of the URL, I will get "Request-URI Too Large" error.
Is there any alternative way to do that? Is it possible to directly write data using JavaScript?
It sounds like you are sending to export.php with a GET, when you should be using a POST. GET is limited to 2048 characters, while a POST is not limited.
You'll need to POST the data to the server. Change the METHOD in your FORM tag to POST (in your html not your php code).
Each browser limits the size of the query string / length of the URL and the limit is browser dependent. You can POST a very large amount of data to the server however. The only limit is how fast is the user's upstream bandwidth and their patience.
Instead of passing the data as a query string, use javascript to create an iframe and build a form which then posts to the php file.
IF your using jquery there's a good tutorial http://tutorialzine.com/2011/05/generating-files-javascript-php/
I'm was making a drag and drop upload script by reading a bunch of tutorials, but they only cover the javascript part, and i'm having issues on the php part.
I'm uploading a image as this:
$('#drop-zone').bind('drop', drop);
function drop(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer = e.originalEvent.dataTransfer;
traverseFiles(e.dataTransfer.files);
}
traverseFiles makes a foreach loop for every file and calls upload funcion, there i do this:
xhr = new XMLHttpRequest();
//some event listners for processing, on load
xhr.open("post", "core/plugins/upload/upload.class.php", true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
then in php i found using this will get me raw data of the image
$file = file_get_contents('php://input');
EDIT: solution found
$fh = fopen($savedir, 'w') or die("can't open file");
fwrite($fh, $file);
fclose($fh);
Assuming you have managed to get the raw file from the PHP input, it's likely going to be base64 encoded. A simple example would be to do this:
<?php
//decode file
$image = base64_decode($file);
// write it
$filename = "myfile.png";
$fh = fopen($filename, 'w') or die("can't open file");
fwrite($fh, $image);
fclose($fh);
Edit
See comments, the file wasn't encoded as a result of the request.
move_uploaded_file is not what you want. If you had sent the file with a normal POST request (rather than through Ajax), that's when you'd use move_uploaded_file.
$file contains the raw binary data for the image. All you have to do is write that data into a file (taking note to properly handle linebreaks) and you're good to go. Start with fopen and see how far you get.
I'm assuming that $file has been successfully populated with the binary data and that you've tested this. If not, then you've got another problem on the javascript side.
Edit: you may also find this helpful.
I've got a large form where the user is allowed to input many different fields, and when they're done I need to send the contents of the form to the server, process it, and then spit out a .txt file containing the results of the processing for them to download. Now, I'm all set except for the download part. Setting the headers on the response to the jQuery .post() doesn't seem to work. Is there any other way than doing some sort of iframe trick to make this work (a la JavaScript/jQuery to download file via POST with JSON data)?
Again, I'm sending data to the server, processing it, and then would like to just echo out the result with headers to prompt a download dialog. I don't want to write the result to disk, offer that for download, and then delete the file from the server.
Don't use AJAX. There is no cross-browser way to force the browser to show a save-as dialog in JavaScript for some arbitrary blob of data received from the server via AJAX. If you want the browser to interpret the results of a HTTP POST request (in this case, offering a download dialog) then don't issue the request via AJAX.
If you need to perform some kind of validation via AJAX, you'll have to do a two step process where your validation occurs via AJAX, and then the download is started by redirecting the browser to the URL where the .txt file can be found.
Found this thread while struggling with similar issue. Here's the workaround I ended up using:
$.post('genFile.php', {data : data}, function(url) {
$("body").append("<iframe src='download.php?url="+url+"' style='display: none;'></iframe>");
});
genFile.php creates the file in staging location using a randomly generated string for filename.
download.php reads the generated file, sets the MIME type and disposition (allowing to prompt using a predefined name instead of the random string in the actual filename), returns the file content and cleans up by deleting the source file.
[edit] might as well share the PHP code...
download.php:
<?php
$fname = "/tmp/".$_GET['url'];
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename="plan.xml"');
echo file_get_contents($fname);
unlink ($fname);
?>
genFile.php:
<?php
$length = 12;
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = substr( str_shuffle( $chars ), 0, $length ).'.xml';
$fh = fopen(('tmp/'.$str), 'w') or die("can't open file");
fwrite($fh,$_POST["data"]);
fclose($fh);
echo $str;
?>
Rather than using jQuery's .post(), you should just do a normal POST by submitting the form, and have the server respond with appropriate Content-Encoding and MIME-type headers. You can't trigger a download through post() because jQuery encapsulates the returned data.
One thing I see in use rather frequently, though, is this:
$.post('generateFile.php', function(data) {
// generateFile builds data and stores it in a
// temporary location on the server, and returns
// the URL to the requester.
// For example, http://mysite.com/getFile.php?id=12345
// Open a new window to the returned URL which
// should prompt a download, assuming the server
// is sending the correct headers:
window.open(data);
});
I created a part of my CMS that allows admins to convert all the text on the page to textareas, so they can edit the content. All the content they change is inside a div, and I submit via jQuery / AJAX the div's content to the PHP controller that processes the data. However, jQuery grabs the HTML just perfectly and sends it to the PHP controller, but the PHP butchers some of the content (removing some tags, every so often).
For example, if I submit
<div class="cmsedit" style="background-color:#EEE">Hello</div>
it will save/write the file with this
div class="cmsedit">Hello</div> .
It removes the opening bracket to the div and the b. It doesnt do it all the time. If I don't include a style tag, it generally leave the code just fine.
Here is the code I'm using on the javascript page.
$('.save_page').click(function(){
updated_content = $('.content_to_be_edited').html();
edit_page = $('#edit_page_name').val();
$.post("<?=site_url('admin/update_page_data') ?>", { content:updated_content,page_name:edit_page });
});
Here is the PHP Controller Page
$page_content = $this->input->post('content');
$page_name = $this->input->post('page_name');
$filename = $_SERVER['DOCUMENT_ROOT']."/application/views/".$page_name.".php";
// SAVE NEW FILE
$file = fopen($filename, 'w') or die("Can't open file");
$filedata = htmlspecialchars_decode($page_content);
fwrite($file, $filedata);
fclose($file);
Anyone have any ideas why the tags are getting all screwed up when the PHP processes the data? Thanks!!
Most likely you have the codeigniter XSS filter active which will destroy your data.
You can disable it and then it should work.