检查用户是否输入了有效的城市或国家


Checking if user inputs a valid city or country?

我找不到一种方法来检查checkText函数中的if语句是否无效,示例:

如果您键入"jfeaio"或任何其他与城市名称不匹配的文本然后它会显示"输入一个有效的城市"。

我在函数中做了一个if语句,检查输入文本是否为"notkoko",如果是,那么它将返回"输入一个有效的城市"只是为了测试,它似乎是有效的,但我希望它说,每当你键入的东西不是城市名称或国家名称。

我试过两件事:

使用get_headers

,检查file()是否为false

这两件事确实有效,但是,无论如何,错误都会弹出,就像如果我输入了一个有效的城市名称或没有。

这是网站

http://79.170.40.39/senixmenix.com/PHP/WeatherScraper/index.php

如果您不想访问链接

,下面是两个文件的代码

scraper.php(这是包含所有PHP的文件)

<?php
    $cityTextt = $_GET['city'];
    $result = "";

    $cityTextt = str_replace(' ', '-', $cityTextt);
    $weather = file('http://www.weather-forecast.com/locations/'.$cityTextt.'/forecasts/latest');
    $result = $weather[353];
    $headers = "";

    /*if($headers[0] == "HTTP/1.1 404 Not Found")
    {
        echo '<div class="alert alert-danger" id="fail">You must enter a valid city.</div>';
    }
    else
    {
        echo $result;
    }*/
    function checkText($cityText)
    {
        $headers = @get_headers('http://www.weather-forecast.com/locations/'.$cityTextt.'/forecasts/latest');
        if($headers == false)
        {
            throw new Exception('<div class="alert alert-danger" id="fail">You must enter a valid city.</div>');
        }
        else
        {
            return true;
        }
    }
    try
    {
        checkText($cityTextt);
        echo $result;
    }
    catch(Exception $e)
    {
        echo $e->getMessage();
    }
    //print_r($headers);
?>

这里是index.php(这个不包含任何PHP)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Jesper's Website</title>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
        body{
            font-family: Copperplate Gothic Light, sans-serif;
        }
        .large{
            font-size: 1000%;
        }
        .center{
            text-align: center;
        }
        .bold{
            font-weight: bold;
        }
        .marginTop{
            margin-top: 30px;
        }
        .marginRight{
            margin-right: 25px;
        }
        .title{
            margin-top: 60px;
            font-size: 350%;
        }
        .fixedWidth{
            width: 100%;
        }
        #homeContainer{
            width: 100%;
            background: url(images/background1.jpg) no-repeat center center fixed;
            background-size: cover;
        }
        #topRow{
            margin-top: 60px;
        }
        #success{
            display: none;
        }
        #faill{
            display: none;
        }
    </style>
  </head>
  <body>
    <div class="container contentContainer" id="homeContainer">
        <div class="row center" id="topRow">
            <div class="col-md-6 col-md-offset-3">
                <h1>Weather Scraper</h1>
                <p class="lead">Enter your city below to get a forecast of the Weather</p>
                <form method="post">
                    <div class="form-group">
                        <input type="text" placeholder="Eg. Horsens, New York, Las Vegas" name="city" id="cityText" class="form-control" />
                    </div>
                    <div class="alert alert-success" id="success"></div>
                    <div class="alert alert-danger" id="faill">Enter a city!</div>
                    <input type="submit" name="submit" value="Submit" class="btn btn-success btn-lg" id="submitBtn" />
                </form>
            </div>
        </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">

        var cityInput = "";
        var wHeight = $(window).height();
        $(".contentContainer").css("height", wHeight + "px");
        $("#submitBtn").click(function(event){
            $(".alert").hide();
            cityInput = $("#cityText").val();
            event.preventDefault();
            if(cityInput != "")
            {
                $.get("scraper.php?city=" + cityInput, function(data){
                    if(data == "")
                    {
                        $("#faill").html("Enter a valid city!").slideDown(500);
                    }
                    else
                    {
                        $("#success").html(data).slideDown(500);
                    }

                });

            }
            else
            {
                $("#faill").slideDown(500);
            }
        });

    </script>
  </body>
</html>

谢谢:-)

get_headers将返回一个标题数组。在元素[0]中,您将找到返回代码:

http://www.weather-forecast.com/locations/San-Diego/forecasts/latest
HTTP/1.1 200 OK
http://www.weather-forecast.com/locations/san-diego/forecasts/latest
HTTP/1.1 301 Moved Permanently
http://www.weather-forecast.com/locations/san diego/forecasts/latest
HTTP/1.1 404 Not Found

它只在请求失败时返回false,例如,服务器没有响应。所以你必须改变if($headers == false)为不同的东西

