Url from form using php - php

I am trying to create a link to include variables from a form.
The script below works put only includes the first variable:
http://example.com/abc.php?id=2
I want it to send:
http://example.com/abc.php?id=2&name=zac
PHP code shown below:
$base = 'http://example.com/abc.php';
$id=$_GET['ID'];
$name=$_GET['Name'];
$data = array(
'id' => $id,
'name' => $name,
);
$url = $base . '?' . http_build_query($data);
header("Location: $url");
exit;

You could make your life a bit easier by just sending the form via $_GET and it will redirect to the URL like you're wanting. Here's an example:
<form action="http://example.com/abc.php" method="GET">
<input type="text" name="ID" />
<input type="text" name="Name" />
</form>
This would send the user to: http://example.com/abc.php?ID=id_value&Name=name_value
Note: This will send all form variables with a value set.

Related

Request form and POST in a single go?

Please excuse the poor title.
I am a total beginner and don't know the right terms to make it better.
I am trying to POST form data using PHP.
My problem is that before i POST the form data i need to get a value from the form, that is changing each time i request the page.
Please notice the second input, the value is auto generated and is a random number each time i request the form.
Here is my form.php:
<?php
if(!isset($_REQUEST['submit_btn'])){
echo '
<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<input type="text" name="user_name" id="user_name">
<input type="hidden" name="a_random_password" value="'.(rand(10,100)).'">
<input type="submit" value="submit" name="submit_btn">
</form>';
}
if(isset($_REQUEST['submit_btn']))
{
$user_name= $_POST["user_name"];
$a_random_password = $_POST["a_random_password"];
echo "Your User Name is:". $user_name;
echo "<br> and your Password is : $a_random_password;
}
?>
And my post.php
<?php
$url = "http://test.com/form.php";
$data = array(
'user_name' => 'John',
'a_random_password' => 'xxx',
'submit' => 'submit'
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo "Error"; }
var_dump($result);
?>
So how do i get the a_random_password value and submit it along with the form in a single request, else the password wont fit with the user name.
Sup, what you wanna do is impossible using PHP in that way, cause the only job PHP has is to render your content on server side. To listen to the client side you'll need to use javascript.
let randomPassword = document.getElementById('a_randow_password')
let name = document.getElementById('name')
let password = document.getElementById('password')
name.onkeyup = function(){
password.value = randomPassword.value + name.value
}
<input type="text" id="name" name="user_name" placeholder="name"><br />
<input type="hidden" name="a_random_password" id="a_randow_password" value="xxx">
<input type="text" id="password" placeholder="password"><br />
Not sure exactly what you trying to achieve, but if You want to interrupt a request (and modify|use it) from HTML to PHP, You need AJAX request (JavaScript).

How to stay on HTML form page and not navigate to php form action page

