Create search box with json Data using PHP - 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;
}
}
}
}

Related

how to change input text into url link

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);

Refresh page without losing the Post value

How do I maintain the $post value when a page is refreshed; In other words how do I refresh the page without losing the Post value
This in not possible without a page submit in the first place! Unless you somehow submitted the form fields back to the server i.e. Without Page Refresh using jQuery etc. Somesort of Auto Save Form script.
If this is for validation checks no need for sessions as suggested.
User fills in the form and submits back to self
Sever side validation fails
$_GET
<input type="hidden" name="first"
value="<?php echo htmlspecialchars($first, ENT_QUOTES); ?>" />
validation message, end.
alternatively as suggested save the whole post in a session, something like this, but again has to be first submitted to work....
$_POST
if(isset($_POST) & count($_POST)) { $_SESSION['post'] = $_POST; }
if(isset($_SESSION['post']) && count($_SESSION['post'])) { $_POST = $_SESSION['post']; }
You can't do this. POST variables may not be re-sent, if they are, the browser usually does this when the user refreshes the page.
The POST variable will never be re-set if the user clicks a link to another page instead of refreshing.
If $post is a normal variable, then it will never be saved.
If you need to save something, you need to use cookies. $_SESSION is an implementation of cookies. Cookies are data that is stored on the user's browser, and are re-sent with every request.
Reference: http://php.net/manual/en/reserved.variables.session.php
The $_SESSION variable is just an associative array, so to use it, simply do something like:
$_SESSION['foo'] = $bar
You could save your $_POST values inside of $_SESSION's
Save your all $_POST's like this:
<?php
session_start();
$_SESSION['value1'] = $_POST['value1'];
$_SESSION['value2'] = $_POST['value2'];
// ETC...
echo "<input type='text' name='value1' value='".$_SESSION['value1']."' />";
echo "<input type='text' name='value2' value='".$_SESSION['value2']."' />";
?>
Actually in html forms it keeps post data.
this is valuble when you need to keep inserted data in the textboxes.
<form>
<input type="text" name="student_name" value="<?php echo
isset($_POST['student_name']) ? $_POST['student_name']:'';
?>">
</form>
put post values to session
session_start();
$_SESSION["POST_VARS"]=$_POST;
and you can fetch this value in another page like
session_start();
$_SESSION["POST_VARS"]["name"];
$_SESSION["POST_VARS"]["address"];
You can use the same value that you got in the POST inside the form, this way, when you submit it - it'll stay there.
An little example:
<?php
$var = mysql_real_escape_string($_POST['var']);
?>
<form id="1" name="1" action="/" method="post">
<input type="text" value="<?php print $var;?>"/>
<input type="submit" value="Submit" />
</form>
You can use file to save post data so the data will not will not be removed until someone remove the file and of-course you can modify the file easily
if($_POST['name'])
{
$file = fopen('poststored.txt','wb');
fwrite($file,''.$_POST['value'].'');
fclose($file);
}
if (file_exists('poststored.txt')) {
$file = fopen('ipSelected.txt', 'r');
$value = fgets($file);
fclose($file);
}
so your post value stored in $value.

Form to form with PHP

