How to modify query string to plain url using PHP? - php

I have following html form :
<div class="row form">
<div class="col-md-offset-3 col-md-6 col-md-offset-3">
<form class="form-inline" role="form" method="get" action="<?php echo htmlspecialchars(SITE_URL.'location'); ?>">
<div class="form-group col-md-10 no-p-m">
<select class="form-control" id="basic" name="location" required>
<?php
$get_location = mysqli_query($conn, "SELECT * FROM product_sub_area");
if(mysqli_num_rows($get_location) == 0 ) {
$choose = 'No City found';
} else {
$choose = 'Choose City';
}
?>
<option value=""><?php echo $choose; ?></option>
<?php
while($get_location_result = mysqli_fetch_array($get_location) ) {
$location_id = (int) $get_location_result['psub_area_id'];
$location_name = htmlspecialchars($get_location_result['psub_name']);
echo "<option value='$location_id'>$location_name</option>";
}
?>
</select>
</div>
<div class="form-group col-md-2 no-p-m" id="basic">
<input type="submit" class="btn btn-default filter-search" value="BROWSE">
</div>
</form>
</div>
</div>
When I submit this form the url is showing like bellow :
http://localhost/freelancer/happiechef/location?location=1
But I need to show this type of url :
http://localhost/freelancer/happiechef/location/carlifonia
here /location/ is a page called location.php. I am hiding page extension using .htaccess.
So from location.php page I want to get $_GET['location'] value = $location_id
for eg.
$_GET['location'] = 1 or 2 ( select tag option value)
Existing .htaccess code
ErrorDocument 404 not-found.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^location/([\w-]+)$ location.php?location=$1 [QSA,NC,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

Here is an example of how this can be accomplished in jQuery:
First, add an id to your <form> tag so you can access it easily:
<form id="formname" class="form-inline" role="form" method="get" action="<?php echo htmlspecialchars(SITE_URL.'location'); ?>">
You also have a duplicate id called "basic". Make sure you leave it only on the <select> tag and remove the other one.
Then in your JS:
$("#formname").submit(function(event) {
event.preventDefault();
var loc = $("#basic option:selected").text();
window.location.href = '/freelancer/happiechef/location/' + loc;
});
This will forward the user to the URL, for example http://localhost/freelancer/happiechef/location/carlifonia. Then .htaccess will rewrite this URL to location.php?location=california.

Related

.htaccess rewrite url , dont work on Form Submit

I am working on a search display, but got some problems with the htaccess, not working the way I want it to. I got multiple rewrites on the same url and I assume thats why. But i am not sure..
UPDATE: From what I can see by testing, all the Rewrite urls work. But the form force the page over to search.php?search=test and not search/test as i want.
So the real question is:
How do I get form action="" to submit to search/test/ and not search.php?search=test
What i get:
search.php?page=1
search.php?type=DEFINED_TYPE&search=test
search.php?type=DEFINED_TYPE&search=test&page=1
What i want:
search/1
search/DEFINED_TYPE/test
search/DEFINED_TYPE/test/1
Form:
<form action="" method="get" id="searchForm">
<label for="DEFINED_TYPE_radio">
<input type="radio" name="type" id="DEFINED_TYPE_radio" value="DEFINED_TYPE"<?php if($_GET['type'] == 'DEFINED_TYPE') echo ' checked' ?> />
<em<?php if($_GET['type'] == 'DEFINED_TYPE') echo ' class="selected"' ?>><i class="fas fa-tags"></i>Type</em>
</label>
<div class="input">
<input type="text" placeholder="Search here..." value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>" name="search" id="searchField" autocomplete="off" autofocus>
<i class="fa fa-search submit" id="submit"></i>
</div>
</form>
Htaccess:
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
RewriteRule ^search$ search.php [NC]
RewriteRule ^search/([^/]+)$ search.php?page=$1 [NC]
RewriteRule ^search/([^/]+)/([^/]+)$ search.php?type=$1&search=$2 [E=ORIG_URI:/$1]
RewriteRule ^search/([^/]+)/([^/]+)/([^/]+)?$ search.php?type=$1&search=$2&page=$3 [E=ORIG_URI:/$1]
Anyone who can spot what I do wrong?
Note that as you are using get method on the form, every field is added with its name to the url as a param.
I suggest you submit the form with method post and add the url in the action attribute (or the whole url):
<form action="search.php?search=test" method="post" id="searchForm">
or
<form action="/search/test" method="post" id="searchForm">
That involves changing how you read those values

How to submit a form by appending textbox value to URL in PHP?

I have a HTML form containing a textbox and a submit button. When I submit the form, I want textbox value appending to the URL.
For example, if my domain is http://www.example.com/ and form lies on index.php. Suppose textbox value is "test" then when the form is submitted the URL should change to http://www.example.com/test. How can we achieve it?
HTML Code:
<form method="post" action="">
<input type="text" name="txtname" value="<?php echo $name; ?>" />
<input type="submit" name="btnsubmit" value="Submit" />
</form>
PHP Code:
<?php
$name = NULL;
if(isset($_POST['btnsubmit']))
{
$name = $_POST["txtname"];
}
?>
.htaccess Code:
# .htaccess mod_rewrite
# example.com
#Enable mod rewrite
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
How about a jQuery solution? Something like...
$(document).ready(function(){
var txtname = $('#txtname').val();
var url = window.location.href;
var new_url = url + "/" + txtname;
$('#formid').on('submit', function(e){
e.preventDefault();
// Do what you need to do here.
console.log(new_url);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formid" method="post" action="">
<input id="txtname" type="text" name="txtname" value="testname" />
<input type="submit" name="btnsubmit" value="Submit" />
</form>
You could use header:
$name = $_POST['txtname'];
header('Location: http://www.example.com/$name');
If you want to get the value without the error you can set the variable to empty like this:
$name = isset($_POST['txtname']) ? $_POST['txtname'] : '';
Place that after your opening php tag.

PHP search form not working with .htaccess

I have search country form with code:
<form name="form_search" id="form_search" class="form1" method="get" action="country/search"><div class="row">
<div class="col-sm-4 col-md-7">
<label>Select country</label>
<div class="select1_inner">
<div class="form-group">
<select class="select2 select" style="width: 100%" name="q" id="q">
<?php
$sql = "SELECT * FROM country";
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) :
$country_name=$row['country_name'];
?>
<option value=<?php echo $country_name?>><?php echo $country_name?></option>
<?php endwhile;?>
</select>
</div>
</div>
</div>
At the frontend url will show : http://example.com/country/search?q=parameter
but I would redirect that url to real directory at the backend http://example.com/page.php?module=search&id1=$1
with .htaccess
RewriteEngine On
Options -Indexes
rewriteRule ^country/search$ page.php?module=search&id1=$1 [L]
But this is not working I can't get value q parameter
Please help me how configure .htaccess for this form
Thanks.
You should use RewriteCond backreferences:
RewriteCond %{QUERY_STRING} q=([^&]*)
RewriteRule ^country/search$ page.php?module=search&id1=%1 [R=301,L]
Line 1: test if query string containing q={any_characters}
Line 2: if the url is country/search, redirect to page.php?module=search&id1={any_characters} permanently

Codeigniter no data sent posted on form

My login system suddenly stopped working, I can't fix it, I've been looking into it and it seems that the data doesn't get posted back but I can't find the problem.
This is my view:
<?php if(! is_null($err)) echo "<div class=\"alert alert-danger\">".$err."</div>";?>
<form class="form-signin" action="<?php echo site_url("user/validate"); ?>" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="email" class="sr-only">Email address</label>
<input type="email" name="email" class="form-control" placeholder="Email address" required autofocus>
<br/>
<label for="password" class="sr-only">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<br/>
<button class="btn btn-lg btn-primary btn-block" name="submit" type="submit">Sign in</button>
</form>
</div>
This is my my validate function inside the user controller:
public function validate()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
// Load the model
echo "$email and $password sent";
print_r($this->input->post());
exit();
$this->load->model('User_model');
// Validate user's login details
$result = $this->User_model->validate($email, $password);
// Now we verify the result
if($result == 0){
// If user did not validate, then show them login page again
$err = 'Invalid email and/or password.';
$this->login($err);
}else{
// If user did validate send him to homepage after setting the credentials
$this->session->set_userdata($result);
redirect(site_url("/index/index"));
}
}
the echo and the print_r show that no data is posted.
After some research I found out that the problem should be the .htaccess file, this is my current .htaccess:
RewriteEngine On
RewriteRule ^(application) - [F,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
But it's not working.
you have an exit(); in validate function comment it
try : if(!empty( $err ))
try : base_url("index.php/user/validate");
try : load model inside
public function __construct()
not inside of
public function validate()
<form class="form-signin" action="<?php echo site_url("user/validate"); ?>" method="post">
Change this to the following:
<form class='form-signin' action="<?php echo base_url();?>user/validate" method="post" name="user_from">
Also don't use the submit button name as 'submit'. Just use sbt or other name, id too...

PHP: Validating Form When Routing

I'm trying to validate a form that's being submitted through a PHP router.
All my traffic is sent to index.php via htaccess. to index.php:
RewriteEngine On
RewriteBase /router
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /divbase/index.php?/$1 [L]
index.php then provides the appropriate content:
<?php
Router::get('/form', function() {
include 'content/form.php';
});
?>
so when you go to example.com/form, the form page is loaded:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
However, when I try to submit the form on that page it 404s. After doing some troubleshooting, it looks like the PHP thinks that the form is being submitted to index.php rather than form.php.
I've tried to set the form action to:
<?php "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>
But it still 404s. Does anyone have any suggestions for this?
You need to add another route for POST, for example...
Router::get('/form', function() {
include 'content/form.php';
});
Router::post('/form', function() {
echo 'Hello world';
});
Your form is using method="post" so you need to add a POST route

Categories