Is it possible rewrite php file using fwrite without removing php comments? - php

I have some php file and it contains some comments.
<?php
$test = array(
'LBL_TEXT' => 'text',//test comment
'LBL_FOO' => 'foo'
);
Now I need to update 'LBL_TEXT' value(text) above file without removing comment('//test comment'). Is it possible using fwrite() or some other way.

So you will need something like
<?php
$data = file_get_contents("foo.php");
$data = so something clever to automatically change string as desired;
file_put_contents("foo.php",$data);
?>

Related

change variable value in a file in php

I have a file which is a small place_config.php file.
Take this as an example where i am setting my variables
<?php
//config file
$place_config = array(
'credentials' => array(
'sid' => 'some_value',
'token' => 'some_token'
)
?>
I want to change the sid and token from the admin panel of the user for the ease. How can i effectively achieve this. One solution which i understand is to make the content of the file in a string with the variables of $_REQUEST placed after the post request write that whole string to the file? Is it a effective approach?
Submit a form with the proper inputs and when submitted call update_place_config():
function update_place_config() {
include('place_config.php');
$place_config['credentials']['sid'] = $_POST['sid'];
$place_config['credentials']['token'] = $_POST['token'];
$output = '<?php $place_config = ' . var_export($place_config, true) . '; ?>';
file_put_contents('place_config.php', $output);
return $place_config; //if you want to get the new config
}
Another option:
$content = file_get_contents('place_config.php');
$content = preg_replace("/('sid' =>) '[^']+'/", "$1 '{$_POST['sid']}'", $content);
file_put_contents('place_config.php', $content);
I personally would store in a database or use JSON if it needs to be a file.
Instead of storing the configuration data in a php file, I'll recommend storing them in a json file which can be easily read/edited through php.
Create a json file, let's say config.json. Then you can load the configuration using $conf = json_decode(file_get_contents("config.json")). You can make changes to the $conf object and save back the configurations as file_put_contents("config.json", json_encode($conf)).

Trying to send an <a> that includes a serialized PHP array through JSON-encoded AJAX

I have a link that looks like this being generated in a php file called through AJAX:
To get this:
<?php
$other_info = 'Download');
$retval = array('link' => $other_info);
echo json_encode($retval);
?>
I'm having trouble handling this on the front end. I tried enclosing it like this:
$other_info = htmlspecialchars($other_info);
but I can't get it to come through in a way I can handle on the front. It seems to enclose it in an additional set of double-quotation marks. How can I escape it out?
EDIT: I forgot to add this line, I apologize: $retval = array('link'
=> $other_info); It has been added to the code.
I was able to figure out a way to do it. On the PHP side:
$other_info = htmlspecialchars(serialize($_REQUEST));
and on the javascript side:
var oi = resp.link
oi = 'Download'
That fixed it.

Notice: Array to string conversion in {Error}

I have to make a directory and save the file, but there is an error that written in title. Help me to solve this error. My code is below.
function main() {
$scrapper = new Cloaked_Scraper();
// Prefix of URL's
$url_prefix = "link";
// URL
$urls = array("www.something.com?");
// Get ID from every URL and will save on index one of $url array
$urls[1] = ((explode("www.something.com?id=com.", $urls[0])));
$urls[0] = $url_prefix;
$urls[0];
$urls[1];
//mkdir("../temp/", 0777 /* The mode is 0777 by default, which means the widest possible access */);
// Destination folder where this file will save, and file name.
$output_dir[0] = "../temp/".$urls[0].$urls[1].".html";
$results = $scrapper->fetch($urls, $output_dir);
var_dump($results);
}
main();
I don't know what Cloaked_Scraper is, but it seems that its fetch method only accepts a string as its first or second parameter. You pass an array to both of them.
I think $output_dir needs to be a normal string, but by assigning to $output_dir[0] you implicitly make it an array.
Change that line to this and see what happens:
$output_dir = "../temp/".$urls[0].$urls[1].".html";
But in general, I think your code is very confusing. It seems like you are recycling items of the $urls array while you should actually use separate variables.
$urls[1] = ((explode("www.something.com?id=com.", $urls[0])));
explodes a String to an Array of strings, in detail, $urls[1] contains: array( '', 'id=com');
You now try to insert this Array as a this Line:
$output_dir[0] = "../temp/".$urls[0].$urls[1].".html";
Just use the correct index for the String:
$output_dir[0] = "../temp/".$urls[0].$urls[1][0].".html";

PHP Include an Array

I am creating a flat file login system for a client (as their IT team does not want to give us a database)
I have worked off this:Easy login script without database which works perfect however...
I need to add a large list of logins and wanted to include them in a septrate file rather than in that script.
I have something like this:
<?php
session_start();
// this replaces the array area of the link above
includes('users.php');
//and some more stuff
?>
And in the users file I have
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
However it just literally outputs the text from that file. Is there a way I can include it so it just runs like it was in the main script?
Cheers :)
Include in PHP works simply like a reference to other piece of code AND any other content. So you should enclose the contents of the file in the <?php tags so it would be parsed as PHP.
You may as well return anything from an included file (I mention this as this in your case is the best solution):
mainfile.php
<?php
session_start();
// this replaces the array area of the link above
$userinfo = include('users.php');
users.php
return array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
The statement name is actually include, and not includes.
Try the following:
include 'users.php';
And if your code is getting outputted as text, then it's probably because you've missed the opening <?php tags. Make sure they're present.
users.php should look something like this:
<?php
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
However, the closing tag is not a requirement and your code will work fine without it.
In Yii framework (configs for exmaple) it's done like this
$users = include('users.php');
users.php:
<?php
return array(
'user1' => array(...),
'user2' => array(...),
);
Make sure you have an opening PHP tag in the included file:
<?php
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
users.php :
<?php
function getUsers(){
return array(
'user1' => array(...),
'user2' => array(...),
);
}
Some bootstrap file
include('users.php');
$myUsers = getUsers();

Making a template with vars and file_get_contents in PHP

I have a php page that is reading from a file:
$name = "World";
$file = file_get_contents('html.txt', true);
$file = file_get_contents('html.txt', FILE_USE_INCLUDE_PATH);
echo $file;
In the html.txt I have the following:
Hello $name!
When I go to the site, I get "Hello $name!" and not Hello World!
Is there a way to get var's in the txt file to output their value and not their name?
Thanks,
Brian
The second param of file_get_contents has nothing to do with how to interpret the file - it's about which pathes to check when looking for that file.
The result, however, will always be a complete string, and you can only "reinterpolate" it with evial.
What might be a better idea is using the combination of include and output control functions:
Main file:
<?php
$name = "World";
ob_start();
include('html.tpl');
$file = ob_get_clean();
echo $file;
html.tpl:
Hello <?= $name ?>
Note that php tags (<?= ... ?>) in the text ('.tpl') file - without it $name will not be parsed as a variable name.
One possible approach with predefined values (instead of all variables in scope):
$name = "World";
$name2 = "John";
$template = file_get_contents ('html_templates/template.html');
$replace_array = array(
':name' => $name,
':name2' => $name2,
...
);
$final_html = strtr($template, $replace_array);
And in the template.html you would have something like this:
<div>Hello :name!</div>
<div>And also hi to you, :name2!</div>
To specifically answer your question, you'll need to use the 'eval' function in php.
http://php.net/manual/en/function.eval.php
But from a development perspective, I would consider if there was a better way to do that, either by storing $name somewhere more accessible or by re-evaluating your process. Using things like the eval function can introduce some serious security risks.

Categories