I need to create a simple postcode / page finder for a site where a user will enter their postcode and be redirected to a page based on whether or not that location is covered by the company.
Basically the same as used on this site: http://www.dailypoppins.co.uk/
The fact it is a postcode is kind of irrelevant. For simplicity I'd probably just like a PHP file which takes the value entered into the form, checks it against a predefined list of values (Postcodes, there aren't that many currently covered) and then redirects the user to the correct page depending on the value / postcode entered.
Does anyone know how to do this?
This is a simple example..
$validPostcodes = array('123', '456', '789');
// get form value
$postcode = $_GET['postcode'];
if (isset($validPostcodes[$postcode])) {
header('Location: http://www.newsite.com/'.$postcode);
}
else {
echo 'Postcode does not exist';
}
Like I said..this is only a very simple example. I might be better to have the postcodes stored in a database and do some error checking on the form value.
I suggest to read about PHP form validation and PHP database access and of course HTML forms.
PHP database access 1,
PHP database access 2,
PHP Form handling,
HTML forms
Related
I'm creating a site (with PHP & MySQL) that takes a user input, generates a random link, and uses that users input on the generated link to show content.
The nearest real-life example would be http://pastebin.com/ - you enter a text input on the homepage, it generates a random link (such as http://pastebin.com/2hf4Dtv7 and then the text you input is permanently displayed on that generated link.
I've been stuck on this problem for what seems like forever. I've managed to get different parts of the problem solved (I think), but I can't seem to get it to work altogether.
Key facts
The user input needs to be available to use on the generated link
A PHP file run.php is what I will use to display content / manipulate the user's input, so somehow needs to be available on the generated link (unless there's another way to do this).
I have a MySQL database that currently has / stores 3 columns: ID (integer, which automatically increments), userinput (varchar, which is set to unique) and pageurl (varchar, which is also set to unique)
The site is using WordPress, but that's not too important as I'm dealing with the PHP / htaccess file(s) directly.
Things I've attempted / managed to do:
I can generate a random string for the url, via <?php echo $randGen ?>. This can be put into <form action="<?php echo $randGen ?>" method="POST"> - This works in the sense that it will open a tab to domain.com/xyz, but that 404s & run.php isn't assigned to the generated link (I'm not sure if the input value is either).
Tried both POST and GET methods in the form. The input data isn't sensitive, so it isn't a huge issue which is used.
Read up on & attempted to use .htaccess rewrite rules / pretty urls, such as RewriteRule ^([0-9a-zA-Z]+)$ run.php?userinput=$1 [NC,L], as well as trying to use [QSA] & &%{QUERY} to keep the user input, but found myself to be way out of my depth.
Attempted to covert the MySQL (auto-incrementing) ID to base64, but aren't sure where to run the PHP script to get it working & also don't understand how to append that random string to the URL, while still showing the users input.
Watched numerous tutorials on how to create pastebin-esque sites / URL shortener sites, to see if I could get any relevant ideas from that - to no avail.
You are almost there, RewriteRule is the way to go.
With this in your apache configuration:
RewriteRule ^([0-9a-zA-Z]+)$ run.php?randurl=$1 [L]
This, in your html page:
<form action="/run.php" method="POST">
Userinput: <input type="text" name="userinput">
You then just need to use the variables $_GET['randurl'] and $_POST['userinput'] in run.php:
if (isset($_POST['userinput'])) { // user adds a new input
// insert into database (userinput, randurl) values ('".$_POST['userinput']."', '".$randGen."')
// redirect the user to the new short URL page:
header('Location: domain.com/'.$randGen);
}
else if (isset($_GET['randurl'])) { // user wants to access the short URL
// retrieve userinput from database:
// select userinput from mydatabasename where randurl = 'domain.com/'.$_GET['randurl']
$sql = "SELECT userinput FROM articles WHERE randurl = '".$_GET[randurl]."'";
$result = $conn->query($sql);
if ($result) {
if ($row = $result->fetch_object()) {
// echo select result in the page
echo($row['userinput']);
}
else
echo("error: fetch_object");
$result->close();
}
else
echo("error: query");
}
I've just designed my first form in HTML and a PHP page to display the results. In the form the user inputs some codes in response to some questions, a bit like a multiple choice, so for example, these are "ABC". The PHP page displays the code to the user as a link, which when clicked will go to a bookmark (a link within the same page) with the ID #ABC. This was achieved with simple manipulation of the PHP variable as follows:
<?php
$code = "ABC"
$part1 = '<a href="mywebpage.php#';
$part2 = '">Go to this code</a>';
$string = $part1.$code.$part2;
echo $string;
?>
(i.e. Link in the page says "go to this code" and when clicked will go to section with bookmark ABC)
This all works fine, but I simply need to know if there is a way of error trapping so that if a bookmark does not exist for the code entered, a message can be displayed to the user instead? Can this be done using the PHP variable, or do I need to use JavaScript? One work around may be to search the web page for the ID "#ABC'. Is it possible to do this? Another option would be to store an array of valid codes on the server then query this before setting the bookmark, but I want to keep it as simple as possible. Any help appreciated, thanks.
What you call a "bookmark" we call a hash. And when you say "go to a bookmark" you mean a hash change. Hash changes do not make an additional request to the server, it is all handled on the client-side, therefore this must be done with JavaScript and not PHP.
So let's just do some simple JavaScript on hash change window.onhashchange that will search for an element with that ID and if it's not found alert something.
window.onhashchange = function(){
if(!document.getElementById(location.hash){
alert("not found");
}
}
I want to use an idea that I have seen on another website where I enter a "keyword", press Enter, and it then takes the client to a specific page or website.
I have seen something like this on http://qldgov.remserv.com.au, On the right side there is a field called "My Employer", type in "health" for example and you will be provided with relevant content.
Essentially I have client branded mini sites where we want to assign a "keyword" for each client brand so all of their employees will be able to go to their site entering this one keyword without all of them having individual logins. I want to be able to link to a URL that I can define in some manner.
I have looked at the source code of the site mentioned above and see they are using a form but I am not sure how they have assigned the keywords or if its even possible to do this without a database or anything like that. Trying to keep it as simple as possible as I am not a PHP/Java expert by any means.
Any help would be appreciated, even if its not code but an idea of the direction I need to go in to make this work. Thanks in advance!! :-)
The easiest way in my eyes would be to define an array that contains all of the keywords and respective urls client side (in JS). For example:
​var array = { 'health' : '/health.php', 'sport' : '/swimming.php' };
You would then get the user input on onSubmit and if it exists modify the window.location appropriately.
if ( array[user_input] !== undefined ) {
window.location = array[user_input];
}
else {
alert ( 'not found' );
}
If the user supplied health they will be redirected to /health.php, if they supply sport they will be redirected to /swimming.php (JSFiddle). Alternatively you can use server-side (PHP, JAVA) to handle the request but this may not be worth the effort.
Goodluck.
By using php (rather than javascript), you're not relying on javascript + making it seo friendly.
Firstly you're going to need either some sort of database or a list of keywords/urls
$keywords = array('keyword1' => 'path/to/load.php', 'another keyword' => 'another/path');
Then you'll need a basic form
<form action="loadkeyword.php">
<input name="query">
<button type="submit">Go</button>
</form>
Then in loadkeyword.php
$keywords = array('keyword1' => 'path/to/load.php', 'another keyword' => 'another/path');
$query = $_GET['query'];
if (isset($keywords[$query])) {
$url = $keywords[$query];
header("HTTP/1.0 301 Moved Permanently");
header('location: '.$url);
exit;
} else {
header("HTTP/1.1 404 Not Found");
die('unable to locate keyword');
}
If you have a large list of keywords, I would suggest using a database instead of an array to keep track of your keywords.
The site you link to is doing it server-side, either via a keyword-list that matches content or a search function (I suspect the latter).
There are a few different ways you could achieve your goal, all of them to do with matching keywords to content and then redirecting, either with an array, a list, or a database - the principle will be the same.
However, I would respectfully suggest this may not be the best solution anyway. My reasoning is that (based upon the example you give) you're effectively making your users guess which keyword matches which minisite (even if you have many keywords for each site). Why not just have some kind of menu to choose from (i.e. a selector with a list of minisites)?
I am having a difficulty of finding a answer that is simple to follow and understand... I making a site (on dreamweaver cs5) and the frontpage of the site has a select city and a dropdown of all the major cities and a email text box.
I have a few questions and those are as follows:
What is my next step now that I have the html pretty much done... do I connect it to a database?
What php script would I need to make sere both fields (the city and email) are filled? and where would I enter this php script?
Here is some of my code in case you were wondering:
http://answers.yahoo.com/question/index?qid=20110611111223AAeAnrT (had to put it on here because overflow wouldn't let me put in code..)
Just a quick starter, to get your form up.
On creating your PHP script, I don't know much about Dreamweaver, but if you have PHP installed on your server, you should be able to create it in the same directory as your HTML. All of the form elements should be in a form tag, and should point to the PHP, such as <form method="POST" action="dosomething.php"> before and </form> after.
Also, a "Please select your city..." might be nice to have on the form, like <option value="unset">Please select your city...</option>. (Also, all of the options in the sample should have a value attribute).
I don't know how much you have learned about PHP, so I'm going to try to start with the basics. The PHP script would be a plain-text file with the extension .php, such as dosomething.php. Inside of the script, the PHP code needs to be surrounded by the PHP start and end tags, <?php and ?>.
The values inputed into the form should be accessible with the $_POST variables in PHP, so in the script $_POST['select'] will be set to the current value. I recommend setting the names to something you can remember, such as selectedCity and emailAddress.
In our PHP script, we will want to get the variables from our form, and check to see if they are both filled. Then the data will get written to the database. I have created a sample snippet below that is commented, but extra security should be added, and this code should not be used as-is.
<?php
$city = $_POST['selectedCity']; // Get the city the user selected from the form
$addr = $_POST['emailAddress']; // Save the email address the user entered
if($city == "unset")
{
// Stops user if a city hasn't been selected
die("Please select a city."); // Stop executing code, and tell user to go back and select a city
}
if($addr == "")
{
// Stops user if the email address is blank (also would be good to make sure email address is correct, like user#domain.com)
die("Please enter a valid email address");
}
if(!file_exists("../mailinglist.sqlite"))
{
// Creates the database if it doesn't exist
// The database should be outside the document root (meaning you can't access it through the web)
$db = sqlite_open("../mailinglist.sqlite"); // Opens the database, creates it if non-existent (it is)
sqlite_query("CREATE TABLE users (city, email)"); // Creates a table for users
}
else
{
$db = sqlite_open("../mailinglist.sqlite"); // Opens the database if it exists
}
sqlite_query("INSERT INTO users (city, email) VALUES ('".sqlite_escape_string($city)."','".sqlite_escape_string($city)."')"); // Add the new user to the database
?>
(Anything that you need help with that is in blue should be searchable on the PHP Documentation)
The code above will take the output from the HTML form, check to make sure that it is not empty, and enter it into a database, creating a new database if it does not exist. Again, this is just a starter, and the code needs to be improved before taking it live.
Hope this helps!
I am using Symfony 1.3.2 with Propel ORM on Ubuntu 9.10.
I have developed a form that dynamically populates a select widget with cities in a selected country, using AJAX.
Before the data entered on the form is saved, I validate the form. If validation fails, the form is presented back to the user for correction. However, because the country list is dynamically generated, the form that is presented for correction does not have a valid city selected (it is empty, since the country widget has not changed yet).
This is inconvenient for the user, because it means they have to select ANOTHER country (so the change event is fired), and then change back to the original country they selected, then FINALLY select the city which they had last selected.
All of this is forced on the user because another (possibly unrelated) field did not vaildate.
I tried $form->getValue('widget_name'), called immediately after $form->bind(), but it seems (infact, IIRC, if form fails to validate, all the values are reset to null) - so that does not work.
I am currently trying a nasty hack which involves the use of directly accesing the input (i.e. tainted) data via $_POST, and setting them into a flash variable - but I feel its a very nasty hack)
What I'm trying to do is a common use case scenario - is there a better way to do this, than hacking around with $_POST etc?
What I do for this exact issue is that I post the form to the same action that generated it, and in that action, I grab any selected countries/regions/cities as POST variables and pass them back to the template (regardless of validation). In the template, I then use JQuery to set the select values to what they were. When validation passes, they get used. When not, they get passed back to template.
If you can tolerate a little PHP in your JQuery, you could do this in the template:
$(document).ready(function()
{
$("#country-select").val('<?php echo $posted_country; ?>');
});
If you use this approach, don't forget to initialise $this->posted_country in your template the first time around or Jquery will get confused.
I guess you could also use $this->form->setWidget(...)->setDefault(...) or something similar, but I havent found a way around using $_POST as accessing the elements seems to need binding the form otherwise.
UPDATED CODE IN RESPONSE TO COMMENTS BELOW:
if($_POST['profile']['country_id'] != '')
{
$this->posted_country = $_POST['profile']['country_id'];
$q = Doctrine_Query::create()
->select('c.city_id, c.city_name')
->from('City c')
->where('c.country_id = ?', $this->posted_country);
$cities = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);
foreach($cities as $city) $list[$city[0]] = $city[1];
$this->form->setWidget('city_id', new sfWidgetFormChoice(array('choices' => array('' => 'Please select') + $list)));
}
So... I get the country from the post, I query db with that, get cities, and craft cities back into a dropdown. Then in the template, you can set a default selected city with something like $this->posted_city (which would be a POST variable too, if exists).