Why does PHP POST Method not work on mac? - php

I am new to PHP. I have written a simple code to collect data from a form using PHP. I am using the POST Method to collect the form data but it goes to the else statement. Can someone please help me out.
Thanks in advance!!
My Code-
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<input type="text" id="name" name="name">
<input type="submit" name="submit" id="submit">
</form>
<?php
if(isset($_POST)){
$x = $_POST['name'];
echo $x;
}else {
echo "failed";
}
?>
</body>
</html>

Don't you need an attribute called "action" to perform something like that? Or maybe it isn't needed if it is in the same file

I think the culprit here is the isset function call. That function returns false even if a variable has been set but equals null, which I believe is what's happening here. Are you supplying any input before submitting?
I recommend using this to check if the form was submitted instead.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
...
}
You can then process the inputs in that block. You might also try checking for !empty instead of isset if you want to keep exploring your script as it is now.

Former answer was incorrect, time for an update.
Running your original code locally on OS X 10.14 using php 7.1 works fine.
Do you have a local server setup? How are you accessing the page that isn't behaving as expected? What happens when you place <?php phpinfo(); ?> in the same file?

Related

(PHP) I can't get a form action PHP code to work

I am not sure what i am doing wrong, but i cannot get a PHP form action page to work, when i attempt to run it, it takes me to a blank page that does nothing. I am trying to create a simple code that redirects the user to a page depending on the input on the form. Here is what my form code looks like:
<form action="index.php" method="post">
<font face="Stymie">ENTER SECRET CODE: <input type="text" name="secretcode"></font>
</form>
and here is what the index.php currently looks like:
<html>
<body>
<?php
if ($_POST['secretcode'] === "banana") {
header("Location: banana.php");
}
?>
</body>
</html>
This is one out of many codes i attempted to use, yet no matter what i put, it always takes me to a blank page. I also tried using GET instead of POST, but that just leaves me on the page without the code running.
Can someone tell me what i am suppose to do to get the code working? Help would be much appreciated.
UPDATE: I found a Javascript equivalent to this script which is a lot more efficient and simpler, thus i no longer need an answer.
<form onSubmit="return checkAnswer();">
<script>
function checkAnswer(){
var response = document.getElementById('secretcode').value;
if (response == "banana")
location = 'banana.html';
else
location = 'wrong.html';
return false;
}
</script>
Add a submit button:
<form action="index.php" method="post">
<font face="Stymie">ENTER SECRET CODE: <input type="text" name="secretcode"></font>
<button type="submit" name="submit" value="Enter"/>
</form>
And for the php code:
<?php
if (isset($_POST['submit'])) {
if($_POST['secretcode'] === "banana"){
header("Location: banana.php");
}
}
?>
I added the isset() to prevent possible Undefined index: errors when you expand the php codes
UPDATE
I just tried OP's codes, it is submitting even without a submit button (didn't know that, or maybe I just forgot).
It seems working for me, I am being redirected to banana.php when I typed banana in the input, the only problem I saw is the Undefined index error (which the isset() will solve it)

PHP is not passing my user entries

