php create file in directory - javascript

The below code checks for a directory 'dat'; if it ins't there, it creates one. That part works just fine; what I need is for it to write a file to said directory where AJAX can read it from.
Here's the php...
//checks for 'dat' directory; if false, creates it, if true, does nothing.
$dir = 'c:\wamp\www\dat';
if(file_exists($dir)){
return;
}
else{
mkdir ('C:\wamp\www\dat',0700);
}
//writes chats to file
$data = fopen($dir. "/chatlog". date('d'). '.txt', 'a+');
fwrite($data, $speak);
fclose($data);
}
And here's the AJAX; I don't need as much help here as I do above, but I won't complain if you provide the help for the AJAX below, mainly in getting it to read from the file within the 'dat' directory...
xhr.open("GET","chatlog<?php /*stamps the chatlog file with date (numerical day only)*/ echo date("d");?>.txt",true);

Your PHP script is running inside www, then, your file you be created there.
If you want to create the file inside the directory www/dat, just change this line
$file = "chatlog". date('d'). ".txt";
for this one
$file = 'dat\chatlog'. date('d'). '.txt';

Related

PHP is not writing to file

I'm trying to pass a variable ( n ) from a JS script to PHP thru the URL and get it to write said variable to a file. Unfortunately I can see the PHP script being called over the network, with the appropriate URL and with 200 status, but it doesn't seem to be executing. The file it should be writing to never changes. The disk is not full, the file is not in use by another process and the file it is writing to has completely open permissions as a testing measure. Hopefully this is a simple fix, thanks in advance.
<?php
$my_file='count.txt';
$count= $_GET['n'];
$handle = fopen($my_file, 'w');
fwrite($handle, $count);
fclose($handle);
?>
Examples of requests being sent
Your code is working fine and its writing whatever value for n is passed. however it keeps on overwriting previous value for every new request.
$handle = fopen($my_file, 'w');
In 'w' mode it create new file for read and write while placing pointer at the beginning.
Use 'w+' mode this places the pointer at the end of file.
$handle = fopen($my_file, 'w+');
For more details on files you can check below url for different modes and other functions
http://php.net/manual/en/function.fopen.php

filesize is changing during download

