Create dynamic text file with php function - php

So I need to create a dynamic text file based on the name of a variable in php (ex: dynamicName.txt). I then need to write other variables in the file.
$testVar = "test.txt";
function sendCalc(){
global $testVar;
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$testVar");
$fp = fopen($objCalcTxt, 'x');
fwrite($fp, "Test\n");
fclose($fp);
When I do the above, the file is created with no problem, and all the data is written successfully. However, this is not a dynamic file name.
$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc(){
global $objName;
global $ext;
global $dynamicNameTxt;
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");
$fp = fopen($objCalcTxt, 'x');
fwrite($fp, "Test\n");
fclose($fp);
When I try to concatenate the variable that contains the dynamic file name ($objName), with the $ext var, it does not want to create the file.
I echoed the $dynamicName var and it returns dynamicName.txt, so why doesn't this work with fopen. Essentially it has to be a problem with the concatenation right? If so, can I either concatenate a different way, or use a different method to open/create the file?
All help/ideas are appreciated.

I do not really know what you're trying to achieve with the line
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");
if from what i understand it should just be a string:
$objCalcTxt = "C:\\xampp\\htdocs\\test.new\\upload\\".$dynamicNameTxt;
Also I'd suggest you provide the needed variables as arguments for the function insted of using globals
function sendCalc($objName, $ext, $dynamicNameTxt){
...
}

You are declaring the global variables inside your function. This could destroy their initial values.
Instead of using global variables in your function, rather pass the variables as arguments:
$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc(objName, $ext, $dynamicNameTxt)
{
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");
$fp = fopen($objCalcTxt, 'x');
fwrite($fp, "Test\n");
fclose($fp);
}
Your other option is to specifically call the global variable:
global $objName;
global $ext;
global $dynamicNameTxt;
$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc()
{
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\".$GLOBAL['dynamicNameTxt']);
$fp = fopen($objCalcTxt, 'x');
fwrite($fp, "Test\n");
fclose($fp);
}

Related

Creating a virtual file from string

I'm using a library which take as a parameter a file to open it with fopen and read it with fseek and fread
Here what the constructor look like :
public function __construct($file) {
$this->file = $file;
$this->h = fopen($this->file, "r");
$stats = fstat($this->h);
$this->size = $stats['size'];
}
The data which i like to give to this constructor come from a database, so basically i have a variable with some text in it.
Is there a way to emulate a file from the variable containing the data ?
I have tried to use stream with php://memory without any luck ($stats = fstat($this->h) = 0) :
$data = " my string data";
$virtualfile = 'php://memory';
$h = fopen($path, "rw+");
fwrite($h, $data);
$lib = new MyLib($virtualfile);
Any ideas ?
Thanks
You can use the data: url wrapper
$data = " my string data";
$virtualfile='data:text/plain;base64,'.base64_encode($data);
$lib = new MyLib($virtualfile);
fopen returns you a $h pointer to the file - you should pass this pointer to your class to keep working on it, so:
$lib = new MyLib($h);
and constructor:
public function __construct($h) {
$this->h = $h;
$stats = fstat($this->h);
$this->size = $stats['size'];
}

Creating a function in PHP

I use this often and would like to turn it into a function:
$f = fopen('../images/snotel/'. $name .'.pdf','w+');
fwrite($f, $pdf);
fclose($f);
$conv='/usr/bin/convert../images/snotel/'. $name .'.pdf ../images/snotel/'. $name .'.jpg';
system ($conv);
This is what I've tried but it doesn't seem to work:
function pdf2jpg($name)
{
$f = fopen('../images/snotel/'. $name .'.pdf','w+');
fwrite($f, $pdf);
fclose($f);
$conv='/usr/bin/convert../images/snotel/'. $name .'.pdf ../images/snotel/'. $name .'.jpg';
system ($conv);
}
...
pdf2jpg('wsr');
As it is, your function tries to write the file with no data in the $pdf variable, because you did not pass it in.
You need to do one of two things:
This version takes the PDF data as an argument and creates the file in the function:
function pdf2jpg ($pdf, $name) {
$f = fopen('../images/snotel/'.$name.'.pdf','w');
fwrite($f,$pdf);
fclose($f);
$conv = '/usr/bin/convert ../images/snotel/'.$name.'.pdf ../images/snotel/'.$name.'.jpg';
//run
system($conv);
}
// Usage
pdf2jpg($pdf, 'wsr');
This version just takes the name, assuming that the file already exists:
function pdf2jpg ($name) {
$conv = '/usr/bin/convert ../images/snotel/'.$name.'.pdf ../images/snotel/'.$name.'.jpg';
//run
system ($conv);
}
// Usage
$name = 'wsr';
$f = fopen('../images/snotel/'.$name.'.pdf','w');
fwrite($f,$pdf);
fclose($f);
pdf2jpg($name);

Define array of file locations, parse and replace. Where's my error?

I'm trying to define an array with a list of file urls, and then have each file parsed and if a predefined string is found, for that string to be replaced. For some reason what I have isn't working, I'm not sure what's incorrect:
<?php
$htF = array('/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension');
function update() {
global $htF;
$handle = fopen($htF, "r");
if ($handle) {
$previous_line = $content = '';
while (!feof($handle)) {
$current_line = fgets($handle);
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
{
$output = shell_exec('URL.COM');
if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
{
$content .= 'PREDEFINED SENTENCE '.$matches[0]."\n";
}
}else{
$content .= $current_line;
}
$previous_line = $current_line;
}
fclose($handle);
$tempFile = tempnam('/tmp','allow_');
$fp = fopen($tempFile, 'w');
fwrite($fp, $content);
fclose($fp);
rename($tempFile,$htF);
chown($htF,'admin');
chmod($htF,'0644');
}
}
array_walk($htF, 'update');
?>
Any help would be massively appreciated!
Do you have permissions to open the file?
Do you have permissions to write to /tmp ?
Do you have permissions to write to the destination file or folder?
Do you have permissions to chown?
Have you checked your regex? Try something like http://regexpal.com/ to see if it's valid.
Try adding error messages or throw Exceptions for all of the fail conditions for these.
there's this line:
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
and I think you just want a != in there. Yes?
You're using $htF within the update function as global, which means you're trying to fopen() an array.
$fh = fopen($htF, 'r');
is going to get parsed as
$fh = fopen('Array', 'r');
and return false, unless you happen to have a file named 'Array'.
You've also not specified any parameters for your function, so array_walk cannot pass in the array element it's dealing with at the time.

Using fwrite() to set a variable in a file

I have two php files: one is called key.php and the other is the function that validates the key. I want to regularly write to the key.php file and update the key from the validator.php file.
I have this code:
$fp = fopen('key.php', 'w');
$fwrite = fwrite($fp, '$key = "$newkey"');
What I'm trying to do is set the $key variable in the file key.php to the value of $new key which is something like $newkey = 'agfdnafjafl4'; in validator.php.
How can I get this to work (use fwrite to set a pre-existing variable in another file aka overwrite it)?
Try this:
$fp = fopen('key.php', 'w');
fwrite($fp, '$key = "' . $newkey . '"');
fclose($fp);
This will "overwrite" the variable in a literal sense. However, it won't modify the one you're using in your script as it runs, you'll need to set it ($key = somevalue).
More to the point, you really should be using a database or a seperate flat text file for this. Modifying php code like this is just plain ugly.
for_example, you have YOUR_File.php, and there is written $any_varriable='hi Mikl';
to change that variable to "hi Nicolas", use like the following code:
<?php
$filee='YOUR_File.php';
/*read ->*/ $temmp = fopen($filee, "r"); $contennts=fread($temp,filesize($filee)); fclose($temmp);
// here goes your update
$contennts = preg_replace('/\$any_varriable=\"(.*?)\";/', '$any_varriable="hi Jack";', $contennts);
/*write->*/ $temp =fopen($filee, "w"); fwrite($temp, $contennts); fclose($temp);
?>

Why does "return fopen" fail?

I have a function:
function open($file){
return fopen($file, 'w');
}
This is then called by:
function write($file,$text){
$h = $this->open($file);
fwrite($h,$text);
}
This doesn't work. It returns that fwrite was given an invalid resource stream.
This:
function open($file){
$h = fopen($file, 'w');
return $h;
}
Works fine, but I can't figure out why assigning a variable first works and directly returning fopen() doesn't.
Does it have something to do with the fact that you're within an object? The following script works for me:
<?php
function open($file) {
return fopen($file, 'w');
}
function write($file, $text) {
$h = open($file);
fwrite($h, $text);
}
write("test.txt", "hello\n");
?>
I'm running PHP 5.2.8 on Mac OS X 10.5.7.
It's probably just because you are working in the scope of an object, so it cleans up the resource stream too early - since it passes a resource stream byref, if you have a variable set, its byref'ing the variable instead of trying to do it to the resource stream - so it'll work.
declare a
var $file
then
$this->file = fopen(...)
return $this->file;
this will works because the $file variable has still a reference.

Categories