I am working on a html form which will connect to a database using a php script to add records.
I have it currently working however when I submit the form and the record is added , the page navigates to a blank php script whereas I would prefer if it when submitted , a message appears to notify the user the record is added but the page remains the same. My code is below if anyone could advise me how to make this change.
Html Form :
<html>
<form class="form" id="form1" action="test.php" method="POST">
<p>Name:
<input type="Name" name="Name" placeholder="Name">
</p>
<p>Age:
<input type="Number" name="Age" placeholder="Age">
</p>
<p>Address
<input type="text" name="Address" placeholder="Address">
</p>
<p>City
<input type="text" name="City" placeholder="City">
</p>
</form>
<button form="form1" type="submit">Create Profile</button>
</html>
PHP Database Connection Code :
<html>
<?php
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx",
"Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values
('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
</html>
Typically your action file would be something like thankyou.php where you'd put whatever message to the user and then maybe call back some data that was submitted over. Example:
Thank you, [NAME] for your oder of [ITEM]. We will ship this out to you very soon.
Or this file can be the the same page that your form resides on and you can still show a thank you message with some javascript if your page is HTML. Something like:
<form class="form" id="form1" action="test.php" method="POST onSubmit="alert('Thank you for your order.');" >
I am taking into consideration that your PHP Database Connection Code snipplet that you posted above is called test.php because you have both connecting to the data base and inserting data into the database in one file.
Taking that into consideration, I think the only line you are missing, to return you back to to top snipplet of code that I shall call index.php would be an include statement just after the data has been added to the database
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values ('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
echo "Data added";
include 'index.php'; //This file is whatever had the earlier form
Once you hit the submit button on your form, test.php is called, your data is handled and passed back to index.php.
N.B:
The other thing i should mention is to make it a habit of using mysqli_real_escape_string() method to clean the data that is in the $_POST[]; because in a real website, if you don't, you give an attacker the chance to carry out SQL injection on your website :)
you said page is coming blank and data is saved so i assumed that there are two files one which contains form and another which contains php code (test.php).
when you submit the form you noticed that form is submitted on test.php
and your test.php has no any output code that's why you are seeing blank page.
so make a page thankyou.php and redirect on it when data is saved.header('Location: thankyou.php'); at the end of file.
Put this in form action instead of test.php
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Put your php code at top of the page.
$Name = $_POST['Name'];
This is step closer to being a safer way to posting into your db as well.
$Name =mysqli_real_escape_string( $_POST['Name']);
I like the jscript Alert from svsdnb to tell user data was successfully added to db.
This is not intended to be an out of the box solution; it's just to get you pointed in the right direction. This is completely untested and off the top of my head.
Although you certainly could do a redirect back to the html form after the php page does the database insert, you would see a redraw of the page and the form values would be cleared.
The standard way to do what you're asking uses AJAX to submit the data behind the scenes, and then use the server's reply to add a message to the HTML DOM.
Using JQuery to handle the javascript stuff, the solution would look something like this:
HTML form
<html>
<!-- placeholder for success or failure message -->
<div id="ajax-message"></div>
<form class="form" id="form1">
<p>Name: <input type="Name" name="Name" placeholder="Name"></p>
<p>Age: <input type="Number" name="Age" placeholder="Age"></p>
<p>Address: <input type="text" name="Address" placeholder="Address"></p>
<p>City: <input type="text" name="City" placeholder="City"></p>
<!-- change button type from submit to button so that form does not submit. -->
<button id="create-button" type="button">Create Profile</button>
</form>
<!-- include jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ajax stuff -->
<script>
// wait until DOM loaded
$(document).ready(function() {
// monitor button's onclick event
$('#create-button').on('click',function() {
// submit form
$.ajax({
url: "test.php",
data: $('#form1').serialize,
success: function(response) {
$('#ajax-message').html(response);
}
});
});
});
</script>
</html>
test.php
<?php
// note: never output anything above the <?php tag. you may want to set headers.
// especially in this case, it would be better to output as JSON, but I'm showing you the lazy way.
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx", "Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
// if mssql needs the non-standard brackets, then put them back in...
// note placeholders to get benefit of prepared statements.
$query = "INSERT INTO SalesLT.Test " .
"(Name,Age,Address,City) Values " .
"(?,?,?,?)";
$params1 = array($Name,$Age,$Address,$City);
$success = false;
if($result = sqlsrv_query($conn,$query,$params1)) {
$success = true;
}
sqlsrv_close($conn);
// normally would use json, but html is sufficient here
// done with php logic; now output html
if($success): ?>
<div>Form submitted!</div>
<?php else: ?>
<div>Error: form not submitted</div>
<?php endif; ?>

insert data in a wordpress database

I'm developing a WordPress plugin which is responsible for getting data from an external HTML form and then inserts it in the database. My form code is:
<html>
<body>
<form action = "http://wp.istic.online/wp-content/plugins/news-apps/index.php" method = "POST">
Name: <input type = "text" name = "name" />
<input type = "submit" />
</form>
</body>
</html>
My plugin code is:
<?php
register($_POST['name']);
register($_POST['name']);
function register($name) {
global $wpdb;
$wpdb->insert(
'gcm_tokens',
array(
'token' => $name
),
array(
'%s'
)
);
}
The data is not inserted however when I try to echo the $name variable it works perfectly. But when I try to echo it after the insert function it's not working.
Any help please?
Use wp_nonce_field() like below
<form>
/*
Your code
*/
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
First, make sure you have correct db prefix, correct table name and you can get $POST variable correctly.
I tried your code by call register('Test'); and It works.

how to pass parameter to php function and call in html

I have this function in php; a separate file, function dbRowInsert($table_name, $form_data).
I included it in my php file in which registration happens. My problem is how do I call the function on form submit and pass a parameter to the dbRowInsert function. This is the data of my form:
$form_data = array(
'username' => $username,
'password' => $password,
'title' => $title,
'first_name' => $first_name,
'middle_name' => $middle_name,
'last_name' => $last_name,
'position' => $position,
'residence' => $residence,
'monthly_salary' => $monthly_salary,
);
I tried this method:
<form id="signup_form" class="form-horizontal" role="form" action="<?php dbRowInsert(tblperson, $form_data) ?>">
...
</form>
PHP is not written like JavaScript; a POST request must be sent to a PHP page for processing (unless you're using AJAX), like so
<form method="POST" action="process.php">
....
</form>
In process.php, you have to extract out the fields you want to send to the function.
$username = $_POST['username'];
doSomethingWIthUserName($username);
Or in you case, since you are sending the entire array:
dbRowInsert("tblHelpers", $_POST);
Here's a detailed tutorial on handling POST requests.
Put all that in the same file where register form is after including function php file
<?php
//include file code start
function dbRowInsert($tblperson, $form_data){
echo "<pre>".print_r($form_data,true)."</pre>";
}
//include file code end
if(isset($_POST['submit'])){
$form_data = array();
$form_data['username'] = $_POST['username'];
$form_data['password'] = $_POST['password'];
$tblperson = "person";
//do the action
dbRowInsert($tblperson, $form_data);
}
?>
<form id="signup_form" method="post" class="form-horizontal" role="form" action="">
<input type="text" name="username" />
<input type="text" name="password" />
<input type="submit" name="submit" />
</form>

Sanitize input before executing at server in php

I want to let user input two variable, Name and Password in a form. I want to disable any XSS or script insert in the input values. I have the following code in the form method:
<form name="form1" method="post" action="checkpw.php">
Your Name:
<table>
<tr><td><input class="text" name="name" onBlur="capitalize(this);" maxlength=12 type="text" /></td></tr>
</table>
Password:
<table>
<tr><td><input class="text" name="passwd" maxlength=8 type="password" /></td></tr>
<tr><td align="center"><br/>
<input class="text" type="submit" name="submitbt" value="Login" />
</td></tr>
</table>
and the following checkpw.php:
<?php
// Clean up the input values
$post = filter_input_array(INPUT_POST, array(
'name' => FILTER_SANITIZE_STRING,
'pw' => FILTER_SANITIZE_STRING,
));
if (is_null($post) || in_array(null, $post)) {
header("location:login.php");
return; // missing fields (or failed filter)
}
// pw is the password sent from the form
$pw=$_POST['passwd'];
$name=$_POST['name'];
if($pw == 'testpass'){
header("location:index.php");
} else {
header("location:wrong.php");
}
?>
Is this a secure way to ensure the form is sent to the server and executed ONLY after the input values have been sanitized?
Also, the $name value i want to pass it to index.php file. I insert a code in the index.php as follow:
<?php echo $name ?>
But it's empty. Any idea how to resolve it?
You are issuing a header( .. ), that means that you are redirecting to another page and start all over.
You have 3 options:
put your $name in the session.
pass the $name in the header function, like header("location: index.php?name=$name");
do not redirect, but include the php file. In that case you do not need a session at all. Will be faster also, because you do not need a round trip to the browser.
As for sanitizing, for a start it will do. It depents what you later on will do with the data. I would suggest, if putting the data in a database to look in more detail what to do.
The magic_quotes_gpc should be disabled on most servers by now; however, do read this article to see other ways of disabling them.
Furthermore, you can use filter_input_array() (PHP >= 5.2) for this purpose:
$post = filter_input_array(INPUT_POST, array(
'name' => FILTER_SANITIZE_STRING,
'pw' => FILTER_SANITIZE_STRING,
));
if (is_null($post) || in_array(null, $post)) {
return; // missing fields (or failed filter)
}
// you can safely use $post['name'] and $post['pw'] here

Categories