-3

It has been a few months since I've started to learn PHP, I've got thus far, and I whilst I ran into dozens of problems, I have fortunately been able to fix them, but today's the problem, not a duplicate question, is probably different, I've read all the Stack Overflow questions about this matter, but they were of no help.

I am getting the following error:

Notice: Undefined index: city in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 99

This is my code:

<?php

    $weather = "";
    $error = "";

    if ($_GET['city']) {

     $urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=".urlencode($_GET['city']).",uk&appid=Hidden");

        $weatherArray = json_decode($urlContents, true);

        if ($weatherArray['cod'] == 200) {

            $weather = "The weather in ".$_GET['city']." is currently '".$weatherArray['weather'][0]['description']."'. ";

            $tempInCelcius = intval($weatherArray['main']['temp'] - 273);

            $weather .= " The temperature is ".$tempInCelcius."&deg;C and the wind speed is ".$weatherArray['wind']['speed']."m/s.";

        } else {

            $error = "Could not find city - please try again.";

        }

    }
?>

I am also using xampp and php.ini is there too.

Robin Daugherty
  • 7,115
  • 4
  • 45
  • 59
Caplin YT
  • 269
  • 1
  • 5
  • 16

1 Answers1

2

From your code syntax I think you are problem is in the how you are getting the city. Your error indicates that it cannot find the index of city in $_GET; so basically it has not been set. Add a isset check before running the code, that will prevent any errors:

if ( isset($_GET['city']) ) {
    $urlContents = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=".urlencode($_GET['city']).",uk&appid=Hidden");
    //...
}

This will prevent the code to run and avoid any errors; Now check your url to make sure that it contains: https://example.com?city=somecity. That should fix the error.

Sam
  • 2,856
  • 3
  • 18
  • 29