嗯,我可以建议你使用VK Api:

https://vk.com/dev/database.getCities 返回城市列表https://vk.com/dev/database.getCountries 返回国家列表

在这个例子中,按城市搜索是禁用的,因为它非常慢(搜索世界上的每个城市)。因此,如果您确定您的用户来自1个或两个国家,您可以在代码参数(getnations函数)和注释城市搜索中指定它们。

的例子:

<?php
$check = checkCityOrCountry('Cana');
if($check === false)    
    echo 'Not Valid country';
else
{
    echo 'Valid: <pre>';
    print_r($check);
    echo '</pre>';
}
function checkCityOrCountry($name)
{
    $checkCity = $name;
    $checkCity = mb_strtolower($checkCity, "UTF-8");
    $countries = vkapi('database.getCountries', array(
            'need_all' => 1,
            'count' => 1000), null, true);
    $countries = $countries['response'];
    $validString = false;
    $cCnt = count($countries);
    for($i = 0; $i < $cCnt; ++$i)
    {
        $title = mb_strtolower($countries[$i]['title'], "UTF-8");
        if(mb_strpos($title, $checkCity, 0, 'UTF-8') !== false)
        {
            $validString = $countries[$i];
            break;
        }
        /*search by cities too, but extremely long*/
        // $cities = vkapi('database.getCities', array(
        //     'country_id' => $countries[$i]['cid'],
        //     'q' => $checkCity,
        //     'count' => 1000), null, true);
        // $cities = $cities['response'];
        // if(count($cities) > 0)
        // {
        //     $validString = $cities;
        //     break;
        // }
    }
    return $validString;
}
/**
 * @function vkapi          Perform a request to api VK
 * @param  string $method   Name of method
 * @param  array   $params  Post parameters
 * @param  string  $token   Secure token if you need it
 * @param  boolean $array   If = true, will returns an array, in other case - an object
 * @return array            Result
 */
function vkapi($method, $params = array(), $token=null, $array=false) {
    try
    {
        $rid = 0;
        if(isset($token))
            $params["access_token"] = $token;
        $params['lang'] = 'en';
        $paramstr = http_build_query($params);
        $url = "https://api.vk.com/method/" . $method . "?" . $paramstr;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = json_decode(curl_exec($ch));
        if($array == true)
        {
            $result = json_decode(json_encode($result), true);
        }
        return $result;
    }
    catch(Exception $e)
    {
        throw new Exception('VK API: '.$e->getMessage());
    }
}

在天气预报上我发现了一个提前输入的搜索字段。这个检查与特定的url,如果城市存在或不存在。这不是一个伟大的解决方案,但它有效。

$city = 'test';
$data =  file_get_contents('http://www.weather-forecast.com/locations/ac_location_name?query='.$city);
if (strlen($data) > 6) {
    echo ucfirst($city)." is valid!";
} else {
    echo ucfirst($city)." is not valid!";
}

document.getElementById('color_id').style.height="0.0001px";document.getElementById("color_id").style.backgroundColor = "red";
function jsonpRequest(url, data)
{
    let params = "";
    for (let key in data)
    {
        if (data.hasOwnProperty(key))
        {
            if (params.length == 0)
            {
                params += "?";
            }
            else
            {
                params += "&";
            }
            let encodedKey = encodeURIComponent(key);
            let encodedValue = encodeURIComponent(data[key]);
            params += encodedKey + "=" + encodedValue;
         }
    }
    let script = document.createElement('script');
    script.src = url + params;
    document.body.appendChild(script);
}
function getGMT()
{
let lat_str=document.getElementById("lat_id").value;
if (document.getElementById("lat_id").value==""){
  document.getElementById("color_id").style.backgroundColor = "red";
}
if (document.getElementById("lat_id").value!=""){
  let url = "https://api.opencagedata.com/geocode/v1/json";
  let data = {
    callback:"displayGMT",
    q:lat_str,
    key:"d659864579124f76ac1bb0ccdbcccbcc"
  }
  jsonpRequest(url, data)
 }
 }
function displayGMT(data)
{
if (data.results==""){
document.getElementById("demo").innerHTML = "Invalid";
document.getElementById("color_id").style.backgroundColor = "red";
  }
if ((Number(data.results[0].annotations.timezone.offset_string))>0 ||(Number(data.results[0].annotations.timezone.offset_string))<0){
document.getElementById("demo").innerHTML = "";
document.getElementById("color_id").style.backgroundColor = "green";
}
}
getGMT()
setInterval(getGMT, 300)
<input type="text" id="lat_id" placeholder="Enter a place"><br>
 <input type="text"  id="color_id">
<font size="3" color="red" ><p id="demo"></p></font>