how to change input text into url link - php

I have four input texts and one submit button
enter image description here
what I want is for the results of the input text to turn into a link that I use as a whatsapp message like this.
https://wa.me/628123456789?text=Hai%20My%20Name%20Andi
what should i do?
this is my code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<!-- https://wa.me/628123456789?text=textInput1%20textInput2%20textInput3%20textInput4 -->
<form action="https://wa.me/628123456789?text=textInput1%20textInput2%20textInput3%20textInput4" method="post">
<input type="text" name="textInput1" id="textInput1" ><br><br>
<input type="text" name="textInput2" id="textInput2" ><br><br>
<input type="text" name="textInput3" id="textInput3" ><br><br>
<input type="text" name="textInput4" id="textInput4" ><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
//target url --> https://wa.me/628123456789?text=textInput1%20textInput2%20textInput3%20textInput4
$url = null;
if(isset($_POST['submit']))
{
$textInput1 = $_POST['textInput1'];
$textInput2 = $_POST['textInput2'];
$textInput3 = $_POST['textInput3'];
$textInput4 = $_POST['textInput4'];
$url = "https://wa.me/628123456789?text=".$textInput1." ".$textInput2." ".$textInput3." ".$textInput4;
}
?>
</body>
</html>
this is var_dump result for my code
enter image description here

Simply set your form to method post, see my code below. Add name attributes to your inputs fields and submit button so you can retrieve their values through http post. Then check to see if the submit button has been posted using isset($_POST['submit']). If isset, we assign the values of your input fields to variables in order to recreate the urls post key/value pairs.
IMPORTANT NOTE: I am not covering cleaning of your input fields make sure to read up on proper cleaning of inputs depending on what you are allowing to be processed by the back-end code in order to recreate your url.
<form action="/https://wa.me/628123456789?text=textInput1%20textInput2%20textInput3%20textInput4" method="post">
<input type="text" name="textInput1" id="textInput1" ><br><br>
<input type="text" name="textInput2" id="textInput2" ><br><br>
<input type="text" name="textInput3" id="textInput3" ><br><br>
<input type="text" name="textInput4" id="textInput4" ><br><br>
<input type="submit" name="submit" value="Submit">
</form>
PHP:
//target url --> https://wa.me/628123456789?text=textInput1%20textInput2%20textInput3%20textInput4
$url = null;
if(isset($_POST['submit'])){
$textInput1 = $_POST['textInput1'];
$textInput2 = $_POST['textInput2'];
$textInput3 = $_POST['textInput3'];
$textInput4 = $_POST['textInput4'];
$url = "https://wa.me/628123456789?text=".$textInput1." ".$textInput2." ".$textInput3." ".$textInput4;
}
Example OUTPUT. Simply outputting the url within an html page in example:
In your html simply echo out the variable $url. it will only display in your code when it is actually set. <?=$url?> or <?php echo $url;?>
NOTE: If you are trying to place the link into your action attribute of your form prior to submitting the page so that the values set in the input fields are a part of the forms action, you will need to get the values before submitting the page by using JS or JQuery and getting the values of the inputs on change or something of that nature, then build the url in js/jquery then set your forms attribute action using JS/Jquery.
EDIT: I want the result of the input text to be a whatsapp message, so it will be placed in the url link. I have updated my post
Okay, to redirect user once the form is filled out and you have sanitized your inputs, set the url in your a header() function and redirect your user to the desired url.
*Make sure you remove the action attribute from your form as you will be redirecting using the php header() function instead.
if(isset($_POST['submit'])){
// I am using filter_var(FILTER_SANITIZE_STRING) in this example.
$textInput1 = filter_var ( $_POST['textInput1'], FILTER_SANITIZE_STRING);
$textInput2 = filter_var ( $_POST['textInput2'], FILTER_SANITIZE_STRING);
$textInput3 = filter_var ( $_POST['textInput3'], FILTER_SANITIZE_STRING);
$textInput4 = filter_var ( $_POST['textInput4'], FILTER_SANITIZE_STRING);
// make sure to test this url by echoing it out before you run the header redirect.
$url = urlencode("https://wa.me/628123456789?text=".$textInput1." ".$textInput2." ".$textInput3." ".$textInput4);
header("Location: $url");
exit();
}
Using a conditional with a foreach loop with header to contruct url from post values:
if(isset($_POST['submit'])){
$url = "https://wa.me/628123456789?text="; // declare the core of your url without the post values
$i = 1; // increment
$k = 0; // key value for $inputs
$userinput = ''; // empty variable to hold user inputs for encoding
$num = count($_POST) - 1; // count the number of items in the array to properly format spaces in url string subtract one for submit button
foreach($_POST as $value){ // run a foreach loop on the $_POST
if($value !== "Submit"){ // we remove the submit post value from our array by omitting it using does not equal
$inputs[] = filter_var ( $value, FILTER_SANITIZE_STRING); // create a new array and push values into it
if($i < $num){ // all but last iterations will produce the space
$url .= $input[$k]." ";
}else{ // last iteration will not have a space
$url .= $input[$k];
}
}
}
$url .= urlencode($userinput);
echo $url; // for testing purposes to make sure the string is populating the input values as you have entered them delete this line after testing.
//header("Location: $url"); <-- Uncomment this line to redirect
//exit(); <-- uncomment exit() if you uncomment header() to close after redirect to make sure code stops on this page.
}

