I'm new to PHP and developing a login form. Please find below the code I used. When I tried it gave me the following error:
Fatal error: Can't use function return value in write context in
C:\xampp\htdocs\forsiteSystem\login.php on line 3
Please help me to fix the issue.
Source code for thems/login.html:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action=".\login.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" id="Submit_button">
</form>
</body>
</html>
Source code for index.php:
<?php
// venushka thisara dharmasiri
require 'config.php';
require 'thems\login.html';
?>
Source code for login.php:
<?php
if(isset($_POST("Submit_button"))==true)
print("Submit button pressed");
else
print("submit button sorry");
?>
Source code for config.php:
<?php
$dbUser="root";
$dbPassword="";
$dbName="forsitelogin";
$dbHost="localHost";
$dbConnection= mysql_connect($dbHost, $dbUser, $dbPassword);
if($dbConnection)
{
mysql_select_db($dbName);
//print("Sucessfully connected to database");
}
else
die("<strong>Cound not connect to database </strong> ");
?>
Should be $_POST["Submit_button"] instead of $_POST("Submit_button")
The error the script returns explains it:
Fatal error: Can't use function return value in write context in
C:\xampp\htdocs\forsiteSystem\login.php on line 3
If you don’t understand the meaning of the error—and believe me, most error messages are bizarre even to experienced programmers—look at the line number referenced. And looking at line 3 in login.php shows me the error; $_POST("Submit_button") is invalid:
if(isset($_POST("Submit_button"))==true)
print("Submit button pressed");
else
print("submit button sorry");
It should be $_POST["Submit_button"]:
if(isset($_POST["Submit_button"])==true)
print("Submit button pressed");
else
print("submit button sorry");
But looking at it further, why is there an ==true? It can simply be like this:
if(isset($_POST["Submit_button"]))
print("Submit button pressed");
else
print("submit button sorry");
But I would recommend doing a better check on that value like this:
if(array_key_exists("Submit_button", $_POST) && !empty(trim($_POST["Submit_button"])))
print("Submit button pressed");
else
print("submit button sorry");
I find that using array_key_exists and a combination of !empty with trim works better for basic user submitted data verification.
First some code clean up might help. PHP does not require braces in if() else syntax; however, a great place to start. I would suggest diving into basic syntax of PHP here. Not that what is there would not work.
if(condition){
//do something
} else {
//do something else
}
The main issue you are experiencing is proper syntax for arrays in PHP. Thus this will solve your fatal error.
//old
$_POST("Submit_button")
//new
$_POST['foo']
This fixes your first fatal error; conversely, will not get you much further. Since your form is using 'GET' not 'POST' to send the variables to the script. The submit button does not return a variable; rather, use another <input> or add a name to the form <form name="form" action="file.php" method="post"> to retrieve a variable. Hence using:
if(isset($_POST['form'])){
echo $_POST['name'];
}
Furthermore, there are many concerns using $_GET variables and mysql_connect. I would suggest using Google to find some good tutorials on PHP mysqli or PDO before moving on.
Related
I'm learning MySQL and PHP and got a problem with the input of the form. So I wrote a small test code, but it still cannot work. My PHP version is 5.6.
The code:
<html>
<body>
<form action ="2.php" method ="post">
Name: <input type="text" name="username" />
<input type ="submit" value="ok" />
</form>
</body>
</html>
and
<html>
<?php
if(isset($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>
The output of the project is always error, can't output the input before.
I tried single quote and double quote for username, both can't work.
I also tried to set always_populate_raw_post_data in php.ini to 0, -1, 1, all can't work.
I don't know where the problem is, though it might be very silly.
As what it look it is correct and should run without any problem. Make sure the above code is what you actually have. From my experience most of the form submission can be
you don't have correct name (username)
you might send incorrect http verb (post)
you submit to wrong endpoint (2.php)
From you code above everything look fine. if you still don't have the right result, you better debug it with var_dump, or print_r function with these built-in
$_POST, $_GET, $_REQUEST and check whether they contains you form variable name username
You are using isset as a variable, but it is a function that returns a boolean.
Change $user=isset($_POST['username']); to $user=$_POST['username'];
Another thing is that in both case you will end up in the IF condition even if there is no value added to the field so you can do something like this too:
<html>
<?php
if(isset($_POST['username']) && !empty($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>
It's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages that come from a file separate to the html/php form.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
All the research I've done hasn't gotten me far. I understand that sending the headers isn't good practice. I looked at ob_open (php function-I think it was called) and couldn't figure out how to properly use it. I couldn't find a question on here that satisfied the conditions I'm trying to meet either.
Any help is certainly appreciated.Thank You
EDIT: This is not a duplicate of 'Passing error messages in PHP'.
-------While the idea is similar, they are 'Passing error messages in PHP' before the headers are sent. Therefore it's not the same.
Store the error in a session and echo it on the destination page.
Put session_start() at the top of the code of the form.php page. Like this:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
Then replace the echo error with:
$_SESSION['error'] = 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
Use this in your conditions instead of the echo. Then in the form.php page:
if (isset($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
The unset makes sure that the error is repeated.
An HTTP Redirect causes a new HTTP request. Since php is stateless, it cannot natively support remembering a message to display to a specific user in another request. In order to get around this limitation, you would need to use a stateful storage mechanism (session or cookies), or pass the error message along to the next request via query string parameter. The usual way this is handled is by using session storage to save flash messages.
Here is a library that can make it a bit easier for you https://github.com/plasticbrain/PhpFlashMessages
Set session of error and display on the page on which you are redirecting
Okay so I have an html form in Add.html. When I click submit, I would like the data to be added to my database via php and then return to the same form with "instance added" or "failed blah blah."
The only way I know how is to set the form action to a separate php file and call that - but then the php file renders and I do not return to the same form.
I would like to not have to add a "return to form" button and would prefer to return to the form on submit with a status message.
Any better ways to do this?
A very simple way to do is to do following :
yourpage.php
<?php
if(isset($_POST)){
//data posted , save it to the database
//display message etc
}
?>
<form method="post" action="yourpage.php" >....
You can do a redirect in php, to the html form - and you can set a "flash message" - to show "instance added" by saving "instance added" to the session and showing that value when you redirect to html.
you can use this trick
<?php if (!isset $_POST['Nameofyourinput']){
?>
<form method="post" action="add.html">
// your inputs here along with the rest of html
</form>
<?php
}
else
{
// Update you database and do your things here
//in your request variable you can add the error you want if things didn't go well, for example
$result = mysqli_query($connection, $sql) or die('Instance not added !'.$req.'<br>'.mysql_error());
// and then
echo (" instance added")
};
The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".
Just give nothing to the action attribute. It will refer to your current page.
<form method="post" action="">
Other way to do this are:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Or just add '#'
<from method="post" action="#">
To handle php code. Write your code inside it.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// write your code here.
}
You should change your file extension from .html to .php .
Well you can employ old school AJAX. For instance,let's say we have a form that takes in a number N,and once we click the calculate button we should see the result the of 2^N displayed on the same page without the page being refreshed and the previous contents remaining in the same place. Here's the code
<html>
<head>
<title> Simple Math Example</title>
<script type="text/javascript">
var request = new XMLHttpRequest();
function createAjaxObject(){
request.onreadystatechange = applyChange;
request.open("POST","calculate.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("N="+document.getElementById('N').value);
}
function applyChange(){
if(request.status == 200 && request.readyState == 4){
document.getElementById('resultSpace').innerHTML = request.responseText;
}
}
</script>
</head>
<body>
<fieldset>
<legend>Enter N to get the value of 2<sup>N</sup> ::: </legend>
<input type="text" name = "N" id = "N">
<br>
<input type="button" value = "Calculate" onclick="createAjaxObject()">
</fieldset>
<div id="resultSpace">
</div>
</body>
The file calculate.php is the same file with the above code. When the calculate button is clicked, it calls a function createAjaxObject which takes in a value N and sends the value to the same file via the POST method. Once the calculation is done, a response will be sent. And if the response is successful, it will be sent to a function called applyChange which will render it to the same page via JavaScript.
I would like create a script that is somewhat like a login. Before going to a certain page, they must answer a question correctly. If they get it right, then they proceed to the page. For example "What's your mom's name?" If the mom's name is Laurie, then they must enter this into a textbox and get it right to proceed.
Update
I used the script that oliver moran gave me to accomplish this. I added more questions so there is currently one question per page. After the final question has been answered, I have the page targeted to a place where they login, because I couldn't figure out how to do this simply based on the answer of the question. And I am fine with having the user login as a separate function. I have gotten the form to get them to login, and not let users that aren't logged in get to these pages. And the script works as long as they have kept the browser window open.
I have used the link that Oliver Moran gave on using sessions, and you can see in my code that I use sessions. But this does not solve the problem of keeping them logged in.
I would now like to know how to set a cookie once the user has logged in so they can leave the browser window and come back and still be logged in. I have searched this site for an answer, and couldn't find one that made sense. Here is my login code
<?php
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
if ($username&&$password) {
$connect = mysql_connect("127.0.0.1","root","") or die('Couldn\'t Connect to Database');
mysql_select_db ("login") or die('Couldn\'t find database');
$query = mysql_query("SELECT * FROM members WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0) {
while($rows = mysql_fetch_assoc($query)){
$dbusername = $rows['username'];
$dbpassword = $rows['password'];
}
if ($username==$dbusername&&$password==$dbpassword) {
echo "Login Successful. <a href='home.php'>Click here for the members area</a>";
$_SESSION['username'] = $dbusername;
}
else{
echo "Incorrect Password";
}
}
else{
die("Incorrect Username and Password");
}
}
else{
die("Please enter something in the boxes");
}
?>
Typically, a server-side language is used for this kind of thing. This is because, if you do password checking in JavaScript, anybody can see the correct password (since all the code is available by looking at the page's source code).
In order to do it securely, you'll need to submit the answer to a server and use a server-side language to check the answer. The server-side script then decides what response to give back to the user.
PHP is a very popular language for server side scripting. Here's the basics:
First we need a log in page (login.html) that has a HTML form in it, like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Login</title>
</head>
<body>
<form action="script.php" method="post">
<label>Enter your mom's name: <input type="text" name="mom" /></label>
<input type="submit" value="Submit" />
</form>
</body>
</html>
The important part here is the form. When the form is submitted, the data is sent to a PHP script called script.php.
That script looks like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Check login</title>
</head>
<body>
<?php
$mom = $_REQUEST['mom'];
$correct_answer = "Barbie";
if (!isset($mom) || $mom != $correct_answer) {
// nothing was submited or the name was incorrect
echo '<p>That\'s the wrong answer. Try again.</p>';
} else {
echo '<p>Welcome! That\'s the right answer.</p>';
}
?>
</body>
</html>
This is a fairly simple script. It checks what was submitted for 'mom'. If nothing was submitted or it was the wrong answer then a 'try again' message is shown. Otherwise, a 'welcome' message is shown.
The PHP logic (and so the correct answer) will not be visible in a web browser. Only the 'try again' or 'welcome' message will be sent down from the server.
This is the basics of working with HTML forms on the server side. I suggest you read up on using PHP. It's an easy and fun language (if inelegant, in my opinion). You can learn the basics here:
http://www.w3schools.com/php/default.asp
To test your code, you will need a web server. You can download and install a fully-fledged web server with PHP and MySQL (a database) from here:
http://www.wampserver.com/en/
With that, you can develop at test server-side code on your own machine. To test the above example, copy the code above into two files, called login.html and script.php, and put them into the www directory of WAMP.
Good luck!
This is what I managed to come up with. At the top of the page, insert this code before the <!DOCTYPE html>
<?php
//Check for existance of cookie from right answer
if(isset($_COOKIE['parents'])){
header("Location:q1.html");//Move on to next question
}
//Checks answer
if(array_key_exists("dad", $_POST) && array_key_exists('mom', $_POST)){
$dad = $_POST["dad"];
$mom = $_POST["mom"];
$dcorrect = array("Dad", "dad");
$mcorrect = array("Mom", "mom");
if(in_array($dad, $dcorrect) && in_array($mom, $mcorrect)){
setcookie('parents', '1' ,time()+60*60*24);
header("Location: index.html");
}else{
$wrong="<div class='error'>Wrong answer</div>";
}
}
?>
With this HTML
<form action="index.html" method="post">
<label>Enter your father's name:</label>
<input required autocomplete="off" type="text" name="dad" placeholder="Bill">
<label>Enter your mother's name:</label>
<input required autocomplete="off" type="text" name="mom" placeholder="Billette">
<input type="submit" value="Press me when you think you are right" />
<?php echo $wrong; ?>
</form>
So I created this page where a user can send data to a msql database but when they leave a field blank and they click submit I want an error to show up saying "You left a field blank".
This is the code:
<?php
$hostname = "";
$db_user = "";
$db_password = "";
$database = "";
$db_table = "";
# STOP HERE
####################################################################
# THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db);
?>
<html>
<head>
<title>Add your url to out database</title>
</head>
<body>
<?php
if (isset($_REQUEST['Submit'])) {
# THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE
$sql = "INSERT INTO $db_table(title,description,url,keywords) values ('".mysql_real_escape_string(stripslashes($_REQUEST['title']))."','".mysql_real_escape_string(stripslashes($_REQUEST['description']))."','".mysql_real_escape_string(stripslashes($_REQUEST['url']))."','".mysql_real_escape_string(stripslashes($_REQUEST['keywords']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into our database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1><center><img src='addalink.png'><center></h1>
<hr>
<center>
<form method="post" action="">
Name of the song:<br>
<input type="text" name="title"><br>
Artist: <br>
<input type="text" name="description"><br>
Download link: <br>
<font color="#0000FF">http://</font><input type="text" name="url"><br>
<input type="submit" name="Submit" value="Submit">
</form></br>
<?php
}
?> <center>
</body>
</html>
First of all, use a CSS style to style your form's inputs. It's a lot easier to read, and it means if you need to change anything in the future it's quick.
What you're wanting to do is run a script on submit that checks whether or not the values in the required fields are what you expect.
The jQuery Validation Plugin - http://bassistance.de/jquery-plugins/jquery-plugin-validation/ takes care of what you want.
If you want to write your own, it's a process of attaching the validation function to the click event of the submit button (or the onSubmit event of the form) and checking the data that's in the form.
If the data is missing, you add a class to show this. If the data is valid, you remove the previous class.
Finally, you only return true (to submit the form) in the case everything validates.
Keep in mind this is only client side, you still need to validate your data server side for security.
So, the common response is "do this on the front-end". If anything you are posting has security implications then I'd also recommend you check your form data on the back-end.
Also if you're going to go through the process of using mysql_real_escape, you might as well use mysqli and parameterized queries see: http://us2.php.net/manual/en/mysqli-stmt.prepare.php.
If you choose to go the back-end route, especially if you are using AJAX for the post, you can throw an Exception that actually outputs a 500 error along with the message you want to display, and then use Javascript to handle the "error case", so you can provide really nice validation methods that still do the validation on the server side.