PHP multiple outputs - php

I've been trying to create a simple little blog for something I want to add in my school assignment. All I want it to do is to output my input in the order it is entered (like a wall on facebook).
My code is:
<?php
//other form that does the password
$pass = $_POST['pass'];
$blog =$_POST['blog'];
?>
<form method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<textarea placeholder="Write Something, Me."
autofocus
required
autocomplete="off"
name="blog"></textarea>
<br />
<input type="password"
placeholder="Password"
autocomplete="off"
name="pass"
method="post" />
<input type="submit"
name="submit"
value="Submit">
</form>
<?php
If ($pass=="pass") {
echo 'Access Confirmed<br>';
echo $blog;
echo '<br/><br/>';
echo $blog;
echo '<br/><br/>';
echo $blog;
} else {
echo 'Wrong password or invalid blog entry. Try again Noob.<br>';
}
?>
I need to be able to call $blog as an array and output multiples datas as they are being entered (like in facebook). But as you can tell it's just printing the same thing over and over again. Also I don't want it do delete all the inputs if the "Password" (can't really call it secure) is entered incorrectly. I still want to be able to see the previous inputs.
I've tried many things, but none seem to work for me.
If this is unclear and you still have questions, please ask. Thanks.

I think you're a long ways from where you want to be with this. I'll get you started by saying that if you have an array, you can't simply use echo to print it, you need to enumerate through the array and print out the pieces that you're interested in.
foreach ($blog as $value) {
echo $value;
}
Start here and work your way up: http://www.php.net/manual/en/control-structures.foreach.php

Related

confused about basic find and replace app

I am trying to do a find and replace applicaiton the problem is that after cliked submit button all the text fields gets clean nothing displays on the screen What am i doing wrong
<?php
$offset=0;
if(isset($_POST['text'] ) && isset($_POST['searchfor']) && isset($_POST['replacewith'])){
$text=$_POST['text'];
$search=$_POST['searchfor'];
$replace=$_POST['replacewith'];
$searchLength=strlen($search);
if(!empty($text) && !empty($search) &&!empty($replace)){
while ($strpos= strpos($text,$search,$offset)){
echo $offset=$strpos+$searchLength;
}
} else {
echo "<script>alert('errorrrr')</script>";
}
}
?>
<form action="#" method="post">
<textarea name="text" id="" cols="30" rows="10"></textarea><br>
Search For:<br>
<input type="text" name="searchfor"><br>
ReplaceWith<br>
<input type="text"name="replacewith"><br>
<input type="submit" value="Fr..."></>
</form>
Regarding your form, you decided to submit to the same page.
Doing this, the page is obviously fully reloaded when submitted. Hence it is normal that what you typed in has disappeared.
If you want to see it again, you have to display you variables in the HTML code.
For example:
<?php
$myVar = "";
if(isset($_POST['myVar']){
$myVar = $_POST['myVar'];
}
?>
<form>
<input type="text" value="<?php echo $myVar;?>"/>
</form>
NB: I encourage you to filter the user entry.
Regards
there is problems in your code :
1 - echo $offset=$strpos+$searchLength; the echo can't be used in this format. insted use echo $offset; in next line for seeing offset values.
2 - if the text be like 'amir love persepolis' and search for 'amir' to replace it with 'all men's' you will have another issue, because you will have while ( 0 ) situation. think about this too!

How to pass a GET Variable to a form

I have three pages. One of which there is a list of texts the user can select. Upon clicking on one of the texts they will be redirected to another page by using:
<a href='second.php?text=whatever>Whatever</a>
A page where they will input the username they wish to send those texts to - using forms. I wish to proceed to the third page with those two variable - texts and username. I only manage to proceed to third page with username only.
I am getting third.php?username=inputtedUsername.
I want to get third.php?username=inputtedUsername&&text=whatever.
I am aware that I can do by storing the text to a SESSION on page two and than transfer it over to third page.
I wish to know if there is another secure way to do this - maybe something needed to be changed in the form action=thirdpage.php? I dont know. Thank you. ö.ö.
Solved: After reading comments and answer, the thing I need was type=hidden. It is now working on my part. Thanks everyone for helping me. :).
'second.php?text=whatever'? You can't just put whatever to the text, you are doing it wrong. Try this.
firstpage.php
<?php
$whatever = 'Tom & Jerry, 1 + 2 = 3';
echo '' . $whatever . '';
?>
secondpage.php
<form action="thirdpage.php" method="post">
<input type="text" name="username" value="" />
<input type="hidden" name="text" value="<?php echo base64_decode($_GET['text']); ?>" />
<input type="submit" value="Submit" />
</form>
thirdpage.php
<?php
echo 'Username: ' . $_POST['username'];
echo '<br />';
echo 'Text: ' . $_POST['text'];
?>

Using $_POST variable on different php pages

EDIT: Thanks for all the helpful answers, I got it solved.
I can't really seem to find an answer to this question, and it's probably really simple.
I was just creating a page for fun where you can guess a number from 1-10. Person 1 enters a secret number, that person 2 will guess. However, I have had a lot of problems storing the $_POST from the secret number.
TL;DR I can't store the information of secretNumber into guessnumber_guessed.php file. For example look in guessnumber_guessed. First part of the if statement, if the inputNumber equals the secretNumber, it should say correct. Problem is, the variblae is undefined, how to a 'transfer the info'?
Hope you guys get my point, help is really appreciated
Here's the code:
guessnumber_welcome:
<form method="post" action="guessnumber.php">
<input type="text" name="secretNumber" placeholder="Type the secret number">
<input type="submit" name="submit" value="Send">
</form>
guessnumber.php:
<form method="post" action="guessnumber_guessed.php">
<input type="text" name="inputNumber" placeholder="Guess the secret number">
<input type="submit" name="submit" value="Guess!">
</form>
<?php
$secretNumber = $_POST["secretNumber"]
?>
guessnumber_guessed.php:
<form method="post" action="">
<input type="text" name="inputNumber" placeholder="Guess the secret number">
<input type="submit" name="submit" value="Guess!">
</form>
<?php
$inputNumber = $_POST["inputNumber"];
if ($inputNumber == $secretNumber) {
echo "<p id=\"correctAnsw\"> CORRECT! </p>";
}
else if ($inputNumber == 2) {
echo "<p id=\"wrongAnsw\">You're very close. Go up a little!</p>";
}
else if ($inputNumber==4) {
echo "<p id=\"wrongAnsw\">You're very close. Go down a little!</p>";
}
else if ($inputNumber > 10) {
echo "<p id=\"wrongAnsw\">The number is you guessed is too high. Stay within the borders!</p>";
}
else if ($inputNumber < 1) {
echo "<p id=\"wrongAnsw\">The number is you guessed is too low. Stay within the borders!</p>";
}
else {
echo "<p id=\"wrongAnsw\">This is not the number. Try a new one!</p>";
}
?>
The sessions will not help. They're user oriented. If the first person is using the page to enter a number and the second person comes after that, in the same session, on the same browser, you can use the sessions mechanism.
If you're trying to make a multi-user "game" and the two persons are with separate browsers, it means you must:
Pair the two persons somewhat (maybe a room mechanism)
Use some kind of server storage or cache (you can even use memcached for in-memory storage) to match the two persons and their answers.
I faced a similar problem trying to pass beetween two scripts some url strings for a "two-step" uploader.
In my opinion there is two solutions, depends on the level of security you want to have:
In guessnumber.php put the $_POST['secretNumber'] value in an input type="hidden"
<input type="hidden" value="<?php echo $_POST['secretNumber']; ?>">
In this way the value will be passed to the second script via POST and will be available in the $_POST array.
This method, is not safe for sensible datas, because everybody who can access the html source simply through the browser devtool can read or modify it!!
The second, and more safe, solution is to use the php session
In guessnumber.php start the php session and save the value in this way:
if ( !session_id() ) {
session_start();
}
$_SESSION['secretNumber'] = $_POST['secretNumber'];
then in guessnumber_guessed.php recover the session and get the value from there
if ( !session_id() ) {
session_start();
}
$secretNumber = $_SESSION['secretNumber'];
I strongly recommend the second solution.
Hope it helps :)

