PHP - Redirect Based On Postcode/zip Code
Hi, can anyone help me?
I am trying to create a form which asks the user to input their postcode then submit. the purpose is so if the service my site offers is not available in the location that the end user lives, then I want to display a message saying 'Sorry, not available', but if they are in area then it redirects to another page.
My form code is:
<form method="post" action="forwarder.php"> <p> Enter Post Code He <input type = "text" name = "zip" id = "zip" size = "10" maxlength = "5" "> <input type='submit'> </form>My PHP is: <?php $zip = isset ($_POST['zip']) { if ($zip=='NG15') { header('Location: https://www.bing.com'); } else { header('Location: http://www.google.co.uk') } ?>I am a bit of a newbie at this, and I know my PHP won't give me my desired result, but I was using this to try and test the concept. Help would be really appreciated, and if you can show me how to do it for multiple postcodes even better Similar TutorialsHi All, Long long long time lurker here!
A little background to understand how this fits in So I am building a local directory for my local area as part of a community project. Part of this there is the ability for local stores to sell online locally for people to have delivered or collect. So in the UK we have postcodes in the formats: AB12 3CD, A1 2BC A12 3CD, A1B 2CD
Most delivery pricing solutions only care about the full postcode as they are all about national delivery or at best only care about the first half. Due to the local nature we need more granularity to it so we have some rules: Delivery Available EH => Price EH3 => Price EH3 1 => Price EH3 1-4 => Price
Exceptions - No Delivery allowed EH => null EH3 => null EH3 1 => null EH3 1-4 => null
Can mix and match for example:
EH3 = £2.00 EH3 2 => £2.25 EH3 5 => null
This means that ALL EH3 address the delivery cost is £2 BUT If they are in EH3 2 then its £2.25 or if the are in EH3 5 then no delivery is possible.
I have came up with this monstrosity of code that for the most part works but also can throw the wrong delivery prices out due to bugs and issues that I can't seem to work out!
Main Function: function isDeliverable($postcode, $rules){ $canDeliver = false; $deliveryValue = 0.00; $found = false; list($outward, $inward) = explode(' ', $postcode); $area = substr($outward, 0, 2); $district = substr($outward, 2); $sector = substr($inward, 0, 1); $unit = substr($inward, 1,1); $rulez = json_decode($rules, true); //RULE START - EH10 9RJ $pcFound = inRule($rulez, $postcode); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9RJ //RULE START - EH10 9R $pcFound = inRule($rulez, $area.$district.' '.$sector.$unit); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9R //RULE START - EH10 9A-F $pcFound = inRule($rulez, $area.$district.' '.$sector.$unit, 1); if($pcFound){ $postArray = postcodeExploder($pcFound, 1); $pcFound = inRule($postArray, $area.$district.' '.$sector.$unit); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH10 9A-F //RULE START - EH10 9 $pcFound = inRule($rulez, $area.$district.' '.$sector); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH10 9 //RULE START - EH10 1-4 $pcFound = inRule($rulez, $area.$district.' '.$sector, 2); if($pcFound){ $postArray = postcodeExploder($pcFound, 2); $pcFound = inRule($postArray, $area.$district.' '.$sector); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH10 1-4 //RULE START - EH10 $pcFound = inRule($rulez, $area.$district); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH20 //RULE START - EH1-20 $pcFound = inRule($rulez, $area.$district, 3); if($pcFound){ $postArray = postcodeExploder($pcFound, 3); $pcFound = inRule($postArray, $area.$district); if($pcFound){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } } //RULE END - EH1-20 //RULE START - EH $pcFound = inRule($rulez, $area); if($pcFound && !strpos($pcFound['postcode'], "-")){ return ['canDeliver' => $pcFound['deliverable'], 'deliveryValue' => $pcFound['price']]; } //RULE END - EH return ['canDeliver' => $canDeliver, 'deliveryValue' => $deliveryValue]; }
Helper Functions: function inRule($rules, $postcode, $type = null){ foreach($rules as $key => $rule){ if(substr_count($rule['postcode'], '-') !== 0 && strlen($postcode) > 2){ $pEX = postcodeExploder($rule, $type); foreach($pEX as $r){ if($r['postcode'] == $postcode){ return $rules[$key]; } //$rule['postcode'] = trim(substr($rule['postcode'], 0, strpos($rule['postcode'], "-")-1)); } } if ( $rule['postcode'] == $postcode ) return $rules[$key]; } return false; } function postcodeExploder($rule, $type){ $out = []; $r = explode(' ', $rule['postcode']); $count = count($r); //It must be in the form AB1 1C //$first = AB1 //$last = 1C-G if($count == 2){ list($first, $last) = $r; } else { $last = $r[0]; } list($left, $right) = explode('-', $last); $sec = $left[0]; $leftInward = substr($last, strpos($last, '-')-1,1); $rightInward = substr($last, strpos($last, '-')+1,1); $range = range($leftInward, $rightInward); foreach($range as $key => $ra){ if($type == 1){ $out['a'.$key] = [ 'postcode' => $first.' '.$sec.$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } else if($type == 2){ $out['a'.$key] = [ 'postcode' => $first.' '.$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } else { $out['a'.$key] = [ 'postcode' => preg_replace('/\PL/u', '', $left).$ra, 'deliverable' => $rule['deliverable'], 'price' => $rule['price'] ]; } } return $out; } Stores Rules: $rules = '{"a1":{"postcode":"EH9","deliverable":true,"price":"1.50"},"a2":{"postcode":"EH9 7","deliverable":true,"price":"1.60"},"a3":{"postcode":"EH9 7A","deliverable":true,"price":"1.70"},"a4":{"postcode":"EH9 7AY","deliverable":true,"price":"1.80"},"a5":{"postcode":"EH1-2","deliverable":true,"price":"1.90"},"a6":{"postcode":"EH1 2-3","deliverable":true,"price":"2.00"},"a7":{"postcode":"EH4 5A-N","deliverable":true,"price":"2.10"},"a8":{"postcode":"EH","deliverable":true,"price":"1.40"},"a9":{"postcode":"TD14","deliverable":true,"price":"2.00"},"a10":{"postcode":"TD14 5DC","deliverable":false,"price":null}}';
Good day: I am tryint to redirect back to a page based on non selection. I am using this code, it is redirecting but not passing the $aid variable on the url. The page is getting the passed variable before doing the redirect. Here is the code: Code: [Select] if ($_POST['hid']==0) { header('Location: sample.php?aid=."$aid"'); } Thanks in advance. Greetings gurus, I need some help, please. I have a classic ASP background and now trying to get my feet wet with php. We have a web app that is used by several depts. I have been told to modify the app so that user is redirected to a site specific to their dept. For instance, if we have say, 3 deppts, HR, IT, and Payroll; if a user who belongs to the Payroll dept logs into the system, s/he will be redirected to PayRoll section of the page. I have done this tons of times using asp. Below is the code I used for asp: Code: [Select] 'Page = validateUser.asp SQL ="SELECT * FROM users " _ & " WHERE Username = '" & Request.Form("txtUserid") & "'" _ & " AND password = '" & Request.Form("TxtPassword") & "' " Set objRS = objConn.Execute( SQL ) If Not objRS.EOF Then If objRS("password") = Request.Form("txtPassword") Then Session.Contents("access_level") = objRS("access_level") Session.Contents("userID") = objRS("userID") 'ID column Session("username") = objRS("username") Session("password") = objRS("password") access_level = CInt(Session("access_level")) username = CStr(Session("username")) Select Case access_level Case 1 Response.Redirect "HRPage.asp" Case 2 Response.Redirect "PayrollPage.asp" Case 3 Response.Redirect "ITPage.asp" Case Else Response.Redirect "default.asp" End Select Else Response.Write "Sorry, but the password that you entered is incorrect." End If Else Response.Write "Sorry, but the username that you entered does not exist." End If objRS.Close Set objRS = Nothing objConn.Close Set objConn = Nothing Then on each page, I would do the check before redirecting the user: Code: [Select] If Session.Contents("access_level") <> 1 AND _ Session.Contents("access_level") <> 2 AND _ Session.Contents("access_level") Then Response.Redirect "default.asp" End If How I can use similar code in php? I hope you can assist me. Thanks very much Hi, I'm trying to get a working php script that will redirect visitors based on a number of variables. I first want to check the country the visitor is from, and redirect based on the user's country ip address. If visitor is not from the US, then go to google.com (for example)... but only after also checking some other variables. I want to also redirect any user (including US visitors) who are using a mobile device browser/cell phone, and redirect visitors coming from a Linux box. I'm not sure how to add those as if/else statement. Any help would be appreciated. Here's what I have so far... Geo ip Redirect: ------------------- <?php require_once("GeoIP.inc"); $gi = geoip_open("GeoIP.dat",GEOIP_STANDARD); $country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']); geoip_close($gi); if($country_code == 'US') { header('Location: http://www.google.com'); } else { header("Location: http://www.redirect.com"); } ?> Mobile Browser Redirect: ------------------------------ require_once('mobile_device_detect.php'); mobile_device_detect(true,false,true,true,true,true,true,'http://redirect.com',false); So not sure how to detect and redirect Linux users, and then how to link these all together in one script so it checks all variables before sending user to destination URL. Hope you can help. I really appreciate it! Hi there,
Is it possible to redirect to another URL based on the cookie that has already loaded on the page?
For example,
If cookie = cookie_name then redirect to http://www.google.com
Thanks!
Hi This should be pretty simple but I can't figure it out.
I want to create and simple forward to different URL based on the user entry.
For example.. If they enter ABC in the box they go to www.11.com if they enter ZXC in the box they go to www.22.com if they enter CCC they go to www.33.com If they enter anything else they get an error message.
Thanks for any help!!
Hello, This is what I'm trying to-do. I have an index.php file I would like a bit of code that says "If you got here from www.websitea.com (or a link within that site) OR www.websiteb.com" do this : else do this: I'm just not sure how to check where they're coming from. so basically if your on google.ca and you goto the site it will exicute the else part of the code but if your already on sitea or b and you click a link it will not Hi. I am trying to create a very simple admin login page that will let only me access a number of pages. I am trying the following code for the login page: Code: [Select] <?php session_start(); // Define your username and password $username = "username"; $password = "password"; if ($_POST['txtUsername'] == $username && $_POST['txtPassword'] == $password) { $_SESSION['admin']="true"; header("location: admin.php"); } ?> ### HTML code and form for entering in username and password with action echoing it back to itself ### On the admin.php page i then try: Code: [Select] <?php if ($_SESSION['admin'] != "true") { header("location: login.php");} else { ?> ### code for the rest of the page ### I am fairly new to all this and cant understand why its remaining on the login page and not sending me to admin.php when the password and username are correct. Is this the correct way to be going about it? I envisaged simply adding the above code to the top of any page only the admin could see. Any help is much appreciated. Hoping someone can help. I have a file, say bounce.php that uses php url ramdomizer, like this: <?php $urls = array("link1", "link2"); $url = $urls[array_rand($urls)]; header("Location: http://$url"); ?> What I want is to only allow that code to execute if the user is coming from another php page on the same sever/folder. So like this.... So bounce.php will check where the traffic is coming from.....if traffic is coming from page1.php (file on same server) then it will allow URL REDIRECT CODE to execute, if traffic is coming from another source, such as google.com, or from no referel, then person is sent to another site, say msn.com. This topic has been moved to mod_rewrite. http://www.phpfreaks.com/forums/index.php?topic=315834.0 Hello. I have a quick question. In my database I have Business's and members. I want the business to be able to advertise to members in their local area (lets say within 30 miles) for a cost. When a member within that distance of the office logs on they see this advert. Outside this distance they do not. Obviously the best way to do this is by postcode of the business compared to the member. I'm basically after some advise as I have been all over the internet looking for answers. First of all is it possible to write this script and what type of functions do I need to learn to do this? Second of all does anybody know of software that can do this out there already? I have found some but they are actual written programs with their own GUI that can not be changed to suit my needs. Thank you Hi, I have this code but i cant get it to work. I have broken it down to sections and I think the get file contents may be at fault as when i dump the array it come back bool false. The URL creates a page with CSV values of longitude and latitude from a postcode. I want to give the variables $custlat1 and $custlong1 the values from the geocoded co-ordinates. The CSV values returned from the URL input are 200,5,54.1202442,-3.2078272 Code: [Select] $pc1 = 'http://maps.google.com/maps/geo?q=la139hu,+UK&output=csv&sensor=false&key=ABQIAAAAcclaxnepdvvxx5D2PAnHtRSLcuoGw6G6HnB4VN4WqoMz7tmtKhTHGV82iKKTXvAg7YFpCFA6ptRc9g'; $data1 = @file_get_contents($pc1); $result1 = explode(",", $data1); $custlat1 = $result1[2]; $custlong1 = $result1[3]; can anyone help? or point me in the right direction Hi I have a function that takes a postcode and splits it so i can enter into DB into two formats, full postcode and prefix. The function is: function check_form_postcode($postcode) { $postcode = strtoupper(str_replace(chr(32),'',$postcode)); $suffix = substr($postcode,-3,3); $prefix = substr($postcode,0,(strlen($postcode)-3)); if (preg_match('/(^[A-Z]{1,2}[0-9]{1,2}|^[A-Z]{1,2}[0-9]{1}[A-Z]{1})$/',$prefix) && preg_match('/^[0-9]{1}[ABD-HJLNP-UW-Z]{2}$/',$suffix)) { $postcode_syntax_check = 1; } else { $postcode_syntax_check = 0; } if($postcode_syntax_check){ $return = $prefix."::".$suffix; } return($return); } I POST the form data and in the top of the same page I get all of the form data and here is is where things go wrong: if ($b == 'go') { //Gets form data $main_event_name = my_import('main_event_name', 'P', 'TXT'); $main_event_type = my_import('main_event_type', 'P', 'TXT'); $main_event_date = my_import('main_event_date', 'P', 'TXT'); $main_event_city = my_import('main_event_city', 'P', 'TXT'); $postcode = my_import('postcode', 'P', 'TXT'); $main_event_added = my_import('main_event_added', 'P', 'INT'); $main_event_active = my_import('main_event_active', 'P', 'INT'); $postcode_array = check_form_postcode($postcode); $postcode = explode($postcode_array, "::"); $prefix = $postcode[0]; $fullpostcode = $postcode[0]." ".$postcode[1]; $valkey = md5(microtime()); $info = array( "main_event_name"=> $main_event_name, "main_event_type" => $main_event_type, "main_event_date" => $main_event_date, "main_event_city" => $main_event_city, "main_event_active" => $main_event_active, "main_event_added" => $sys['now'], "main_event_pcode" => $fullpostcode, "main_event_pcode_prefix" => $prefix, "eo_id" => $eo['id'] ); $table = $db['main_event']; $userid = my_insert($info, $table); When I enter into the DB all I get is the "::" no data. I know that the POST works as I can enter the data easily without the function going wrong. Thanks for any help, i am new to arrays go easy if I have made an obvious mistake! Cheers... Hi Guys I need a PHP function to which I pass two postcodes and it works out the road distance, I dont mind using google or any other API I have managed to fing JS ways and php functions using crow route but I really really need a traffic distance in PHP Please advice, Help Thank you quick questions.. i have this code echo '<p>message of error</p>'; echo"<script type='text/javascript'> window.location='index.php'</script>"; and i want to know how could i delay the redirect to index.php for about 5 seconds or so? i've found how to do it using header(); but I've used that before and have gotten alot of errors, which is why i use on javascript to do it for me. i'm trying to use this code to detect if the browser of the user is IE (any version) and id true (if it is IE), then it's redirected to an error page; otherwise, it's ok and sent ot the index. I get the following error... Warning: Cannot modify header information - headers already sent by (output started at /index.php:1) in /xie.php on line 13 any ideas.. ??? <?php function ae_detect_ie() { if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)) return true; else return false; } if (ae_detect_ie()) { header("Location: error.php"); } else { header("Location: index.php"); } ?> Hey guys, I am not a coder at all and would love a little bit of help with my code not working. Basically, I have a redirect script that sends my visitors to a software download. I want to be able to track a snippet from the incoming refer and send it along with the download. I hope I am explaining this correctly. Here is my code: <?php $tid = $_GET["tid"]; header( 'Location: http://www.liutilities.com/affcb/?id=RBgendtd&aff=14231&xat=WU-<?php echo $tid; ?>' ); ?> The page that sends them to this script automatically adds ?tid={keyword here}. What the above script is supposed to do is grab tid and then put it after the &xat=WU- but instead, its only putting the actual code itself (&xat=WU-<?php echo $tid; ?>). Can anyone offer a suggestion? Thanks so much! Hi I've been working on a site for 6 months and have used the header command to redirect loads and loads of times. But i just noticed some crazy behaviour today. Heres a test page: <?php include("includes/db_connect.php"); header('location:stores.php'); $sql = "insert into test (id) values (77)"; $result = mysql_query($sql); ?> when i hit this page, i get redirected to stores.php, but the sql gets executed! Is this supposed to be the behaviour? Have i completely missed the point of header(location:)?? Im baffled as i've used this before, but only now noticed this crazy behaviour! Code: [Select] <form action="checkbox-form.php" method="post"> <input type="checkbox" name="c1" value="1" /> Pending <input type="checkbox" name="c1" value="2" /> Approved <input type="checkbox" name="c1" value="3" /> Rejected <input type="button" name="formSubmit" value="Fetch Results"/> </form> <?php $con = mysql_connect("localhost","root","password"); if (!$con) { die('Could not connect:' . mysql_error()); } mysql_select_db("Products", $con); $result = mysql_query("SELECT * FROM btp_reviews" ); echo "<table border='1' cellspacing='0' cellpadding='0'>"; echo '<tr> <td>Id</td> <td>Review</td> <td>Name</td> <td>Update</td> <td>Status</td> </tr>'; while($row = mysql_fetch_assoc($result)) { echo '<tr>'; echo '<td>' . $row['id'] . '</td>'; echo "<td>" . strip_tags($row['review']) . "</td>"; echo "<td>" . $row['r_name'] . "</td>"; echo "<td>" ."<form action='radio.php' method='post' ><a href=http://localhost/editt.php?id=".$row['id'].">Edit</a>.</td> <td>" ."<input type='radio' name='r1' value='2' />Approve<br/><input type=hidden name=id value='".$row['id']."' /> <input type='radio' name='r1' value='3' /> Reject<br/> <input type=submit value=Submit /></form>"."</td>"; } echo "</table>"; mysql_close($con); ?> |