How do i update a variable in a php file and save it to disk? I'm trying to make a small CMS, in one file, no database, and i'd like to be able to update the config variables, I've made a settings page and when i update i'd like the variables to updated in the php-file.
Below will update the variable, but of course not save it to the php-file, so how do i do that?
<?php
$USER = "user";
if (isset($_POST["s"]) ) { $USER = $_POST['USER']; }
?>
<html><body>
Current User: <?php echo $USER; ?>
<form method="post" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>">
New User<input type="text" name="USER" value="<?php echo $USER; ?>"/>
<input type="submit" class="button" name="s" value="Update" />
</form>
</body></html>
I don't know if i'm missing the obvious?
I was thinking of using something like this:
$newcms = file_get_contents(index.php)
str_replace(old_value, new_value, $newcms)
file_puts_contents(index.php, $newcms)
But it doesn't seem like the right solution...
The easiest way is to serialize them to disk and then load them so you might have something like this:
<?php
$configPath = 'path/to/config.file';
$config = array(
'user' => 'user',
);
if(file_exists($configPath)) {
$configData = file_get_contents($configPath);
$config = array_merge($defaults, unserialize($configData));
}
if(isset($_POST['s']) {
// PLEASE SANTIZE USER INPUT
$config['user'] = $_POST['USER'];
// save it to disk
// Youll want to add some error detection messagin if you cant save
file_put_contents($configPath, serialize($config));
}
?>
<html><body>
Current User: <?php echo $config['user'; ?>
<form method="post" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>">
New User<input type="text" name="USER" value="<?php echo $config['user']; ?>"/>
<input type="submit" class="button" name="s" value="Update" />
</form>
</body></html>
This approach uses PHP's native serialization format which isnt very human readable. If you want to be able to manually update configuration or more easily inspect it you might want to use a different format like JSON, YAML, or XML. JSON will probably be nearly as fast and really easy to work with by using json_encode/json_decode instead of serialize/unserialize. XML will be slower and more cumbersome. YAML is pretty easy to work with too but youll need an external library like sfYaml.
Additionally i wouldnt just do this at the top of a script, id probably make a class of it or a series of functions at the least.
As a better approach, you can have a separate file just for the settings and include that file in the PHP file. Then you can change and save its values as you want instead of modifying the PHP file itself.
for example, you have YOURFILE.php, and inside it you have $targetvariable='hi jenny';
if you want to change that variable, then use this:
<?php
$fl='YOURFILE.php';
/*read operation ->*/ $tmp = fopen($fl, "r"); $content=fread($tmp,filesize($fl)); fclose($tmp);
// here goes your update
$content = preg_replace('/\$targetvariable=\"(.*?)\";/', '$targetvariable="hi Greg";', $content);
/*write operation ->*/ $tmp =fopen($fl, "w"); fwrite($tmp, $content); fclose($tmp);
?>
Related
I have the following pages (code fragments only)
Form.html
<form method="post" action="post.php">
<input type="text" name="text" placeholder="enter your custom text />
<input type="submit">
</form
post.php
....
some code here
....
header('Location: process.php');
process.php
on this page, the "text" input from form.html is needed.
My problem is now, how do i pass the input-post from the first page through process.php without loosing it?
i dont want to use a process.php?var=text_variable because my input can be a large html text, formated by the CKeditor plugin (a word-like text editor) and would result in something like this process.php?var=<html><table><td>customtext</td>......
How can i get this problem solved?
I would like to have a pure php solution and avoid js,jquery if that is possible.
If you don't want to use $_SESSION you can also make a form in the page and then send the data to the next page
<form method="POST" id="toprocess" action="process.php">
<input type="hidden" name="text" value="<?php echo $_POST["text"]; ?>" />
</form>
<script>
document.getElementById("toprocess").submit();
</script>
or you can the submit the form part to whatever results in moving to another page.
Having said that using the $_SESSION is the easiest way to do this.
Either use $_SESSION or include process.php with a predefined var calling the post.
$var = $_POST['postvar'];
include process.php;
Process.php has echo $var; or you can write a function into process.php to which you can pass var.
maybe the doc can help: http://php.net/manual/fr/httprequest.send.php
especially example #2:
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
$r->addPostFile('image', 'profile.jpg', 'image/jpeg');
try {
echo $r->send()->getBody();
} catch (HttpException $ex) {
echo $ex;
}
But I wouldn't use this heavy way where sessions are possible and much easier, see previous answer/comments.
This is ok for instance if you want to call a pre-existing script awaiting post-data, if you can't (or don't want to) modify the called script. Or if there's no possible session (cross-domain call for instance).
I'm redesigning a site that's mainly static content, so a CMS is really not necessary. The only thing that changes is the 'events' page, which my client frequently updates. He does this now by going into the HTML, copying the tags of a previous event, changing whatever needs to be changed and uploading it back to the server. I want to make this easier for him (it's a pain in the a**, as he puts it), but without using a CMS I'm kind of lost.
Is there a way to have a form he can fill in (with place, date, etc.) and then display it on the proper page on submit? I'm thinking it should be possible with PHP but I don't know how to do it.
DEMO
The cleanest way to do this if you have PHP available is to set up a form that uses PHP to write to a text file, and then subsequent form posts would overwrite the same file. This is a very basic form created with the idea that the user would be the administrator. if this form was user facing to the public you would want toimplement a little more security.
You can format the output in the php script to match the site as needed.
Use this to read in the txt file on the page php file to display the text file:
<?php
readfile("Post.txt");
?>
HTML Form
<h1>Event Post </h1>
<form name="blogs" action="eventpost.php" method="post" enctype="multipart/form-data">
<label for="titlePost">Post Title </label>
<input type="text" name="titlePost">
<label for="commentPost">Comment: </label>
<textarea type="text" name="commentPost" rows="5" cols="35"></textarea>
<input type="submit" name="submitPost" width="200px" value="Submit"/>
</form>
PHP Script
<?php
global $output;
$title = $_POST['titlePost'];
$comment = $_POST['commentPost'];
$tagDate = date('l, M d, Y');
$content = "<div><h2>$title</h2><span class=\"dateStamp\"> $tagDate</span><br><br><span>$comment</span>\n</div><hr>\n\r\r";
$file = "Post.txt";
if($_POST['titlePost'] = !"" && $_POST['commentPost'] != ""){
if (isset($_POST['submitPost'])){
if (file_put_contents($file, $content) > 0){
$output = "The post titled <b>$title</b> was accepted. Here is what was posted:<br><br>$comment<hr><br>";
} else{
$output = "<em>Unfortunately ".$title."</em> did not post appropriately.";
}
} else {
$output = "Your form is not filled out <u>completely.</u>";
}
echo "<span>".$output."</span>";
}
?>
Set it all up like this:
<?
$EventIs = "Event name"
$EventDate = "date"
//etc...
?>
in your HTML:
<p><span class="eventName">Event: <? echo $EventIs ?></span><br />
<span class="eventDate">Date: <? echo $EventDate ?></span></p>
That's really oversimplifying it. But it gives you the basic idea. You guy can just edit the variables at the top of the file, and they will appear wherever you want in the code.
If you want these variables set from a post from a form, you will have to save those variables in your database. But that's the basic idea.
From a high level perspective, you could create a form for him to fill out which would, on the back end, store the form contents into a file or database. Then, on the front end, you would read in that file, or database, parse the content, and display it however you like. That's a very common thing to do using PHP.
I'm trying to add elements to an array after typing their name, but for some reason when I do
<?php
session_start();
$u = array("billy\n", "tyson\n", "sanders\n");
serialize($u);
file_put_contents('pass.txt', $u);
if (isset($_POST['set'])) {
unserialize($u);
array_push($u, $_POST['check']);
file_put_contents('pass.txt', $u);
}
?>
<form action="index.php" method="post">
<input type="text" name="check"/><br>
<input type="submit" name="set" value="Add person"/><br>
<?php echo print_r($u); ?>
</form>
It puts it in the array, but when I do it again, it rewrites the previous written element. Does someone know how to fix this?
You always start with the same array, which means no matter what you do you're going to only be able to add one person. I /think/ you're trying to add each person to the file, which can be accomplished by modifying the code to resemble something like this:
session_start();
$contents = file_get_contents('pass.txt');
if (isset($_POST['set'])) {
$u = unserialize($contents);
array_push($u, $_POST['check'] . "\n");
$u = serialize($u);
file_put_contents('pass.txt', $u);
}
Notice also that you can't use [un]serialize() on its own, it must be used in the setting of a variable.
**Note: Personally, I'd just go the easy route and do $u[] = $_POST['check'], as using array_push() to push one element seems a bit... overkill.
I'm having a problem when using file_get_contents combined with $_GET. For example, I'm trying to load the following page using file_get_contents:
https://bing.com/?q=how+to+tie+a+tie
If I were to load it like this, the page loads fine:
http://localhost/load1.php
<?
echo file_get_contents("https://bing.com/?q=how+to+tie+a+tie");
?>
However, when I load it like this, I'm having problems:
http://localhost/load2.php?url=https://bing.com/?q=how+to+tie+a+tie
<?
$enteredurl = $_GET["url"];
$page = file_get_contents($enteredurl);
echo $page;
?>
When I load using the second method, I get a blank page. Checking the page source returns nothing. When I echo $enteredurl I get "https://bing.com/?q=how to tie a tie". It seems that the "+" signs are gone.
Furthermore, loading http://localhost/load2.php?url=https://bing.com/?q=how works fine. The webpage shows up.
Anyone know what could be causing the problem?
Thanks!
UPDATE
Trying to use urlencode() to achieve this. I have a standard form with input and submit fields:
<form name="search" action="load2.php" method="post">
<input type="text" name="search" />
<input type="submit" value="Go!" />
</form>
Then to update load2.php URL:
<?
$enteredurl = $_GET["url"];
$search = urlencode($_POST["search"]);
if(!empty($search)) {
echo '<script type="text/javascript">window.location="load2.php?url=https://bing.com/?q='.$search.'";</script>';
}
?>
Somewhere here the code is broken. $enteredurl still returns the same value as before. (https://bing.com/?q=how to tie a tie)
You have to encode your parameters properly http://localhost/load2.php?url=https://bing.com/?q=how+to+tie+a+tie should be http://localhost/load2.php?urlhttps%3A%2F%2Fbing.com%2F%3Fq%3Dhow%2Bto%2Btie%2Ba%2Btie. you can use encodeURIComponent in JavaScript to do this or urlencode in php.
<?
$enteredurl = $_GET["url"];
$search = urlencode($_POST["search"]);
if(!empty($search)) {
$url = urlencode('https://bing.com/?q='.$search)
echo '<script type="text/javascript">window.location="load2.php?url='.$url.'";</script>';
}
?>
When I post my form data:
<form action="layouts.php" method="post">
<input type="text" name="bgcolor">
<input type="submit" value="Submit" align="middle">
</form>
to a php page, "layouts.php", it returns the string, as expected.:
$bgcolor = $_POST['bgcolor'];
echo $bgcolor; //returns "red"
echo gettype($bgcolor); // returns "string"
But when I include "layouts.php" in another page it returns NULL.
<?php
include("php/layouts.php");
echo $bgcolor; //
echo gettype($bgcolor); //returns "NULL"
?>
How do I pass the variable to another page?
You'll have to use a session to have variables float around in between files like that.
It's quite simple to setup. In the beginning of each PHP file, you add this code to begin a session:
session_start();
You can store variables inside of a session like this:
$_SESSION['foo'] = 'bar';
And you can reference them across pages (make sure you run session_start() on all of the pages which will use sessions).
layouts.php
<?php
session_start();
$bgcolor = $_POST['bgcolor'];
$_SESSION['bgcolor'] = $bgcolor;
?>
new.php
<?php
session_start();
echo $_SESSION['bgcolor'];
?>
Give the form two action="" and see what happens. I just tried that on a script of mine and it worked fine.
A more proper way to solve this might exist, but that is an option.