In the function show_commentbox() below, I would like to pass along the variables $_SESSION['loginid'], $submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl. With the setup below, it's not working. How could I change it to make show_commentbox() pass the variables along?
Thanks in advance,
John
index.php:
<?php
$submission = $_GET['submission'];
require_once "header.php";
include "login.php";
include "comments.php";
include "commentformonoff.php";
?>
In header.php:
require_once ("function.inc.php");
In comments.php:
$uid = $_SESSION['loginid'];
$submissiondate = mysql_real_escape_string($_GET['submissiondate']);
$submittor = mysql_real_escape_string($_GET['submittor']);
$countcomments = mysql_real_escape_string($_GET['countcomments']);
$dispurl = mysql_real_escape_string($_GET['dispurl']);
$url = mysql_real_escape_string($_GET['url']);
$submission = mysql_real_escape_string($_GET['submission']);
$submissionid = mysql_real_escape_string($_GET['submissionid']);
commentformonoff.php:
<?php
if (!isLoggedIn())
{
if (isset($_POST['cmdlogin']))
{
if (checkLogin($_POST['username'], $_POST['password']))
{
show_commentbox();
} else
{
echo "Login to comment";
}
} else
{
echo "Login to comment";
}
} else
{
show_commentbox();
}
?>
In display.functions.inc.php:
function show_commentbox()
{
echo '<form action="http://www...com/sandbox/comments/comments2.php" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<input type="hidden" value="'.$submission.'" name="submission">
<input type="hidden" value="'.$url.'" name="url">
<input type="hidden" value="'.$submittor.'" name="submittor">
<input type="hidden" value="'.$submissiondate.'" name="submissiondate">
<input type="hidden" value="'.$countcomments.'" name="countcomments">
<input type="hidden" value="'.$dispurl.'" name="dispurl">
<label class="addacomment" for="title">Add a comment:</label>
<textarea class="commentsubfield" name="comment" type="comment" id="comment" maxlength="1000"></textarea>
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
}
Simply pass them as arguments:
function show_commentbox($submissionid, $submission, ...) {
...
show_commentbox($submissionid, ...);
Note that I removed $_SESSION['loginid'], since it doesn't need to be passed through the form to be available. Also, it's probably sensitive information an thus shouldn't be leaked.
mysql_real_escape_string should only be used to prepare data that's going to be sent to a database. Instead, use htmlspecialchars or htmlentities to prepare the data for output. This should be done in show_commentbox, not before, since it's where the destination of the values is determined.
Of course, that many parameters are unwieldy. For one thing, how do you remember their order? One solution for that particular problem is to keyword arguments, which (in PHP) you have to implement by passing an associative array:
function show_commentbox($args) {
...
show_commentbox(array('submissionID' => $submissionid, ...));
The better solution in this case is to use classes. It can be as simple as:
class CommentBox {
public $submissionid, ...;
function show() {
?><form ...><?php
foreach ($this as $name => $val) {
$val = htmlspecialchars($val);
?><input name="<?php echo $name; ?>" value="<?php echo $value; ?>" type="hidden"/><?php
}
?></form><?php
}
}
...
$cb = new CommentBox();
foreach ($cb as $name => $ign) {
// note: we don't want to loop over $_GET, as that introduces
// potential injection attacks
if (isset($_GET[$name])) {
$cb->$name = $_GET[$name];
}
}
Or you can start using an MVC architecture, separating show into a FormView class.
I'm intentionally leaving out using globals, since globals are bad.
Related
I created a simple form, to create a post, that has three inputs:
One for the title
Description
Image
So, when I submit my form (using post) I call a php file, that "echoes" the value from each input.
It works just fine, but when I try to call the php function $_FILES['my_input_name']['tmp_name'], on my file input, I get an error saying:
Undefined index: my_input_name
My form looks like this (shorter version):
<form action="processForm.php" method="post">
<input type="text" name="title" class="input" required>
<textarea id="description" name="description"required></textarea>
<input type="file" name="fileMedia">
</form>
My php file looks like this
$method = $_SERVER[ 'REQUEST_METHOD' ];
if ( $method=='POST') {
$_args = $_POST;
$_INPUT_METHOD = INPUT_POST;
}
elseif ( $method=='GET' ) {
$_args = $_GET;
$_INPUT_METHOD = INPUT_GET;
}
else {
exit(-1);
}
$title = $_args['title'];
$description = $_args['description'];
$mediaName = $_args['fileMedia'];
$mediatmpPath = $_FILES["fileMedia"]["tmp_name"];
echo $title."<br>";
echo $description."<br>";
echo $mediaName."<br>";
echo $mediatmpPath ."<br>";
I have no idea of what I'm doing wrong, so any helped would be really apreciated!
P.s: My form's is really reduced. In the original one I have row, cols, divs, etc, and some other inputs, which I did not find relevant for this question
You just need to add multipart = "form/data" in form tag
You need to add this below line in <form> tag
<form action="processForm.php" method="post" enctype='multipart/form-data'>
<input type="text" name="title" class="input" required>
<textarea id="description" name="description"required></textarea>
<input type="file" name="fileMedia">
<input type="submit" name="save" value="save">
</form>
And below post data code:
<?php $method = $_SERVER[ 'REQUEST_METHOD' ];
if ( $method=='POST') {
$_args = $_POST;
$_INPUT_METHOD = INPUT_POST;
}
elseif ( $method=='GET' ) {
$_args = $_GET;
$_INPUT_METHOD = INPUT_GET;
}
else {
exit(-1);
}
$title = $_args['title'];
$description = $_args['description'];
$mediaName = $_FILES["fileMedia"]["name"];
$mediatmpPath = $_FILES["fileMedia"]["tmp_name"];
echo $title."<br>";
echo $description."<br>";
echo $mediaName."<br>";
echo $mediatmpPath ."<br>";
?>
I think this help you.
I'm trying to write to file like this:
<?php
date_default_timezone_set('Europe/Budapest');
if(isset($_POST['user'])) {
global $user;
$user = $_POST['user'];
} else {
die("Nincs user beállítva!");
}
if(isset($_POST['pass'])) {
global $pass;
$pass = $_POST['pass'];
} else {
die("Nincs pass beállítva!");
}
if(!isset($_POST['msg'])) {
die("Nincs üzenet!");
} else {
global $msg;
$msg = $_POST['msg'];
}
if(!file_exists("logfile.txt")) {
die("Nem létezik a logfile.txt!");
}
$cont = file_get_contents("logfile.txt");
file_put_contents("logfile.txt","{$user}: {$msg}\n{$cont}"); //<-- Tried this one so many ways
?>
And it gives me this in the txt file:
<? global $user; echo $user; ?>: test
No matter what i change in the file_put_contents, it always give something similar to this.
Thanks for the help in advance.
EDIT: I made the edit that #Barmar suggested, but it is still doing the same thing:
<form name="send" action="chat_send.php" method="post">
<input type="text" name="msg" autocomplete="off" value="">
<?php
global $user;
echo '<input type="hidden" name="user" value="' . $user . '">';
...
</form>
There's nothing wrong with how you're writing to the file. The problem is most likely with how you're setting $_POST['user']. It looks to me like the script that created the form did something like:
echo '<input type="hidden" name="user" value="<?php global $user; echo $user; ?>">';
You can't use <?php ... ?> in the middle of a string to execute PHP code;
That's used when you're outputing normal HTML after ?>, to get back into PHP execution mode temporarily. So your form just contains the literal string ?php global $user; echo $user; ?> in the hidden input value.
In a string, you use concatenation, so it should be:
global $user;
echo '<input type="hidden" name="user" value="' . $user . '">';
Or you can return to HTML mode first:
?>
<form name="send" action="chat_send.php" method="post">
<input type="text" name="msg" autocomplete="off" value="">
<input type="hidden" name="user" value="<?php global $user; echo $user; ?>">
...
</form>
<?php
I am working on a web back-end that will pull information into a form, and then when updated, will update the database with the new information. However, when I try to pull information previously stored in a class private variable, it throws me an error stating that the information is NULL. What am I doing wrong here?
<?php
class modify_racer
{
private $mysqli, $racer_id, $firstname,
$lastname, $banner, $bio;
public function error($code)
{
switch($code)
{
case 1:
echo '<p id="error"><b>Error:</b> Please fill out all fields!</p>';
modify_racer::send_form($this->firstname, $this->lastname, $this->banner, $this->bio);
break;
case 2:
echo '<p id="error"><b>Error:</b> Racer already exists!</p>';
break;
case 3:
echo '<p id="error"><b>Error:</b> Could not connect to MySQLi: ' . mysqli_error();
break;
}
}
public function send_form($modify = 1)
{
?>
<div id="form">
<h3>Edit Racer:</h3>
<form method="post" action="">
<label for="firstname">First Name: </label>
<input type="text" id="firstname" name="firstname"
placeholder="Racer's First Name"
value="<?php echo $this->firstname;?>" />
<br />
<label for="lastname">Last Name: </label>
<input type="text" id="lastname" name="lastname"
placeholder="Racer's Last Name"
value="<?php echo $this->lastname;?>" />
<br />
<label for="banner">Banner Location: </label>
<input type="text" id="banner" name="banner"
placeholder="Racer's Banner Image Location:"
value="<?php echo $this->banner;?>" />
<br />
<label for="bio">Racer's Bio Info: </label>
<textarea rows="5" cols="50" id="bio" name="bio"
placeholder="Racer Statistics / Biography"
value=""><?php echo $this->bio;?></textarea>
<input type="submit" id="submit" name="modify" value="submit" />
</form>
</div>
<?php
}
public function get_racer($racerID)
{
$this->racer_id = $racerID;
$this->mysqli = new mysqli(MYSQLI_HOST,MYSQLI_USER,MYSQLI_PASS,MYSQLI_DATABASE)
or die(error(3));
$racer_info = "SELECT * FROM ArtecRacers WHERE RacerID=?";
$load_racer = $this->mysqli->prepare($racer_info);
$load_racer->bind_param('s', $racerID);
$load_racer->execute();
$load_racer->bind_result($this->racerID, $this->firstname, $this->lastname, $this->banner, $this->bio);
$load_racer->fetch();
modify_racer::send_form();
}
public function list_racers()
{
?>
<div id="form">
<h3>Select Racer:</h3>
<form method="post" action="">
<?php
$this->mysqli = new mysqli(MYSQLI_HOST,MYSQLI_USER,MYSQLI_PASS,MYSQLI_DATABASE)
or die(error(3));
$racer_list = "SELECT * FROM ArtecRacers";
$get_racers = $this->mysqli->query($racer_list);
while($list = $get_racers->fetch_array(MYSQLI_NUM))
{
echo '<input id="part" type="radio" name="editRacer" value="' . $list[0] . '"/>';
echo '<label for="part">' . $list[1] . ' ' . $list[2] . '</label><br />';
}
?>
<input type="submit" name="selectRacer" id="submit" value="Select Racer" />
</form>
</div>
<?php
}
function test2()
{
echo $this->firstname;
echo $this->lastname;
echo $this->racer_id;
}
}
$start = new modify_racer();
if(!isset($_POST['selectRacer']))
$start->list_racers();
if(isset($_POST['selectRacer']))
$start->get_racer($_POST['editRacer']);
$start->test2();
?>
Everything in the code works except at $start->test2(); all of the information pulled from the function test2() is blank, and I am not sure why... Any insights?
EDIT:
I changed the code to reflect the following on the bottom, and test2() still outputs the variables as NULL:
if(!isset($_POST['editRacer']))
$start->list_racers();
else
$start->get_racers($_POST['editRacer']);
$start->test2();
If you leave your code alone, you're going to have to pass both selectRacer and editRacer parameters into the page. My guess is that you might only want to pass the one, though. In which case, you'll want to change
if(isset($_POST['selectRacer']))
$start->get_racer($_POST['editRacer']);
into
if(isset($_POST['editRacer']))
$start->get_racer($_POST['editRacer']);
Also, if you want to pass these values in through the URL bar, you need to check $_GET, not $_POST.
And finally, everywhere that you are making method calls by executing modify_racer::my_method_here(), you should change that to $this->my_method_here(). The former is a static method call, meaning it's not actually associated with your object, meaning it can't touch those variables. For it to be able to access and change the variables, you'll need to call it through $this.
I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.
I never really used session so it could be some stupid mistake. When I use if(isset($_SESSION) it outputs false, I think it has something to do with the foreach. I get no errors whatsoever. Could anyody spare some time to help me?
<?php
session_start();
if(isset($_POST['register']))
{
require_once('../resources/library/register.class.php');
//require_once('../resources/library/sessions.class.php');
$obj_reg = new register();
$name = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$checking = $obj_reg->checking($name, $pass);
//An foreach for converting POST data inside SESSION variables
//isset checks if the array value contain post variables
$posts = array($name, $pass, $email);
foreach ($posts as $p)
{
if(isset($_POST['p'])){
$_SESSION['p'] = $_POST['p'];
}
}
}
?>
<form method="post" action="index.php?page=register.php">
<table>
<tr><td>username:</td><td> <input type="text" name="user"></td></tr>
<tr><td>password:</td><td> <input type="password" name="pass"/></td></tr>
<tr><td>email:</td><td> <input type="text" name="email"/></td></tr>
<?=( !empty( $checking ) ) ? $checking : '' ?>
</table>
<input type="hidden" name="token" value="<?=$token;?>"/>
<input type="submit" name="register" value="register"/>
</form>
<?php
session_start();
if(isset($_SESSION['p']))
{
echo "mama";
}
else
{
echo "why?";
}
?>
You need to call session_start on every page that needs $_SESSION.
I think you also mean to use $_SESSION[$p] = $_POST[$p] instead of the string 'p'.