I am trying to create a multi steps form where user will fill the form on page1.php and by submitting can go to page2.php to the next 'form'. What would be the easiest way?
Here is my code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
?>
<form id="pdf" method="post">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
if ($_POST["pr_name"]!="")
{
// data collection
$prname = $_POST["pr_name"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, enddate, sel, content) VALUES(?,?,?,?)");
if (!$stmt) echo "\nPDO::errorInfo():\n";
$stmt->execute(array($prname,$prend, $prmenu, $prcontent));
}
// somehow I need to check this
if (data inserted ok) {
header("Location: pr-pdf2.php");
}
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
I have changed following Marc advise, but I don't know how to check if the SQL INSERT was OK.
Could give someone give me some hint on this?
thanks in advance
Andras
the solution as I could not answer to my question (timed out:):
Here is my final code, can be a little bit simple but it works and there are possibilities to check and upgrade later. Thanks to everyone especially Marc.
<form id="pdf" method="post" action="pr-pdf1.php">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
Email subject:<input type="text" name="pr_subject" placeholder="must be filled..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
include_once "ckeditor/ckeditor.php";
$CKEditor = new CKEditor();
$CKEditor->basePath = 'ckeditor/';
// Set global configuration (will be used by all instances of CKEditor).
$CKEditor->config['width'] = 600;
// Change default textarea attributes
$CKEditor->textareaAttributes = array(“cols” => 80, “rows” => 10);
$CKEditor->replace("pagecontent");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// data collection
$prname = $_POST["pr_name"];
$prsubject = $_POST["pr_subject"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, subject, enddate, sel, content) VALUES(?,?,?,?,?)");
// error checking
if (!$stmt) echo "\nPDO::errorInfo():\n";
// SQL command check...
if ($stmt->execute(array($prname, $prsubject, $prend, $prmenu, $prcontent))){
header("Location: pr-pdf2.php");
}
else{
echo"Try again because of the SQL INSERT failing...";
};
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
Add the attribute action with the url you'd like to go to. In this case it'd be
<form id="pdf" method="post" action="page2.php">
EDIT: i missed you saying this method doesn't work. What part of it doesn't work?
You should keep the action to the same script, so the POST action is still performed and then redirect with header("Location: page2.php"); when the processing is done.
A basic structure like this will do it:
form1.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... process form data here ...
if (form data ok) {
... insert into database ...
}
if (data inserted ok) {
header("Location: form2.php");
}
}
?>
... display page #1 form here ...
And then the same basic structure for each subsequent page. Always submit the form back to the page it came from, and redirect to the next page if everything's ok.
You're probably better off separating the php code from the form. Put the php code in a file called submit.php, set the form action equal to submit.php, and then add the line header('Location: whateverurl.com'); to your code.
The easiest way is to post it to form2.php by giving the form the attribute action="page2.php". But there's a risk in that. It means that form2 must parse the posted data of form1. Also, if the data is wrong (verification) form1 must be shown instead of form2. This will make your code over complicated and creates dependencies between the two forms.
So the better solution (and quite easy as well) is to implement the post-redirect-get pattern.
You post to form1, verify all data and store it. If the data is ok, you redirect to form2. If the data is wrong, you just show form1 again.
Redirecting is done by a header:
// Officially you'll need a full url in this header, but relative paths
// are accepted by all browsers.
header('Location: form2.php');
Save already posted fields in hidden input fields, but don't forget to validate them every time user submits another step of the form as the user may change hidden inputs in source code.
<input type="hidden" name"some_name" value="submitted_value"/>
There are several ways handling the submitted data while jumping between steps.
You will find your reasons for /against writing data to session, database, whatever... after each step or not.
I did following approach:
The form includes always a complete set of input elements, but on page #1 the step-2-elements are hidden ... and other way round.
I built a 6-step-wizard this way. One large template, some JS /Ajax for validating input, additional hidden inputs that hold current step-ID and PHP deciding, which fields to show or hide.
The benfit in my opinion: Data can easily be saved completely, as soon as input is alright and complete. No garbage handling, if users abort after step 1.
I would store it all in a session array (or sub array)
a really rough example where I'm saving all the form names to an array (to be checked later of course):
<?
foreach($_POST as $k => $v){
$session['register'][$k]=$v;}
?>

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>

Reading remote files using PHP

can anyone tell me how to read up to 3 remote files and compile the results in a query string which would now be sent to a page by the calling script, using headers.
Let me explain:
page1.php
$rs_1 = result from remote page a;
$rs_2 = result from remote page b;
$rs_3 = result from remote page c;
header("Location: page2.php?r1=".$rs_1."&r2=".$rs_2."&r3=".$rs_3)
You may be able to use file_get_contents, then make sure you urlencode the data when you construct the redirection url
$rs_1 =file_get_contents($urlA);
$rs_2 =file_get_contents($urlB);
$rs_3 =file_get_contents($urlC);
header("Location: page2.php?".
"r1=".urlencode($rs_1).
"&r2=".urlencode($rs_2).
"&r3=".urlencode($rs_3));
Also note this URL should be kept under 2000 characters.
Want to send more than 2000 chars?
If you want to utilize more data than 2000 characters would allow, you will need to POST it. One technique here would be to send some HTML back to the client with a form containing your data, and have javascript automatically submit it when the page loads.
The form could have a default button which says "Click here to continue..." which your JS would change to "please wait...". Thus users without javascript would drive it manually.
In other words, something like this:
<html>
<head>
<title>Please wait...</title>
<script>
function sendform()
{
document.getElementById('go').value="Please wait...";
document.getElementById('autoform').submit();
}
</script>
</head>
<body onload="sendform()">
<form id="autoform" method="POST" action="targetscript.php">
<input type="hidden" name="r1" value="htmlencoded r1data here">
<input type="hidden" name="r2" value="htmlencoded r2data here">
<input type="hidden" name="r3" value="htmlencoded r3data here">
<input type="submit" name="go" id="go" value="Click here to continue">
</form>
</body>
</html>
file_get_contents certainly helps, but for remote scripting CURL is better options.
This works well even if allow_url_include = On (in your php.ini)
$target = "Location: page2.php?";
$urls = array(1=>'url-1', 2=>'url-2', 3=>'url-3');
foreach($urls as $key=>$url) {
// get URL contents
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$target .= "&r".$key."=".urlencode($output));
}
header("Location: ".$target);
You can use the file_get_contents function.
API documentation: http://no.php.net/manual/en/function.file-get-contents.php
$file_contents = file_get_contents("http://www.foo.com/bar.txt")
Do note that if the file contain multiple lines or very, very long lines you should contemplate using HTTP post instead of a long URL.

Categories