Hi I'm learning php of a tutorial and these are my two files. I browse to my apache2 server via http://myservers-ip/form2.php
fill out the forms and hit the submit button, it calls my result.php page, but all it displays is "Hi ." where it should be like "Hi (userentry)."
Please help :-(
form2.php:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Enter your name</h1>
<form method="post" action="result.php">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
and my result.php
Hi <?php print $username; ?>.
Using apache2 and mysql running on my box.
I'm not sure if the source code is correct or if there might be a misconfiguration? if so which config files would you need?
Thanks
Data sent via a form with POST action will be in the superglobal $_POST array. You would want to sanitize it before trying to use it for anything, but just starting with $_POST['username'] will get you closer to your end goal.
Edit: Whatever tutorial you are using, abandon it. It's clearly waaaaay outdated.
You're sending data from form via post so you need to get them in your result.php file from POST superglobal like so:
Hi <?php print $_POST['username']; ?>.
The data is being sent to results.php via POST method.
All post params are stored in $_POST param. So to get user name you need to get it from $_POST, in results.php. E.g:
<?php
// file: results.php
if (isset($_POST['username']){
echo "Hi, {$_POST['username']}.";
} else {
echo "No user name."
}

PHP - Submit button does not work

I just started to learn PHP. I use a "Missing Manual" series book. I downloaded PHP 5, I installed it with the option "Do not setup a web server". From command line I can launch a php test program. But I can launch from browser.
The HTML code :
<html>
<head></head>
<body>
<h1>Welcome!</h1>
<form action="scripts/sayHelloWeb.php" method="POST">
<p><i>Enter your name:</i>
<input type="text" name="name" size="20" /></p>
<p><input type="submit" value="Say Hello" /></p>
</form>
</body>
</html>
and sayHelloWeb.php code is :
<html>
<head></head>
<body>
<h1>Hello, <?php echo $_REQUEST['name']; ?></h1>
</form>
</body>
</html>
Well, the HTML works : the text input and the buttons are displayed
, but php does not display any name. That is the "name" variable is empty. It displays only : "Hello, ". The folder scripts exists, the path is correct.
Where I did wrong ?
Thank you.
You have to setup a web server otherwise you can't run php file. if you check the source of sayHelloWeb.php after loading it, you will see that the php code is commented which means that it's not runned.
Make sure to install a web server. Wampserver is a good choise for beginners.
PHP is a Hypertext Preprocessor meaning that its not meant to be be interpreted on the client but rather on the server end, prior to the delivery of the HTML document itself. Installing a PHP interpreter along with a capable web server is required to make PHP work.
If you are seeing PHP code in your browser you can be sure that PHP is not set up correctly with your web server. Installing PHP itself merely installs a local PHP interpreter without setting it up to handle incoming web requests, for that you need a "proper" web server like Apache or IIS.
A good way to test if PHP is working is by creating this document:
<?php
phpinfo();
and loading it into your browser. Upon successful installation of PHP, a detailed (extremely verbose) status of PHP and web server components can be seen.
First check if is submit btn clicket. Than get value from field. Whitout that u will get notice
<?php
if ($_POST['submit']) {
$msg = $_POST['name'];
}
?>
<html>
<head></head>
<body>
<h1>Hello, <?php echo $msg ?></h1>
</form>
</body>
</html>
Try to use isset() and empty() on $_REQUEST
if (isset($_REQUEST['param']))
{
if(empty($_REQUEST['param']))
{
///
}
}
or
if ((isset($_REQUEST['submit'])) && (!empty($_REQUEST['name'])))
{
$name= $_REQUEST['name'];
}
<html>
<body>
<h1>Hello, <?php echo $_POST['name']; ?></h1>
</body>
</html>
Should work?
These fields are stored in $_POST array.
Try this: echo $_POST['name'];

HTML PHP Form Processing; Variable

I'm a newbie learning and trying to understand how html forms and php processing works.
Came across this pair of examples:
HTML FORM:
<html>
<body>
<form action="hello-web.php" method="GET">
<label>Name:</label>
<input type="text" name="yourName" size="24">
<input type="submit">
</form>
</body>
</html>
PHP PROCESSOR:
<?php
$fname = $_GET["yourName"];
echo "Hello $fname!";
?>
OUTPUT SHOULD BE:
Hello Entered/Example Name!
QUESTION:
When I try to change the variable "yourName" (on BOTH HTML and PHP files) to, for example "typeName" , the entered name on the form does not show up.
In other words, the output becomes just: Hello !
Is "yourName" a standard php or html variable? Can it not be changed to what ever you want it to be?
Better yet, how exactly does the form process data?
Here is my altered code that won't output the entered name (I posted here as an answer because all the codes shows up as a continuous line, like a paragraph, when I paste as a comment to your answer:
HTML FORM(altered--typeName):
<html>
<body>
<form action="hello-web.php" method="GET">
<label>Name:</label>
<input type="text" name="typeName" size="24">
<input type="submit">
</form>
</body>
</html>
PHP PRCESSOR (altered--typeName):
<html>
<body>
<?php
$fname = $_GET["typeName"];
echo "Hello $fname!";
?>
</body>
</html>
You can see what data is available to you from the submitted form by outputting the entire array. Since your form method is GET, the following will show you all that was submitted:
var_dump( $_GET );
From this, you can see what the variable names should be in your PHP script.
Array
(
[YourName] => Jonathan
)
Anytime you come across a disconnect between what is being submitted, and what you're expecting, check $_GET (or if your method is POST, you would check $_POST).
For instance, if I were trying the following:
echo $_GET["yourName"]; // nothing output to the screen
I could refer to the array contents printed above and see that the correct key is "YourName":
echo $_GET["YourName"]; // Jonathan
$_GET["yourName"]; Contains a value based off of the input of the form field. It's a php superglobal http://us3.php.net/manual/en/reserved.variables.get.php
It sounds like you're changing the html form, but your not entering a value through the form. Therefore, $_GET["yourName"]; is empty

Issues With PHP Session

I am trying to create a very simple session between 3 php pages as: index.php ,validate.php and target.php
index.php
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start A Session</title>
</head>
<body>
<h1>Welcome to Heaven</h1>
<form method="POST" action="validate.php">
Your Name: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
and validate.php as:
<?php
session_start();
$err="Not Allowed";
if(($_POST['name']) == $_SESSION['uid']){
header ("Location: heaven.php");}
else
{echo $err; }
?>
and finally target.php as
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start Email with PHP</title>
</head>
<body>
<h1>Welcome to Targer <?php echo $_SESSION['uid'] ?></h1>
<img src="session.jpg">
</body>
</html>
Now my questions are:
How come user still can get access to target page while I have already set a session between pages(according to my understanding of sessions the target page must NOT be accessible unless the correct seesion value has been submitted but I can get access to page by clicking on page link in wamp index list! with echoing the $err; ! )
I tried to validate the $_SESSION value by using the isset() but it did'nt go through! can you please let me know how I can modify the validate.php using the isset() instead of if(($_POST['name']) == $_SESSION['uid']) comarison?
Can you please let me know how I can merge two (index.php and validate.php) in one page? I mean how I can validate the session inside the index.php and reduce the files two index and target? In this case I need to handle the wrong logins inside the index page.
Finally, can you please let me know how I can assign the value to $_SESSION from user input? I mean instead of having a hard coded part like $_SESSION['uid'] = 'test'; let the session value start with user input! I know this looks meaningless here but I would like to get idea on creating captcha in same index page
Thanks for your time in advance
This should work properly and just with 2 files. You could even compress it to 1 file, if you really want so (it's much harder to understand), ask for it and I can make it.
index.php:
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start A Session</title>
</head>
<body>
<h1>Welcome to Heaven</h1>
<form method="POST" action="heaven.php">
Your Name: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
And the other file, heaven.php
<?php
session_start();
if (!empty($_SESSION['uid'])&&$_POST['name']==$_SESSION['uid'])
{
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start Email with PHP</title>
</head>
<body>
<h1>Welcome to Targer <?php echo $_SESSION['uid'] ?></h1>
<img src="session.jpg">
</body>
</html>
<?php
}
else
{
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Access denied</title>
</head>
<body>
Sorry, you have no permission to access this page.
</body>
</html>
<?php
}
?>
'Validation' is just to display the desired message if the strings match or to display a 'you cannot see this page' if they don't match.
The !empty() needs to be set. Else, imagine what would happen if someone visited the 'heaven.php' page without going first to index.php. You'd compare 2 empty strings! So it would be validated. The alternative is to put $_SESSION['uid'] = 'test'; at the beginning of heaven.php also.
I didn't really answer your questions in order (and in the 2nd one I cheated as I put 2nd and 3rd file together instead of 1st and 2nd), but my code should cover all your problems. For the last part, it's simply $_SESSION['uid']=$_POST['name']; , but it'd be a no sense to do it while validating user. The validation must come from somewhere, generally from a mysql database.
Please start to accept answers to your questions if valid (below the up/down button).
1) What do you mean by assigning correct session value? "heaven.php" is a file which is accessible by anyone if you don't check for access rights in that file.
2) Not sure what you mean. If you need to check if two variables exist and match, you need something like if ( (isset($_POST['name']) && isset($_SESSION['uid'])) && (($_POST['name']) == $_SESSION['uid']) )
3) If there's no need to reduce files to minumun, it's a good idea to keep validating, form processing etc. function in their respective files. If you want to valide session and form values within "index.php" you can do so by first checking if the values exist and then do to them whatever you like. (Like in the 2 above.)
4) You can assign user inputted values for variables by using forms. It's what you are doing with your form currently. In you process file/function you do something like:
if(isset($_POST['submit']){
$_SESSION['uid'] == $_POST['name'];
}
The example above is very simplified.
Finally. You aren't really validating anything, you just check if two values match. Validating means that you make sure value meets the standard(s) specified, for example user submitted value is an integer when it should be an integer (when inserted into database or used some other manner). I think you should see some tutorials about form processing and user input validation before creating anything that's intended in production environment.

Categories