I've downloaded files from my svn that are now stored in a folder on my local disk. The folder name is cs_DATA and within the folder I have another folder which contains all the files (unncessary but I just saved it that way). These files are the code files I have stored in subversion. Most of these files are php files. How can I read in documents (that aren't "txt") which are located on my local disk and open them on a website that uses php. Currently when I load them in, it echoes out as an empty string. This is what I have
index.php
<script>
$(function() {
$('#getData').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "endPoint.php",
data : { field2_name : $('#userInput2').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#displayParse").html(html);
//$('[name=field1_name]').val('');
}
});
});
});
</script>
<form id="comment_form" action="endPoint.php" method="GET">
Enter the file you would like to view:
<input type="text" class="text_cmt" name="field2_name" id="userInput2"/>
<input type="submit" name="submit" value="submit" id = "getData"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id="displayParse">
</div>
endPoint.php
<?php
$filePath = $_GET["field2_name"];
$url = "cs_DATA/files/" . $filePath;
$contents = file_get_contents($url);
echo '<div class="comment">', htmlspecialchars($contents),'</div>';
?>
Nothing is printing out so I can only assume that how I'm accessing my local files is incorrect. I've written my code on phpstorm and am running it on a localhost. The files I need to have access are all stored on my computer. Not sure if that affects it in any way.
Related
Hi everyone I had written code to capture image of div tag when click on button and javascript code will capture that image ,but i want to save that captured image using codeigniter but we can't using default codeigniter upload method because upload only work for input type file which create one object but here getting captured image by javascript so i want to upload that image in folder so please tell me how to do that using codeigniter.below i mentioned my code.
Html code....
<div id="target" style="border: 1px solid #CCC;padding: 5px;margin: 5px;">
<div>
<p>PHP is a server-side scripting language designed primarily for web development.</p>
</div>
</div>
<form method="POST" enctype="multipart/form-data" id="form1">
<input type="hidden" name="img_value" id="img_value" value="" />
</form>
<input type="submit" value="Screenshot" onclick="capture();" />
javascript code to captured image and call ajax to save image
<script type="text/javascript">
function capture() {
$('#target').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data
$('#img_value').val(canvas.toDataURL("image/png"));
//Submit the form1
var hid_img=$("#img_value").val();
$.ajax({
url: "<?= base_url('controller/save_img') ?>",
type: "POST",
data: {
hid_img: hid_img,
},
success: function (response) {
$(".show_img").html(response);
}
});
}
});
}
</script>
code in controller method of codeigniter to save image in folder...
public function save_img() {
$data = $this->input->post($hid_img);
$file = md5(uniqid()) . '.png';
// remove "data:image/png;base64,"
$uri = substr($data,strpos($data,",")+1);
// save to file in uploads folder of codeigniter
file_put_contents('./uploads'.$file, base64_decode($uri));
}
to store image in table
$res=$this->db->insert('demo',array('img'=>base_url('uploads/').$file));
$detail = $this->db->select('*')->from('demo')->where('id', $this->db->insert_id())->get()->row();
echo '<img src="'.base_url('uploads/').$detail->message.'" style="width:500px;"/>';
As you correctly elucidated the upload library only works with file inputs and not base64 streams. So you can't use that.
Using your method, you have a few errors in your code that need to be addressed:
$this->input->post($hid_img) should be $this->input->post('hid_img')
./uploads should probably have an end slash: './uploads/'.$file
Use this sample. It is working good. First, if you check upload library.
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('taskcat_img'))
{
echo $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$imgval = array('success' => 'success' ,'data_image' => $data["file_name"]);
echo json_encode($imgval );
}
My intention is to delete file from folder But Here in above script is not working properly can any one please suggest me about this
function deleteFile()
{
var myObject;
myObject = new ActiveXObject("Scripting.FileSystemObject");
myObject.DeleteFile("D:\\WEBSITE_FILES\\docs\\OTR\\"+db_unicid+"\\passportImage.jpg");
return true;
}
<input type='Button' value='Click to Delete File' onClick='return deleteFile()'>
You cannot delete files with Javascript. It mostly has to do with security issues. Also, right now ActiveX Object is only supported by IE, so you'll have troubles with it in every other browser. You should do it just with PHP or with an Ajax call to a PHP file.
the PHP (this would be a file called deleteFile.php)
<?php
unlink($_GET['file']);
?>
and the JavaScript
function deleteFile()
{
$.ajax({
url: 'deleteFile.php',
data: {'file' : "<?php echo dirname(__FILE__) . '/uploads/'?>" + file_name },
success: function (response) {
// do something
},
error: function () {
// do something
}
});
}
<input type='Button' value='Click to Delete File' onClick='return deleteFile()'>
I'm trying to upload a PDF document using AJAX, but it keeps on failing with an unknown error. What am I doing wrong?
HTML File:
<form id="document">
<p>
Title<br>
<input type="text" name="name" size="30">
</p>
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input id="submit-button" type="button" value="Send">
</div>
</form>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#submit-button').click(function() {
$.ajax({
type: "POST",
dataType: "JSON",
url: "upload_document.php",
data: $("#document").serialize(),
success : function(data){
alert(data.message);
}, error : function(data) {
alert(data.message);
}
});
});
});
</script>
PHP File (upload_document.php)
<?php
header("Access-Control-Allow-Origin: *");
try {
$id = "[RANDOM_GENERATED_GUID]";
$targetDir = "../../../../modules/sites/documents/";
if (!is_dir($targetDir)) {
if (!mkdir($targetDir, 0777, true)) {
throw new Exception("Unable to upload your document. We were unable to create the required directories");
}
}
$targetFile = $targetDir . $id . ".pdf";
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
if (file_exists($targetFile)) {
throw new Exception("Unable to upload your document. The file already exists");
}
if ($_FILES["datafile"]["size"] > 2000000) {
throw new Exception("Unable to upload your document. The file is to large (Maximum of 2MB)");
}
if ($fileType != "pdf") {
throw new Exception("Unable to upload your document. Only PDF documents can be uploaded");
}
if (!move_uploaded_file($_FILES["datafile"]["tmp_name"], $targetFile)) {
//Keeps failing here with error code 0
throw new Exception("Unable to upload your document. There was an error uploading the file");
}
echo json_encode(array(
"error" => false,
"message" => "Your document was successfully uploaded"
));
} catch (Exception $ex) {
echo json_encode(array(
"error" => true,
"message" => $ex->getMessage()
));
}
I also checked on the server, and the directory is being created successfully. Thanks for the help!
Edit
This exact same PHP script works if I set the action on the form, and use a submit button. The only reason I want to use AJAX, is to display a modal dialog after receiving a response
When you start using AJAX POST, the posted parameter should be looked for in $_POST instead of $_FILES.
This is because $_FILES is a cache for files uploaded through multipart post. Since you have serialized it and sent using AJAX, PHP parses the JSON and put everything inside $_POST
Look here for an example
I want to uplod multiple files through ajax but I can't figure out how I can grab the files in PHP. Can anyone help me? Thank you!
Here is the code:
HTML:
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file" multiple="multiple" name="file"/>
</form>
<div id="info"></div>
<div id="preview"></div>
JavaScript:
$(document).ready(function(){
$("#file").change(function(){
var src=$("#file").val();
if(src!="")
{
formdata= new FormData(); // initialize formdata
var numfiles=this.files.length; // number of files
var i, file, progress, size;
for(i=0;i<numfiles;i++)
{
file = this.files[i];
size = this.files[i].size;
name = this.files[i].name;
if (!!file.type.match(/image.*/)) // Verify image file or not
{
if((Math.round(size))<=(1024*1024)) //Limited size 1 MB
{
var reader = new FileReader(); // initialize filereader
reader.readAsDataURL(file); // read image file to display before upload
$("#preview").show();
$('#preview').html("");
reader.onloadend = function(e){
var image = $('<img>').attr('src',e.target.result);
$(image).appendTo('#preview');
};
formdata.append("file[]", file); // adding file to formdata
console.log(formdata);
if(i==(numfiles-1))
{
$("#info").html("wait a moment to complete upload");
$.ajax({
url: _url + "?module=ProductManagement&action=multiplePhotoUpload",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res){
if(res!="0")
$("#info").html("Successfully Uploaded");
else
$("#info").html("Error in upload. Retry");
}
});
}
}
else
{
$("#info").html(name+"Size limit exceeded");
$("#preview").hide();
return;
}
}
else
{
$("#info").html(name+"Not image file");
$("#preview").hide();
return;
}
}
}
else
{
$("#info").html("Select an image file");
$("#preview").hide();
return;
}
return false;
});
});
And in PHP I get $_POST and $_FILES as an empty array;
Only if I do file_get_contents("php://input"); I get something like
-----------------------------89254151319921744961145854436
Content-Disposition: form-data; name="file[]"; filename="dasha.png"
Content-Type: image/png
PNG
���
IHDR��Ò��¾���gǺ¨��� pHYs��������tIMEÞ/§ýZ�� �IDATxÚìw`EÆgv¯¥B-4 ½Ò»tBU©)"¶+*"( E¥J7ôÞ;Ò¤W©¡&puwçûce³WR¸ èóûrw»³ï}fö
But I can't figure out how to proceed from here.
I am using Jquery 1.3.2 maybe this is the problem?
Thank you!
Sorry about the answer, but I can't add a comment yet.
I would recommend not checking the file type in javascript, it is easily bypassed. I prefer to scrutinise the file in PHP before allowing it to be uploaded to a server.
e.g.
This answer taken from another question (uploaded file type check by PHP), gives you an idea:
https://stackoverflow.com/a/6755263/1720515
<?php
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
?>
You can read the documentation on the exif_imagetype() function here.
Could you post your PHP code please? And I will update my answer if I have anything to add.
UPDATE:
NOTE: The 'multiple' attribute (multiple="multiple") cannot be used with an <input type='file' /> field. Multiple <input type='file' /> fields will have to be used in the form, naming each field the same with [] added to the end to make sure that the contents of each field are added to an array, and do not overwrite each other when the form is posted.
e.g.
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file_0" name="img_file[]" />
<input type="file" id="file_1" name="img_file[]" />
<input type="file" id="file_2" name="img_file[]" />
</form>
When the form is submitted, the contents of any <input type='file' /> fields will be added to the PHP $_FILES array. The files can then be referenced using $_FILES['img_file'][*parameter*][*i*], where 'i' is key associated with the file input and 'paramter' is one of a number of parameters associated with each element of the $_FILES array:
e.g.
$_FILES['img_file']['tmp_name'][0] - when the form is submitted a temporary file is created on the server, this element contains the 'tmp_name' that is generated for the file.
$_FILES['img_file']['name'][0] - contains the file name including the file extension.
$_FILES['img_file']['size'][0] - contains the file size.
$_FILES['img_file']['tmp_name'][0] can be used to preview the files before it is permanently uploaded to the server (looking at your code, this is a feature you want to include)
The file must then be moved to its permanent location on the server using PHP's move_uploaded_file() function.
Here is some example code:
<?php
if (!empty($_FILES)) {
foreach ($_FILES['img_file']['tmp_name'] as $file_key => $file_val) {
/*
...perform checks on file here
e.g. Check file size is within your desired limits,
Check file type is an image before proceeding, etc.
*/
$permanent_filename = $_FILES['img_file']['name'][$file_key];
if (#move_uploaded_file($file_val, 'upload_dir/' . $permanent_filename)) {
// Successful upload
} else {
// Catch any errors
}
}
}
?>
Here are some links that may help with your understanding:
http://www.w3schools.com/php/php_file_upload.asp
http://php.net/manual/en/features.file-upload.multiple.php
http://www.sitepoint.com/handle-file-uploads-php/
Plus, some extra reading concerning the theory around securing file upload vulnerabilities:
http://en.wikibooks.org/wiki/Web_Application_Security_Guide/File_upload_vulnerabilities
You can use ajax form upload plugin
That's what i have found couple of days ago and implemented it this way
Ref : LINK
You PHP Code can be like this
uploadimage.php
$response = array();
foreach ($_FILES as $file) {
/* Function for moving file to a location and get it's URL */
$response[] = FileUploader::uploadImage($file);
}
echo json_encode($response);
JS Code
options = {
beforeSend: function()
{
// Do some image loading
},
uploadProgress: function(event, position, total, percentComplete)
{
// Do some upload progresss
},
success: function()
{
// After Success
},
complete: function(response)
{
// Stop Loading
},
error: function()
{
}
};
$("#form").ajaxForm(options);
Now you can call any AJAX and submit your form.
You should consider below code
HTML
<input type="file" name="fileUpload" multiple>
AJAX
first of all you have to get all the files which you choose in "input type file" like this.
var file_data = $('input[type="file"]')[0].files;
var form_data = new FormData();
for(var i=0;i<file_data.length;i++)
{
form_data.append(file_data[i]['name'], file_data[i]);
}
then all your data is in formData object now you can send it to server(php) like this.
$.ajax({
url: 'upload.php', //your php action page name
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (result) {
// code you want to execute on success of ajax request
},
error: function (result) {
//code you want to execute on failure of ajax request
}
});
PHP
<?php
foreach($_FILES as $key=>$value)
{
move_uploaded_file($_FILES[$key]['tmp_name'], 'uploads/' .$_FILES[$key]['name']);
}
My html page for uploading has only two things on it: a file open button, and a Submit. It's no problem getting the open dialog up, but after the user clicks OK, where can I find the path string?
</td>
<td style="width: 109.8pt; padding: .75pt .75pt .75pt .75pt" width="146">
<input id="file" name="file" type="file">
<p class="MsoNormal"> </p>
</td>
Does the php file below come with development tools, or is it part of default Windows javaScrpt?
action="upload.php"
Pekka is correct, this has nothing to do with either asp.net or javascript. When you submit a file upload (whether it be in an asp.net app or php) there will be some standard Response information, some of which will be details on the selected file (filename, etc.).
A quick Google search brings up several open source PHP upload utilities, as well as file upload DOM references, such as:
http://sourceforge.net/projects/uploadtool/
http://www.tizag.com/phpT/fileupload.php
http://www.w3schools.com/php/php_file_upload.asp
I'd recommend editing your question to exclude the asp.net tag and replace it with PHP. That way more PHP developers will see your question.
Try the below code
You have to make an "images" folder in the current directory and make two files :
1: Index.php 2: upload.php
You will also get the image name in the success which can be used for saving image name in the database.
1: Index.php
<html>
<head>
<title>
</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" >
var imgName = "";
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST" ,
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
data = JSON.parse(data);
imgName = data.path;
var pic = imgName;
},
error: function () {}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data">
<input type="file" name="pic" id="pic">
<br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
2: Upload.php
<?php
if (is_array($_FILES)) {
if (is_uploaded_file($_FILES['pic']['tmp_name'])) {
$sourcePath = $_FILES['pic']['tmp_name'];
$targetPath = "./images/" .time(). $_FILES['pic']['name'];
if (move_uploaded_file($sourcePath, $targetPath)) {
$imgPath['path']=$targetPath;
echo json_encode($imgPath);
}
}
}