i have a pdf file that if downloaded through the viewer it downloads at the correct file size but when i use this code for say download selected the file size of the pdf changes and renders it useless when you open with adobe/nitro/etc.
<?php
#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 'Off');
if (isset($_GET['url'])) {
$fullPath = $_GET['url'];
if($fullPath) {
#$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
header("Content-type: application/pdf"); // add here more headers for diff. extensions
break;
default;
header("Location: ".$fullPath);
exit;
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
fopen($fsize, "r");
exit;
}
}
?>
i noticed the file size is 24kb on the server. i go to url and view it then click the download from pdf viewer the file downloads just fine and verified the filesize in my download folder at 24kb. however when i use this code above as my download.php it downloads but comes back as 2kb.
can someone help me figure out why its changing the file size please?
I don't see any code where you are actually sending the file.Make sure you actually send the file. You have used fopen() but you are not using fread() that's why files is getting opened but not getting being read may be that's why it's showing some default output which amounts to 2kb . You can use the much simpler readfile() instead
For that replace this line
fopen($fsize, "r");
with this one
readfile('path/to/' . $path_parts["basename"]);
Just in case you are handling huge files like several MBs then fopen will suite you better as it would be more memory efficient.Also note the b flag in fopen() parameter it refers to binary mode so whenever you are sending a binary file like pdf,images etc you should always use this flag
set_time_limit(0);
$file = #fopen('path/to/' . $path_parts["basename"],"rb");
while(!feof('path/to/' . $path_parts["basename"]))
{
print(#fread('path/to/' . $path_parts["basename"], 1024*2));
ob_flush();
flush();
}
the problem was the / in the url it was starting with. once i added a trim to the url it worked. tbh now that i started looking into this i dont think it really ever work just appeared it did.
$trmfullPath = $_GET['url'];
$fullPath = trim($trmfullPath, "/");
this seemed to fix it. also dont get any errors in my php error log now.

Modify a local JS-file using php and javascript

Information
For testing purposes I am building a system where a javascript file contains an array called "contains".
The javascript will then make the browser redirect to another page where the php-code is located, and that code should add the keyword as a new array-element
And before anyone of you try to say how simple this is, let me reiterate that I am injecting the JS code on another page using Tampermonkey, and I have no chance to modify their code
The code should then be converted to JS again and be written to a file which is called "copyright.js"
Code
At the moment the "copyright.js" file looks like this
var contains = ["original"]
The following code returns a positive result
$str = 'var contains = ["original"]';
$str = str_replace("var ", '$', $str);
eval($str.";");
But when I try to fetch the variable from the file i get an error
$file = fopen('copyright.js', 'r') or die('Unable to open File');
$str = fread($file, filesize('copyright.js'));
fclose($file);
$str = str_replace("var ", '$', $str);
eval($str.";");
If there is a better solution to this, please don't hesitate to tell me :)

Issue saving file with PHP script

I'm making a PHP script for a JavaScipt site I've made.
The goal is to save the contents of a string as an HTML file when I click a button.
I'm using jQuery to make a Post request.
I'm using an Ubuntu OS with an Apache 2 server. The folder I'm writing to has permissions 777 (for testing only, will repeal this).
A requirement is the PHP must live in another file.
The issue is whenever I make the request, the file saves blank.
A requirement is each filename must be a timestamp. The file has the correct file name, but not contents.
So far, here is my code:
<?php
$fileName = $_GET['fileNameData'];
$htmlImport = $_GET['htmlToSaveData'];
$htmlToSave = (string)$htmlImport;
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
?>
I've tried the frwite function that I've commented out, same effect.
I have tested this in terminal by passing in arguments ($argv[1] and $argv[2]). That works fine.
The JS I've made to run my site looks like:
var newURL = 'saveHTML.php/?fileNameData=' + fileName + '&htmlToSaveData=' + htmlToSave
$.post(newURL)
.done(function(){
alert('Your file saved as ...' + htmlToSave)
})
I've also tried this code, with the same result:
$.post('saveHTML.php/', {
fileNameData : fileName,
htmlToSaveData : htmlToSave
})
Both the fileName and htmlToSave are strings, although htmlToSave is rather long and is actually html text that I've converted to a string.
Does anyone have ideas about what's going on here? I'm not a PHP developer at all.
I'm using a callback so I can be sure I've collected all my html before I pass the string to PHP.
I've read and tested the recommendations on this question here and this has been fruitless.
EDIT Don't be alarmed about the code, I realise it's a security issue but this is a learning project and this will not be in production.
I can see right off the bat that you have
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
file_put_contents takes a file name, not a handle. So you would only need
file_put_contents($fileName, $htmlToSave);
Edit: I also feel like I should point out that you should not allow your users to name your files. They could potentially do some nasty stuff to your machine.

Remove XML Node With jQuery

I wonder whether someone may be able yo help me please.
I've put together this page which allows users to view a gallery of their uploaded images.
Upon initial upload, the physical images are saved in the following file structure:
UploadedFiles/userid/locationid/image and the details of the image i.e. description etc are saved in an xml file called files.xml which is in the same directory as the physical images.
I'm now working on allowing the user to be able to delete these images.
By way of a deletion icon under each image, I've, admitedly with some help, put together the following which successfully deletes the physical image.
'Deletion Icon Onclick Event'
<script type="text/javascript">
Galleria.ready(function() {
this.$('thumblink').click();
$(".galleria-image").append(
"<span class='btn-delete ui-icon ui-icon-trash'></span>");
$(".btn-delete").live("click", function(){
var img = $(this).closest(".galleria-image").find("img");
// send the AJAX request
$.ajax({
url : 'delete.php',
type : 'post',
data : { image : img.attr('src') },
success : function(){
alert('Deleting image... ');
img.parent().fadeOut('slow');
}
});
return false;
});
});
</script>
Original 'delete.php'
<?php
if (!empty($_POST)) {
$image = $_POST['image'];
if (file_exists($image)) {
unlink($image);
}
}
?>
Updated 'delete.php'
<?php
if (!empty($_POST)) {
$image = $_POST['image'];
if (file_exists($image)) {
unlink($image);
}
}
$doc = new DOMDocument;
$doc->load('files.xml');
$thedocument = $doc->documentElement;
$list = $thedocument->getElementsByTagName('files');
$nodeToRemove = null;
foreach ($list as $domElement){
$attrValue = $domElement->getAttribute('file_name');
if ($attrValue == 'image') {
$nodeToRemove = $domElement;
}
}
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);
echo $doc->saveXML();
?>
The problem I'm having is deleting the xml node form the xml file. I've provided an extract of the XML file below.
<?xml version="1.0" encoding="utf-8" ?>
- <files>
<file name="stag.jpg" source="stag.jpg" size="21341" originalname="stag.jpg" description="No description provided" userid="1" locationid="1" />
</files>
I've done quite a bit of research about how to go about this and found that jQuery had it's own command i.e. jQuery.remove which I thought would be able to delete the node. Following the brief tutorial I added the following to the end of my 'Onclick Event' script:
var doc = $(files.xml);
doc.find('file_name:src').remove();
Unfortunately, although I don't receive a specific error, the node isn't being deleted from the file. I'm a complete beginner when it comes to XML so perhaps I'm looking at this too simplistically.
I just wondered wheteher someone could perhaps have a look at this please and let me know where I'm going wrong.
Many thanks and regards
This is because JavaScript(JQuery) loads the XML DOM in memory and then when you delete a node,
it gets deleted from the in-memory xml doc(the object).
It wont be removed from the physical XML file.
JS runs in a sandbox Browser environment and cannot alter local files on the system.
and if you are trying to load xml from a remote server then its a very bad idea.
the XML file from remote server is downloaded as temp file and then when you load XML again an in-memory DOM is created and the node is deleted from it.
So in case you want the actual file to be changed,
you will need to use AJAX and send some HTTP request to your server to do the same to the physical file.
UPDATE:
Check this tutorial
http://www.phpeveryday.com/articles/PHP-XML-Removing-Node-P415.html
and try to load the xml file in your delete.php and remove the corresponding node from it and then save this xml back to the original file which will be overwritten.

Categories