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.
Related
I'm really new new to php. I consider myself alright at Java, but wanted to get more into web stuff. I like HTML and CSS well enough, but I'm having a lot of trouble with php.
I'm writing a really basic php code. I want it to get info from a user (via form) and add it to an array in php (POST). I then would like to store the array as a session variable and write a for loop that prints out each index in an HTML list.
ISSUES:
1. I don't have a good handle on SESSION, so not sure how to store the array as a session variable.
2. I'm not sure how to reference a specific index of an array in php. I've sorta done it in a java way here, but that needs to change.
--CODE--
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
$stack = array("");
array_push($stack, $_POST[name]);
for(i < $stack.length){
print_r($stack[i]);
}
?>
To access session variables is easy:
First, you need to call the method session_start() (Make sure, you call it, before sending any HTTP header).
After calling the session_start() method, you will have access to the $_SESSION associative array. You will be able to append anything to this array.
The syntax of the for loop in PHP is as follows:
foreach (array_expression as $value)
statement
or
foreach (array_expression as $key => $value)
statement
I hope that it helps.
First let's see the lines of code in PHP you have written:
I.
$stack = array("");
This creates an array called $stack with a single element of "". $stack[0] will have the value of "". You can name the elements of an associated array, like this:
$stack = array("name" => "value");
In this case $stack["name"] will be "value".
II.
array_push($stack, $_POST[name]);
This is incorrect, since name is not a variable, nor a string. You probably meant:
array_push($stack, $_POST["name"]);
this would have written $_POST["name"] at the end of your array having "", so $stack[1] would have been whatever the value of $_POST["name"]; was.
III.
for(i < $stack.length){
This is incorrect syntax. You have meant
for($i = 0; $i < count($stack); $i++){
Note how $ is put in front of all variables and how similar this for cycle is to a Java for.
IV.
print_r($stack[i]);
Incorrect, you need the the cash ($), otherwise your variables will not cooperate.
print_r($stack[$i]);
You, however, do not check whether this is a POST request or a GET. When the user loads the page, it will be a GET request and when he submits the form, it will be a POST request. The first (GET) request will not have $_POST members ($_POST will be empty), as the form was not submitted yet. And if you check whether it is a POST request, you need to check whether "name" is present in $_POST:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //it is a post
if (isset($_POST["name"])) { //name is found inside $_POST
echo "Name is " . $_POST["name"];
}
}
?>
Question1:
$_SESSION is an array, like $stack. You can do something like this:
$_SESSION["name"] = $_POST["name"];
This will create a new element of $_SESSION with the index of "name", however, before such an assignment, you need to make sure the session was started.
Question2:
You reference it by the name of the index, just like in Java, however, in PHP you can have textual indexes as well if you want, while in Java you can only use integers.
Just to quickly update the code you have, to make it somewhat workable:
Html code
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
Php code
<?php
$stack = array("");
if(isset($_POST['name'])){
array_push($stack, $_POST['name']);
for($i=0; $i < count($stack); $i++){
echo($stack[$i]);
}
}
?>
Assuming this is all in welcome.php.
I'm making a simple hangman application and I have my php file and a separate .txt file holding the words, one on each line.
What I want is for the $word variable to remain constant even after the page refreshes since I was planning on using a GET or POST to get the user's input.
In the example code below I want $word to stay the same after the form is submitted.
I believe it's a simple matter of moving code to another place but I can't figure out where any help for this PHP noob would be appreciated!
wordsEn1.txt:
cat
dog
functions.php:
<?php
function choose_word($words) {
return trim($words[array_rand($words)]);
}
?>
hangman.php:
<?php
include('functions.php');
$handle = fopen('wordsEn1.txt', 'r');
$words = array();
while(!feof($handle)) {
$words[] = trim(fgets($handle));
}
$word = choose_word($words);
echo($word);
echo('<form><input type="text" name="guess"></form>');
?>
use sessions:
session_start(); // in top of PHP file
...
$_SESSION["word"] = choose_word($words);
$_SESSION["word"] will be there on refresh
if you care about the "lifetime", follow also this (put it just before session_start)
session_set_cookie_params(3600,"/");
It will hold an hour for the entire domain ("/")
You could use a hidden input:
<form method="POST">
<input type="text" />
<input type="hidden" name="word" value="<?php echo $word; ?>" />
</form>
...and on the next page:
if(isset($_POST['word'])) {
echo $_POST['word'];
}
Or you could use a PHP $_COOKIE, which can be called forever (but kind of a waste if you just want it on the next page):
setcookie('word', $word, time()+3600, '/');
...and on the next page:
echo $_COOKIE['word'];
Just use hidden type forms for that issue.if we put it into session while page refreshes its hide also. if you can store that value in hidden form field it was stored and retrived any time .
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);
?>
I want a function that prints those 2 "print" in the database ( insert intro ) when a button is pressed.
Here's the code:
<?php
$id2name=array();
$x=mysql_query("SELECT id,name FROM products WHERE id IN(".implode(',',array_keys($_SESSION['cart'])).")");
while($y=mysql_fetch_assoc($x)){
$id2name[$y['id']]=$y['name'];
}
foreach($_SESSION['cart'] as $k=>$v){
print "<br>[".$id2name[$k]."]\t".$v."\n <br>";
}
print "<br>$total<br>";
?>
How can I make that a function, to print it in the database when a button is pressed?
Not sure if I got you right, but as far as I understand, you want to write something to the database by pressing a button, right?
Well, to trigger an action by pressing a button, you need a form:
<form action="page_to_process_the_db_request.php" method="post">
<input type="hidden" value="<?php echo $total;?>" name="total" />
<input type="submit" value="Wirite to DB!" />
</form>
In this example, I assume you want to write the variable $total to DB.
So you post the data to the processing page (which also can be the same one you're on) and there, you look if there's something in the $_POST-array:
<?php
if(isset($_POST['total'])) {
mysql_query("UPDATE products SET total = ". $total); //or something like that
}
?>
Not sure though if this is what you're looking for...
//edit
referring to your comment, I guess you want to write the output of the loop to DB...
At first, you have to create an appropriate structure, like an array:
foreach($_SESSION['cart'] as $k=>$v){
$id2name[$k]['name'] = $v;
}
now you can turn the array into a simple string with
$serialized_array = serialize($id2name);
And now you can write this string to db. And when you read it from db, you can turn it back into an array again with:
$id2name_array = unserialize($serialized_array);
Sorry if this has been answered somewhere; I'm not quite sure how to phrase the problem to even look for help.
Anyway, I have a form with three text input boxes, where the user will input three song titles. I have simple PHP set up to treat those input boxes as an array (because I may want, say, 100 song titles in the future) and write the song titles to another document.
<form method="post">
<input type="text" name="songs[]" value="" />
<input type="text" name="songs[]" value="" />
<input type="text" name="songs[]" value="" />
<button type="submit" name="submit" value="submit">Submit</button>
</form>
<?php
if (isset($_POST['submit'])) {
$open = fopen("test.html", "w");
if(empty($_POST['songs'])) { }
else {
$songs = $_POST['songs'];
foreach($songs as $song) {
fwrite($open, $song."<br />");
};
};
};
?>
This correctly writes the song titles to an external file. However, even when the input boxes are empty, the external file will still be written to (just with the <br />'s). I'd assumed that the if statement would ensure nothing would happen if the boxes were blank, but that's obviously not the case.
I guess the array's not really empty like I thought it was, but I'm not really sure what implications that comes with. Any idea what I'm doing wrong?
(And again, I am clueless when it comes to PHP, so forgive me if this has been answered a million times before, if I described it horribly, etc.)
you should check each entry:
<?php
if (isset($_POST['submit'])) {
$open = fopen("test.html", "w");
foreach($_POST['songs'] as $song) {
if(!empty($song)) {
fwrite($open, $song."<br />");
};
};
};
?>
Indeed $_POST['songs'] is not an empty array, it's an array of 3 empty strings.
You can use the following to clear out all the empty values:
$song_titles = array_filter($_POST['songs'], function($title) {return (bool) trim($title);});
You could also put some other checks into that callback function (whitelist only alphanumerics and some other characters (spaces, dashes etc)).
If you have a version of PHP older than 5.3 you'll have to define the callback function separately, see http://us2.php.net/manual/en/function.array-filter.php