GET and POST Method in same form - php

So i want to use the GET method and POST method on the same form. The GET to send the details from the form to the url bar and the post for a isset if statement to check if the form has been submitted. I would like to be able to do this. But if you can find another way of doing it please tell me
HTML
<form method="post">
<p>Username:</p><input type="text" name="Username">
<p>Password:</p><input type="password" name="Password">
<p>Post:</p><input type="text" name="Post" value=""><br><input type="submit"
value="submit" name="submited">
</form>
PHP
if (isset($_POST['submited'])){
$Username=$_GET["Username"];
$Password=$_GET["Password"];
$Post=$_GET["Post"];
$Password=md5($Password);
if(blah=blah){
echo "blah";
}
}

Change
isset($_POST['submited'])
to
isset($_GET['submited'])
But it is a really bad idea to send password using GET.

Kinda bad practice, but you could force it by sending parameters in URL:
Setting like action="index.php?data=123" should do the work:
<form method="post" action="index.php?name=a&surname=b"> //Here we go
<p>Username:</p><input type="text" name="Username">
<p>Password:</p><input type="password" name="Password">
<p>Post:</p><input type="text" name="Post" value="">
<br>
<input type="submit" value="submit" name="submited">
</form>

in your form you can change it's action -- so action="?var1=something&var2=example"
It could be done with javascript; example:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function() {
$('form').attr('action','?Username=' + $('input[name=Username]').val() + '&Password=' + $('input[name=Password]').val() + '&Post=' + $('input[name=Post]').val());
return true;
});
});
</script>
</head>
<body>
<form method="post">
<p>Username:</p><input type="text" name="Username">
<p>Password:</p><input type="password" name="Password">
<p>Post:</p><input type="text" name="Post" value=""><br><input type="submit"
value="submit" name="submited">
</form>
</body>
</html>

Personally I would POST the form to say my formprocess.php page, placing your
if(isset($_POST['submitted'])) {
//Code goes here, do checks/validation etc
}
Then once you've done what you needed to do with your code do a header (or meta redirect if you have already sent your headers) like so:
header('Location:http://www.mysite.com/index.php?value=formsubmitted&action=success');
So the value= and the action= could just be the values you want to pass back in the URL. You could also add some RewriteRule 's to your .htaccess to make these redirected URL's a bit prettier and better for SEO etc. Also if you do go down this route, make sure to set/define the redirection status i.e. 301 see below:
header("HTTP/1.1 301 Moved Permanently");

I think what everyone is wondering is why anyone would need to use $_GET if they are using $_POST.
i.e.:
if (isset($_POST['submited'])){
$Username=$_POST["Username"];
$Password=$_POST["Password"];
$Post=$_POST["Post"];
$Password=md5($Password);
if(blah=blah){
echo "blah";
}
}
... and if you want to check your parameters while developing just stick in...
print_r($_POST)
Is there any reason why you need to retrieve your form field data from a $_GET?

Related

php passing data form