Just add the function urlencode() before the content:
$url = urlencode("https://wa.me/628123456789?text=".$textInput1." ".$textInput2." ".$textInput3." ".$textInput4);

Related

How to go back to filled fields in a form after a php form is submitted?

I have a php form
After filling fields I submit the form
After submitting form I have in the same window (a pop up) a print (via echo) of strings using variables values previously entered in the form
I need a way to go back to the form with fields filled by the values entered previously in order to modify or review them and then submit the form again
My form is created in a proprietary php framework. A field is so defined in a file named base.env:
$sf_vaccine['fields']['taxCode'] = new TextField('taxCode');
$sf_vaccine['fields']['taxCode']->label = 'Codice fiscale';
$sf_vaccine['fields']['taxCode']->addFlag(Field::NOT_EMPTY());
$sf_vaccine['sheet']->addField($sf_vaccine['fields']['taxCode']);
After a research on the web and differents attempts I did this. After submitting the form I print a link to the previous page:
echo "<center>Go Back</a></center></br></br></br>";
It allows me to back to the previous page but fields are empty and not filled as I need
I've also made an attempt using sessions: here what I did:
<?php
session_start();
echo "<center><a href=http://192.168.228.34/it/centre_rm/card_block/?_command=insert&prefill=yes><b>Go Back</b></a></center></br></br></br>";
$_GET['prefill']=='yes';
$_SESSION['taxCode'] = $record['taxCode'];
$fields['taxCode']->value = $_SESSION['taxCode'];
Don't use javascript history for this, but just go back to the page after submitting the form and add the values to the form.
Something like this:
<?php
$length = '';
$width = '';
if (!empty($_POST)) {
if (isset($_POST['length'])) {
$length = $_POST['length'];
}
if (isset($_POST['width'])) {
$width = $_POST['width'];
}
echo "Submitted length '$length' and width '$width'.";
}
?>
<form method="POST" action="">
Length: <input type="text" name="length" value="<?= $length ?>"/>
Width: <input type="text" name="width" value="<?= $width ?>"/>
<input type="submit">
</form>
I've added the echo-statement as sort of confirmation message but this can be removed if not needed.
Because of the action="" part, after clicking submit, the same page wil reload. De input values are sent and can be reused on the page reload.
Within the if-statements the submitted values are assigned to a variable to add these again in the input fields within the value tag so they are prefilled with the submitted data.
If you'd like to modify the submitted values before adding them to the inputs, you can do this within the if-statements and adjust the data accordingly.

Create search box with json Data using PHP

im newbie how to create multi search box like this https://imgur.com/yPWUKAL ? my data is from json and im using php prog. my goal is get the value input by user then transfer to my function.
// create & initialize a curl session
$curl = curl_init();
$url = "data.json";
// set our url with curl_setopt()
curl_setopt($curl, CURLOPT_URL, $url);
// return the transfer as a string, also with setopt()
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// curl_exec() executes the started curl session
// $data_curl contains the output string
$data_curl = curl_exec($curl);
// close curl resource to free up system resources
// (deletes the variable made by curl_init)
curl_close($curl);
$data_json = json_decode( $data_curl );
if( !empty( $data_json )){
// fetch data
foreach ($data_json as $data ){
$loc_data = $data->location->city;
if( $loc_data == "San Francisco" ){
echo $loc_data;
}
}
}
else {
echo "No Data!";
}
?>
<form id="form" action="#" method="POST">
<input type="text" placeholder="Keyword" />
<input type="text" placeholder="Location" />
<input type="text" placeholder="Distance" />
<input type="submit" value="Search">
</form>
You need to understand the request cycle and the difference between client and server side code. PHP is a server side language, all the PHP code executes on a server and the output (whatever you echo, whatever HTML you write) is then sent to the client to be rendered in their browser.
To get user input (such as your form) you need to start a new request, i.e. when the form is submitted it starts a new request to the server, only the request now contains the data from the form in the $_POST superglobal.
Firstly, you need to add names to the inputs, as the name you use will be the key in the $_POST array, and the corresponding value will be the users input. E.g.
<input type="text" placeholder="Keyword" name="keyword">
Then whatever the user enters after submitting the form will be in $_POST['keyword'].
Secondly, you need to tell the form where to submit to using the action value. In this instance, you probably want it to submit back to the same php file, or you could move your function to retrieve data into another php file and then have the code submit to there. Assuming that your file is called search.php and people go to https://my.website/search.php to see the search box you would have the following:
<form id="form" action="/search.php" method="POST">
<input type="text" name="keyword" placeholder="Keyword">
<input type="text" name="location" placeholder="Location">
<input type="text" name="distance" placeholder="Distance">
<button type="submit">Submit</button>
</form>
Thirdly, when your script runs you need to check to see if there is any user input or not. If the user is just landing on your search page and hasn't filled the form out yet then there won't be any input for you to get. You can do this with a simple if statement and check the value of $_SERVER['REQUEST_METHOD'] to check if the request was a POST or a GET. Initial loads of the page without the form submission will use a GET request, where as form submissions will use a POST request.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// User has filled out the form, we can get location specific data
// ... your curl to fetch the data
if (!empty($data_json)) {
foreach ($data_json as $data) {
if ($data->location->city == $_POST['location']) {
echo $data->location->city;
}
}
}
}

