douyou7878 2014-08-09 20:37
浏览 88
已采纳

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

I can't find a way for the if statement in the checkText function, to check if the city is invalid, Example:

If you typed "jfeaio" or any other text that doesn't match a city name then it would say "Enter a valid city".

I made a if statement in the function which checks if the input text is "notkoko", if it is then it is going to echo "Enter a valid city" just to test, and it seems to work, but i want it to say that whenever you type something that isn't a city name or a country name.

I've tried a 2 things like:

Using get_headers, Checking if the file() is false.

The 2 things did work but, then the error would pop up no matter what, like if i typed a valid city name or not.

This is the website

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

Here's the code for both files if you don't want to visit the link

scraper.php(This one is what contains all the 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);

?>

and here's the index.php(This one doesn't contain any 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>

Thanks :-)

  • 写回答

3条回答 默认 最新

  • douluchuo0801 2014-08-09 21:03
    关注

    get_headers will return you an array of headers. In element [0] you will find the return code:

    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
    

    It only returns false if the request fails, e.g. no response from the server. So you have to change the if($headers == false) to something different.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路