I use the GET method to pass data from index.php to profile.php
index.php code is
<html>
<body>
<form action="profile.php" method="GET">
username: <input type="text" username="user"><br>
password: <input type="password" name="pass"><br>
<input type="submit">
</form>
<button type="button" onclick="alert('task success')"/>click me"</button>
</body>
</html>
profile.php code is
<?php
echo " username: "$_GET ['username']."; password "$_GET['pass'];
?>
the output is
it es pass the inputs of the form successfully but I need it to appear in profile.php file
how can I make the output appear in profile.php page?
any help please
The problem is that the page is redirected. You will need to send an AJAX request to the action that you want to execute. With jQuery you can prevent a form from submitting like this:
$('form').submit(function (evt) {
evt.preventDefault(); //prevents the default action
}
You will need to collect the parameters, send them via AJAX and handle the response.

Simple submit form to go to a page

I have some numbered pages:
1.php
2.php
3.php
etc.
I want to create a textbox that the user enter any number: 2 for example, and hit enter or Go button, and they will go to the page 2.php depending on the number entered.
I know how to link to a specific page as in form action="....", but I am not sure how to echo the user input and translate it as link (whether using html or php).
Ex:
<form method="POST">
<input type="number" value="" />
<input type="submit" value="Go" />
</form>
You need to add an action attribute to your form and a name attribute to your number input. The file from your action attribute will "catch" the POST variables and do the logic needed to redirect your user. Change your form tag to:
<form method="POST" action="redirect.php">
<input type="number" value="" name="redirect" />
<input type="submit" value="Go" />
</form>
Then create the redirect.php file that gets the POST variables and does the redirection:
<?php
$redirectPage = (int) $_POST['redirect'];
$redirectUrl = "http://www.example.com/{$redirectPage}.php";
header("Location: $redirectUrl");
printf('moved.', $redirectUrl);
Beware that there's no input validation nor error handling included.
I think, the best available option in your case would be the one using client-side javascript to dynamically change the form's action attribute base on the number entered in the input box.
A quick and dirty solution to fulfil such a task might look like this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function submitAction(formElement) {
var // get the input box element
el = document.getElementById('form-action-number'),
// get a number specified by user in the input box
num = parseInt(el.value),
// validate that it's really a number and is greater than zero
// (you don't want someone to request -666.php right? :)
// build a page url using the correct number
page = !isNaN(num) && num > 0 ? num.toFixed(0).toString() + '.php' : undefined;
if (page) { // the page url is valid
// set form's action attribute to an url specified by page variable
formElement.setAttribute('action', page);
// returning true will allow the form to be submitted
return true;
}
// you might think of a better way to notify user that the input number is invalid :)
console.error('INVALID NUMBER SPECIFIED!');
// returning false will prevent form submission
return false;
}
</script>
</head>
<body>
<!-- When user clicks Go, the return value of submitAction function will be used to decide if the form should be submitted or not -->
<form method="POST" onsubmit="return submitAction(this)">
<input id="form-action-number" type="number" value="" />
<input type="submit" value="Go" />
</form>
</body>
</html>
With PHP you can do something like this:
<?php
// Check if the POST value has been set
if(isset($_POST['my_number'])) {
// Redirect to the corresponding page
header('Location: ' . $_POST['my_number'] . '.php');
}
?>
<form method="POST">
<input name="my_number" type="number" value="" />
<input type="submit" value="Go" />
</form>
This is like DaMeGeX's answer but uses javascript to go to the new page.
<?php
// Check if the POST value has been set
if(isset($_POST['my_number'])) {
// Redirect to the corresponding page
echo "<script> window.location.href = '".$_POST['number'].".php' </script>";
}
?>
<form method="POST">
<input name="my_number" type="number" value="" />
<input type="submit" value="Go" />
</form>

How to validate form using another php file?

I am new to web designing. Now, I have created a form, and if the user input doesn't meet the requirements I display error message, and if it does I do some mysql commands to enter the info to the database. Now one way to do this is to code the php file into the html and use this command,<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> like described [here][1]
But I don't want to put the script in the same file. How do I do that in another php file such that if user input is invalid, it will return to the homepage with the error message updated?
Here is my code
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="register.css">
</head>
<h1>Register as A new user</h1>
<div id="signup">
<form id="registration_form" action="registration.php" method="post">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
<span class="errorMessage"></span>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
</div>
What should be in the registration.php? Like the link, I do everything, I set a flag to the error, Now if the flag is true I return the user to the homepage with the error messages, and if false, I show a message saying registration successful. How do I do the part,"return to homepage with the appended error message"?
All your validation and bulletproofing should be in the registration.php
stuff like this:
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['name'])) {
die('Must pass \'name\');
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['email'])) {
die('Must pass \'email\');
}
if(!isset($_GET['passwd'])) {
die('Must pass \'password\');
} else {
//do cool stuff here
}
Don't forget your JS validation as well for the front end. I really hope this helps and gives you a bit of direction.
put your validation codes in "validate.php" or any file name you like
then change the action to validate.php to
then in validate.php if validation matches the requirements.
header("Location: registration.php");
if not match
header("Location: back to the httml with form.php");
You can learn form validation here : http://allitstuff.com/registration-form-in-php-with-validation/

How to do a ajax request for login

I have this in my PHP code, and it currently does the login request in the same login.php page but now i want to do it with Ajax. Basically I have this in the login.php
echo '<form method="post" ><div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" name="submitlogin" class="button" />
</div>';
I would like to still use this but have a login_request.php or something where i can send the username and password validated and then change the <div id=login> to say you are logged in!</div> I can do it the conventional way, with the form post .. but now I would like to try it with Ajax.
Any help will be much appreciated.
Regards
What have you tried so far? This is how I would start:
This should get you started:
HTML:
<form id="loginForm">
<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="button" value="Submit" id="submitlogin" class="button" />
</div>
</form>
jQuery:
$("#submitlogin").click(function() {
inputs = //grab then inputs of your form #loginform
$.ajax ({
url: "urltoyourloginphp.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
}
});
})
I wrote this a while ago, it's not quite a full ajax login (i.e. at the end it does still redirect you), but it may serve as a basis for a full ajax login. As a plus you actually don't need https (that was the whole point of this little project).
https://github.com/eberle1080/secure_http_login/blob/master/login.php
The high level steps go something like this:
Ask the server for a seed value (a salt) using an ajax request
Hash the password + seed using a sha1 sum
Ask the server to verify the username and salted + hashed password
If it's valid, the server sets a session cookie indicating that the user is logged in
The server responds to the ajax request with a success / fail message
jQuery has built in .post() and .serialize() methods for wrapping up a form.
$.post("login.php", $("#loginForm").serialize(), function(data) {
//pass information back in with data. if it's JSON, use $.parseJSON() to parse it.
alert('either logged in or errored');
);
You will also need to edit your form so it has an id, like: <form id="loginForm">...
I don't know PHP but will give you an example of how I would have done it with vbscript (classic asp) so you may try to adapt it to PHP as needed.
I, in my applications, don't use the form tag since I first used ajax. So, here we go:
login html page:
include jquery
<script type='text/javascript' src='your-jquery-url'></script>
<script type='text/javascript'>
function tryLogin() {
var inputs='userName='+$('logInUsername').val()+
'&userPassw='+$('logInPassword').val();
//notice that I changed your name= to id= in the form
//notice the '&' in the '&userPassw=
$.post('your-login-validation-page',inputs,function(data) {
eval('var json='+data);
if (json['success'] == 'true') {
$('#loginForm').html('<p>Congratulations! You\'ve been logged in successfully</p>')
} else {
alert(json['errorMessage']);
$('#logInUsername').focus();
}
});
}
</script>
<div id='loginForm' >
<label for="login">User Name</label>
<input type="text" id="logInUsername" />
<label for="Password">Password</label>
<input type="password" id="logInPassword" />
<button onClick='tryLogin(); ' >LOGIN</button>
</div>
login-validation-page
[in vbscript]
user = request.Form("userName")
passw = request.Form("userPassw")
"if is there this user" (coded as if there was a database look up...)
"if the password = passw" (coded as comparing the values)
response.write "{'sucess':'true'}"
else
response.write "{'success':'false','errorMessage':'wrong password'}"
end if
else
response.write "{'success':'false','errorMessage':'user not found'}"
end if
---> end of login-validation-page

POST without redirect with PHP

I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/
The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.
<form method="POST" action="mlml/process.php">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="submit" value="" id="submit"name="submit" >
</form>
You will need AJAX to post the data to your server. The best solution is to implement the regular posting, so that will at least work. Then, you can hook into that using Javascript. That way, posting will work (with a refresh) when someone doesn't have Javascript.
If found a good article on posting forms with AJAX using JQuery .
In addition, you can choose to post the data to the same url. The JQuery library will add the HTTP_X_REQUESTED_WITH header, of which you can check the value in your server side script. That will allow you to post to the same url but return a different value (entire page, or just a specific response, depending on being an AJAX request or not).
So you can actually get the url from your form and won't need to code it in your Javascript too. That allows you to write a more maintanable script, and may even lead to a generic form handling method that you can reuse for all forms you want to post using Ajax.
Quite simple with jQuery:
<form id="mail_subscribe">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="hidden" name="action" value="subscribe" />
<input type="submit" value="" id="submit"name="submit" >
</form>
<p style="display: none;" id="notification">Thank You!</p>
<script>
$('#mail_subscribe').submit(function() {
var post_data = $('#mail_subscribe').serialize();
$.post('mlml/process.php', post_data, function(data) {
$('#notification').show();
});
});
</script>
and in your process.php:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'subscribe' :
$email_address = $_POST['address'];
//do some db stuff...
//if you echo out something, it will be available in the data-argument of the
//ajax-post-callback-function and can be displayed on the html-site
break;
}
}
?>
It redirects to a different page because of your action attribute.
Try:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="text" name="address" id="email" maxlength="30" size="23" />
<input type="submit" value="" id="submit" name="submit" />
</form>
<?php if (isset($_POST['submit'])) : ?>
<p>Thank you for subscribing!</p>
<?php endif; ?>
The page will show your "Thank You" message after the user clicks your submit button.
Also, since I don't know the name of the page your code is on, I inserted a superglobal variable that will insert the the filename of the currently executing script, relative to the document root. So, this page will submit to itself.
You have to use AJAX. But that requires JavaScript to be active at the users Brwoser.
In my opinion it's the only way to do without redirect.
to send a form request without redirecting is impossible in php but there is a way you can work around it.
<form method="post" action="http://yoururl.com/recv.php" target="_self">
<input type="text" name="somedata" id="somedata" />
<input type="submit" name="submit" value="Submit!" />
</form>
then for the php page its sending to have it do something but DO NOT echo back a result, instead simply redirect using
header( 'Location: http://yourotherurl.com/formpage' );
if you want it to send back a success message simply do
$success = "true";
header( 'Location: http://yourotherurl.com/formpage?success='.$success);
and on the formpage add
$success = $_GET['success'];
if($success == "true"){ echo 'Your success message'; } else { echo
'Your failure message';
Return and print the contents of another page on the current page.
index.php
<html>
<body>
<p>index.php</p>
<form name="form1" method="post" action="">
Name: <input type="text" name="search">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_POST['search'];
include 'test.php';
}
?>
</body>
</html>
test.php
<?php
echo 'test.php <br/>';
echo 'data posted is: ' . $_POST['search'];
?>
Result:
Just an idea that might work for you assuming you have no control over the page you are posting to:
Create your own "proxy php target" for action and then reply with the message you want. The data that was posted to your php file can then be forwarded with http_post_data (Perform POST request with pre-encoded data). You might need to parse it a bit.
ENGLISH Version
It seems that no one has solved this problem without javascript or ajax
You can also do the following.
Save a php file with the functions and then send them to the index of your page
Example
INDEX.PHP
<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
Tools.php (It can be any name, note that it is kept in a folder lame tools)
<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}
if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
Use
form onsubmit="takeActions();return false;"
function takeAction(){
var value1 = document.getElementById('name').innerHTML;
// make an AJAX call and send all the values to it
// Once , you are done with AJAX, time to say Thanks :)
document.getElementById('reqDiv').innerHTML = "Thank You for subscribing";
}

Categories