Saving form values with php and calling cookie using SESSION

I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>

Is there something wrong with my form?

I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?
I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""
I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.
I tried using
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?
Form code:
echo ' <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
Name: <input name="name" type="text" /><br />
Email: <input name="email" type="text" /><br />
Phone Number: <input name="phone" type="text" /><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"></textarea><br /><br />
<input type="submit" name="submit" value="Submit Email"/>
</form></div>
<div style="clear:both;"></div><br /><br />';
and the vaildator:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!is_numeric($phone)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
} else {
mail( "email#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!
Second: you could(should?) use a hidden field instead of specifing it in the action?
But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?
You could use ajax to fix it(I believe plain old HTML has this side-effect?).
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.
In case you display the form again, you could set the values of the inputs like this:
$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:
<input type="hidden" name="date" value="'.$date.'"/>
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.
Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:
If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:
Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.
Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.
A very basic form handling script would look something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] = 'POST') {
# do this only if actually handling a POST
$field1 = $_POST['field1'];
$field2 = $_POSt['field2'];
...etc...
if ($field1 = '...') {
// validate $field1
}
if ($field2 = '...') {
// validate $field2
}
... etc...
if (everything_ok) {
// do whatever you want with the data. insert into database?
redirect('elsewhere.php?status=success')
} else {
// handle error condition(s)
}
} // if the script gets here, then the form has to be displayed
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>
?>
Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.
As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.
first, a few general changes:
change
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
to
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="data" value="'.$date.'" />
the answer to your original question:
set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);
For example: the name field
<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />

Categories