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);
?>
Related
I am making a redeem key page for educational purposes with PHP just to see what it is capable of. I am storing the keys in a txt file as such:
key1
key2
And so on.
I have tried the following to loop through the txt file, insert the values into and array and work off of there. Here is what I have:
$gkey = $_GET["key"];
$file = fopen("./generatedkeys.txt", "a");
$generatedk = array();
// generate table from data in txt file
while(! feof($file)) {
$generatedk[] = fgets($file);
}
foreach ($generatedk as $key){
if ($key == hash("sha256", $gkey)){
// Removing of key from data in txt file
$contents = file_get_contents($file);
$contents = str_replace($key, '', $contents);
file_put_contents($file, $contents);
fclose($file);
$accfile = fopen("./accs.txt", "a");
fwrite($accfile, hash("sha256", $key).",".hash("sha256", $hwid)."\n");
break;
}
}
The code above however doesn't seem to be working. The key is simply not detected and not removed from generatedkeys.txt. (Not sure if there is any errors since I cannot see any).
Is there any obvious mistakes?
Any help is appreciated. Thank you.
I think this should make the process simpler, using file to read the whole file in one go into an array and then using array_search() to find if the key exists (it returns false if not found, so !== false).
Then if found, it just appends the used key to the other file, unsets the array entry for the key and overwrites the original file...
$gkey = $_GET["key"];
$generatedk = file("./generatedkeys.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ( ($entry = array_search(hash("sha256", $gkey), $generatedk)) !== false ) {
// Add key used, with whatever content you want
file_put_contents("./accs.txt", $gkey.PHP_EOL, FILE_APPEND);
// Remove found key from list in input file
unset($generatedk[$entry]);
// Overwrite input file with adjusted array
file_put_contents("./generatedkeys.txt", implode(PHP_EOL, $generatedk));
}
Your code will make some empty lines when erases key from file.
And you passed return value of fopen() as a parameter of file_get_contents(). the return value is resource on file, but file_get_contents() needs string(file path).
You can check following.
$gkey = $_GET["key"];
$file_path="./generatedkeys.txt";
$file = fopen($file_path, "a");
$generatedk = array();
// generate table from data in txt file
while(! feof($file)) {
$generatedk[] = fgets($file);
}
fclose($file);
for($i=0; $i<count($generatedk); $i++){
$key=$generatedk[$i];
if ($key == hash("sha256", $gkey)){
// Removing of key from data in txt file
array_splice($generatedk, $i, 1);
file_put_contents($file_path, implode("\n", $generatedk));
$accfile = fopen("./accs.txt", "a");
fwrite($accfile, hash("sha256", $key).",".hash("sha256", $hwid)."\n");
fclose($accfile);
break;
}
}
I hope it will be working well.
Thanks.
I am new to both PHP and understanding GET/POST. I am using a postbackurl to this phpfile and trying to write GET/POST information to a text file. It's not working and I was hoping someone could point out my likely obvious error to me. Below is the code.
$postback_data = $_REQUEST;
foreach($postback_data as $key=>$var)
{
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$output = $key . ' : ' . $val ."\n";
fwrite($myfile, $output);
fclose($myfile);
}
There are two misconceptions in your code:
You are opening a file, write to it and close it for each $key=>$var in $postback_data which is highly ineffective. You should open it once before the loop and close it after completion of the loop.
You are writing to a file instead of appending. Check the modes for fopen().
Here is the code that might do what you desire:
$postback_data = $_REQUEST;
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
foreach($postback_data as $key=>$var) {
$output = $key . ' : ' . $val ."\n";
fwrite($myfile, $output);
}
fclose($myfile);
If you wish to create a new file for each request, use the "w" mode on fopen(). Use "a" if you want to append every new request’s POST data to the same file.
Place fopen and fclose outside the loop or use fopen('file.txt', a) instead. fopen('file.txt', w) resets the files and overwrites everything.
If your goal is just saving that information into a file to see it and format is not so important, you can achieve that by using a few built-in functions. You don't need to iterate all over the list using foreach:
$post = var_export($_REQUEST, true);
file_put_contents('newfile.txt', $post);
Beware: $_REQUEST also contains $_COOKIE data besides $_POST and $_GET.
var_export here returns string representation of given variable. If you the omit second argument true, it directly prints it.
If your goal is improving your skills, here is the correct version of your code with some notes:
// prefer camelCase for variable names rather than under_scores
$postbackData = $_REQUEST;
// Open the resource before (outside) the loop
$handle = fopen('newfile.txt', 'w');
if($handle === false) {
// Avoid inline die/exit usage, prefer exceptions and single quotes
throw new \RuntimeException('File could not open for writing!');
}
// Stick with PSR-2 or other well-known standard when writing code
foreach($postbackData as $key => $value) {
// The PHP_EOL constant is always better than escaped new line characters
$output = $key . ' : ' . $value . PHP_EOL;
fwrite($handle, $output);
}
// Close the resource after the loop
fclose($handle);
And don't forget to call your file using some test data in your querystring such as: http://localhost/postback.php?bar=baz Otherwise, both $_RQUEST and the contents of the file would be empty since there is nothing to show.
Good luck and welcome to stack overflow!
I am uploading files that I need to attach to email via office365 API.
What I need is the content of the file in a variable WITHOUT storing/saving the file, how can I do that?
foreach ($request->filesToUpload as $file) {
$originalName = $file->getClientOriginalName();//working
$content = $file->getContent();//<- I need this, but not working
//$this->addAttachment($content, $originalName) //logic for later
}
Access the contents of the file like so:
$content = file_get_contents(Input::file('nameAttribute')->getRealPath());
or in other words inside that loop
$contents = file_get_contents($file->getRealPath());
Get the real path with object methods, and you may interact with it like any other file.
Waqas Bukhary,
You get that result, beucause, getContent is not a method of uploadedFiles, check the documentation.
But you have the path, so you can always read the content, like:
$path = $file->path();
$handle = fopen($path, 'r');
$content = fread($handle, filesize($path);
fclose($handle);
You can also use the Request File method if you know the name of the file field, check it here.
I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/
I have small class called 'Call' and I need to store these calls into a flat file. I've made another class called 'CallStorage' which contains an array where I put these calls into.
My problem is that I would like to store this array to disk so I could later read it back and get the calls from that array.
I've tried to achieve this using serialize() and unserialize() but these seems to act somehow strange and part of the information gets lost.
This is what I'm doing:
//write array to disk
$filename = $path . 'calls-' . $today;
$serialized = serialize($this->array);
$fp = fopen($filename, 'a');
fwrite($fp, $serialized);
fclose($fp);
//read array from serialized file
$filename = $path . 'calls-' . $today;
if (file_exists($filename)) {
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
fclose($handle);
$unserialized = unserialize($contents);
$this->setArray($unserialized);
}
Can someone see what I'm doing wrong, or what. I've also tried to serialize and write arrays that contains plain strings. I didn't manage to get that working either.. I have a Java background so I just can't see why I couldn't just write an array to disk if it's serialized. :)
Firstly, use the shorthand forms:
file_put_contents($filepath,serialize($var));
and
$var=unserialize(file_get_contents($filepath));
And then output/debug at each stage to find where the problem is.