write a file on local disk from web app [duplicate] - javascript

I am trying to create and save a file to the root directory of my site, but I don't know where its creating the file as I cannot see any. And, I need the file to be overwritten every time, if possible.
Here is my code:
$content = "some text here";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
How can I set it to save on the root?

It's creating the file in the same directory as your script. Try this instead.
$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);

If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>

This question has been asked years ago but here is a modern approach using PHP5 or newer versions.
$filename = 'myfile.txt'
if(!file_put_contents($filename, 'Some text here')){
// overwriting the file failed (permission problem maybe), debug or log here
}
If the file doesn't exist in that directory it will be created, otherwise it will be overwritten unless FILE_APPEND flag is set.
file_put_contents is a built in function that has been available since PHP5.
Documentation for file_put_contents

fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.
This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.
Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:
$fp = fopen("myText.txt","wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}

Related

Download file: direct access to application google chrome or another way to do it

hello friend i am making an aplication based on web plataform html5 css3 ...
and i have a web site with this, but i thought creat a direct link to shout(pop) this aplication to end user from the desktop.
example:
Descarga Aplicativo
but it not work on chrome or other browser. i get error file or uncomplete download. file named: IcarosNetWeb.downkload ....
Can someone help me with this?
Solved by this way
Direct Access
As not able to find the way to do it directly. I created a free mechanism:
1. Create a .bat file (Batch command line) Hiden.(This is the task: create the shortcut to the application with its parameters.)
Compressing the .bat file within a file self-extracting WinRAR and run the .bat file at the end of the extraction, automatically.
Create Hidden Log File on C:/ if have problem executing.
AutoInstall.bat file
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET LinkName=MyAplication
SET Esc_LinkDest=%%HOMEDRIVE%%%%HOMEPATH%%\Desktop\!LinkName!.lnk
SET Esc_LinkTarget=%%ProgramFiles(x86)%%\Google\Chrome\Application\chrome.exe
SET Esc_WorkDir=%%ProgramFiles(x86)%%\Google\Chrome\Application
SET Esc_Icon=%%ProgramFiles(x86)%%\Google\Chrome\Application\chrome.exe,6
SET Esc_URL=www.google.com
SET Esc_ARG=--app=http://!Esc_URL!/
SET cSctVBS=CreateShortcut.vbs
SET LOG=".\%~N0_runtime.log"
((
echo Set oWS = WScript.CreateObject^("WScript.Shell"^)
echo sLinkFile = oWS.ExpandEnvironmentStrings^("!Esc_LinkDest!"^)
echo Set oLink = oWS.CreateShortcut^(sLinkFile^)
echo oLink.TargetPath = oWS.ExpandEnvironmentStrings^("!Esc_LinkTarget!"^)
echo oLink.WindowStyle = 1
echo oLink.IconLocation = oWS.ExpandEnvironmentStrings^("!Esc_Icon!"^)
echo oLink.Arguments = !Esc_URL!
echo oLink.WorkingDirectory = oWS.ExpandEnvironmentStrings^("!Esc_WorkDir!"^)
echo oLink.Description = "Internet Access"
echo oLink.Save
)1>!cSctVBS!
cscript //nologo .\!cSctVBS!
DEL !cSctVBS! /f /q
)1>> !LOG! 2>>&1
attrib +h !LOG!
in Winrar:
put SFX File option, go Advance Tab and Click SFX FIle, on tab General add folder Extraction C:/ and on Instaltion tab in Instaltion after Extraction field add the full name (no path) .bat aplication.

automatically printing using php

I have pdf files coming in a folder after some duration. I want to print them using php automatically by default printer and after printing those files move to other folder. How can I do this? I am using the code given below but it's not printing anything..Please help..
$printer = "\\\\server\printer";
if($ph = printer_open($printer))
{
$fh = file_get_contents('455.pdf');
printer_set_option($ph, PRINTER_MODE, "RAW");
printer_write($ph, $fh);
printer_close($ph);
}
else
echo "Can't connect to printer";
Here https://www.daniweb.com/web-development/php/threads/449709/php-print-pdf-directly-to-a-printer i found the solution of this issue . i hope it will work for you and use rename('foo/test.php', 'bar/test.php'); for the transfer of all files from one folder to another after printing .

List files, read files as links, php?

This is a strange request I suppose, but I have a directory full of txt files. For example:
- david_smith_interview.txt -
- beth_martin_interview.txt -
- sally_smithart_interview.txt
The contents of these text files are a link to their interview in an mp3 format, for example, if you open the file david_smith_interview.txt, it is simply this:
http://www.interviews/employees/david_smith.mp3
All of the other text files follow the same format. They are simply links to their mp3 interview.
I am trying to use something like below to list the text files:
<?php
$directory = "/employees/";
$phpfiles = glob($directory . "*.txt");
foreach($phpfiles as $phpfile)
{
echo $phpfile; // This will list the files by name
// How can I output something to reflect this:
// david_smith_interview
}
?>
So I am asking is it possible that the text file can be "read" and used as the actual link?
Any thoughts?
Replace _interview.txt with .mp3
echo "" . str_replace(".txt", "", $phpfile). "\";
Since those are .txt files you can just read them one by one to a variable and then echo the result in a for-loop.
In pseudo:
$paths fetch_paths()
$urls = array();
foreach($paths as $path)
{
$url=fopen($path);
array_push($urls,fgets(url)); // Assuming there's only one link per file and it is on one line.
}
foreach($urls as $url)
{
echo <Your formatted link here>
}

Running PHP in text/javascript environment

I'm looking to run this bit of PHP within a text/javascript environment. The point is to display a description for certain media files within the Jplayer Playlister. So how can I run this within a text/javascript environment? If you need an example of the Playerlister working fine, and then breaking upon implementation of the PHP, I can provide that.
Here's the PHP:
// CONFIGURE THESE VARIABLES:
// actual place where your mp3s live on your server's filesystem. TRAILING SLASH REQ'D.
$musicDirectory="myServerPathHere";
// corresponding web URL for accessing the music directory. TRAILING SLASH REQ'D.
$musicURL="myURLhere";
// step through each item...
$fileDir = opendir($musicDirectory) or die ($php_errormsg);
while (false !== ($thisFile = readdir($fileDir))) // step through music directory
{
$thisFilePath = $musicDirectory . $thisFile;
if (is_file($thisFilePath) && strrchr ($thisFilePath, '.') == ".mp3") // not . or .., ends in .mp3
{
// only include files that have a corresponding .txt file
$thisTextPath = substr_replace($thisFilePath, ".txt", (strlen($thisFilePath) - 4));
if (is_file($thisTextPath))
{
$myFullURL=$musicURL . $thisFile;
$myFileSize=filesize($thisFilePath);
$textContents = file($thisTextPath);
foreach ($textContents as $thisLine) echo htmlspecialchars($thisLine) . "\n";
}
}
}
closedir($fileDir);
It's possible I don't fully understand what you're asking, so forgive me if that is the case, but what you seem to be asking is how to run PHP client side.
The simple answer is you can't.
PHP is a server-side language. To accomplish what you're trying to do you need to pass some data from PHP to your javascript.
This has always been a bit of a tricky thing to do for me. I usually resort to setting my variables via an on-page <script> tag like this:
<script>
var myJSVar = <?= $myPHPVar ?>
</script>
I've also used a simple JS object to configure a later script using this same method. There are also some neat tools that enable you to create JSON objects from your PHP objects and pass that to the client side. This makes things pretty smooth, and I recommend you check it out on your own.

How can I make the browser see CSS and Javascript changes?

CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.
Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.
Could use the SVN revision number to automate this for you: ASP.NET Display SVN Revision Number
Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file.
In the Subversion book it says about Revision: "This keyword describes the last known revision in which this file changed in the repository".
Firefox also allows pressing CTRL+R to reload everything on a particular page.
To clarify I am looking for solutions that don't require the user to do anything on their part.
I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP:
function urlmtime($url) {
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
if ($path[0] == "/") {
$filename = $_SERVER['DOCUMENT_ROOT'] . "/" . $path;
} else {
$filename = $path;
}
if (!file_exists($filename)) {
// If not a file then use the current time
$lastModified = date('YmdHis');
} else {
$lastModified = date('YmdHis', filemtime($filename));
}
if (strpos($url, '?') === false) {
$url .= '?ts=' . $lastModified;
} else {
$url .= '&ts=' . $lastModified;
}
return $url;
}
function include_css($css_url, $media='all') {
// According to Yahoo, using link allows for progressive
// rendering in IE where as #import url($css_url) does not
echo '<link rel="stylesheet" type="text/css" media="' .
$media . '" href="' . urlmtime($css_url) . '">'."\n";
}
function include_javascript($javascript_url) {
echo '<script type="text/javascript" src="' . urlmtime($javascript_url) .
'"></script>'."\n";
}
Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.
<script type="text/javascript" src="funkycode.js?v1">
You could use the SVN revision number to automate this for you by including the word LastChangedRevision in your html file after where v1 appears above. You must also setup your repository to do this.
I hope this further clarifies my answer?
Firefox also allows pressing CTRL + R to reload everything on a particular page.
In my opinion, it is better to make the version number part of the file itself e.g. myscript.1.2.3.js. You can set your webserver to cache this file forever, and just add a new js file when you have a new version.
When you release a new version of your CSS or JS libraries, cause the following to occur:
modify the filename to include a unique version string
modify the HTML files which reference the library to point at the versioned file
(this is usually a pretty simple matter for a release script)
Now you can set the Expires for the CSS/JS to be years in the future. Whenever you change the content, if the referencing HTML points to a new URI, browsers will no longer use the old cached copy.
This causes the caching behavior you want without requiring anything of the user.
I was also wondering how to do this, when I found grom's answer. Thanks for the code.
I struggled with understanding how the code was supposed to be used. (I don't use a version control system.) In summary, you include the timestamp (ts) when you call the stylesheet. You're not planning on changing the stylesheet often:
<?php
include ('grom_file.php');
// timestamp on the filename has to be updated manually
include_css('_stylesheets/style.css?ts=20080912162813', 'all');
?>

Categories

Resources