How to call upon a PHP function on button click?

I am trying to setup a website that converts a Steam user ID into an auth ID. It will ask for the visitor to input their regular Steam ID and then hit a button to convert it to auth ID. Steam provides us with the function for ID conversion from one type to the other.
Steam function for converting IDs:
function convert_steamid_to_accountid($steamid)
{
$toks = explode(":", $steamid);
$odd = (int)$toks[1];
$halfAID = (int)$toks[2];
$authid = ($halfAID*2) + $odd;
echo $authid;
}
Below is my attempt at setting up a basic HTML page that gets user input and then uses the function to convert that input to something else.
<INPUT TYPE = "Text" VALUE ="ENTER STEAM:ID" NAME = "idform">
<?PHP
$_POST['idform'];
$steamid = $_POST['idform'];
?>
Also, this is what the default Steam user ID looks like:
STEAM_0:1:36716545
Thank you for all the help!
If you can make it into two seperate files, then do so.
foo.html
<form method="POST" action="foo.php">
<input type="text" value="ENTER STEAM:ID" name="idform" />
<input type="submit" />
</form>
foo.php
<?php
function convert_steamid_to_accountid($steamid)
{
$toks = explode(":", $steamid);
$odd = (int)$toks[1];
$halfAID = (int)$toks[2];
$authid = ($halfAID*2) + $odd;
echo $authid;
}
$id = $_POST['idform'];
convert_steamid_to_accountid($id)
?>
if you don't have an option of making two seperate files, you can add the php code to 'foo.html' file and make the form to submit to the same file. However if you do this, check if the file is getting requested the first time, or it is requested because the form is submitted, BEFORE you call convert_steamid_to_accountid() function.
You can do this by:
if ($_SERVER['REQUEST_METHOD']=='POST'){
// your php code here that should be executed when the form is submitted.
}

Form method - POST delete previous data

I am trying to get some data from page to page and then mail them.
So from one form I am getting a title of item :
//Form1
<form class="orderFormFields" method="post" action="order">
<input type="hidden" name="productName" value="<?php the_title(); ?>">
<input class="oButton" value="Order" type="submit"/>
</form>
And then is another form (next page) with other fields witch I need to mail :
<?php
//getting a variable from previous form
$product = $_POST['productName'];
if(isset($_POST['submit']))
{
$name = $_POST['order_name'];
$mail = $_POST['email'];
$phone = $_POST['mobile'];
$date = $_POST['date'];
$comment = $_POST['comment'];
//simple mail function goes here
$done = true;
}
?>
//Form2 goes here
So if I insert <?php echo $product; ?> before if(isset($_POST['submit'])) I can see my variable from previous page and all works just find. But when I am inserting that same variable in mail function witch is inside if(isset($_POST['submit'])) , I cant mail that variable, seems like it is empty.
Does form method POST delete all previous form data? Because, if I change my Form1 method to GET and $product = $_POST['productName']; to $product = $_GET['productName']; I am getting that variable after Form2 submit and I can mail that variable. But I would like to prefer using POST method, because of nice URL.
You forgot to name your submit button so there is no $_POST['submit']
<input class="oButton" value="Order" type="submit" name="submit" />
EDIT:
Okay, $_POST is array and have its values only after the post request. If you make another post request or change the page the previous values of $_POST are deleted and these from the new request are stored.
You can store data from the first post in the sessions for example -
$_SESSION['postData']['form1'] = $_POST;

Retaining values in forms fields when validation of data fails

I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>

Categories