помогите разобраться в скрипте PHP

seosniks
На сайте с 13.08.2007
Offline
389
689

Добрый вечер.

Есть такой код.


$output_dir = "/var/openweathermap.org/";
$weather_type = "current";
$output_location = "[OUTPUT LOCATION]";
$location_city = "[CITY]";
$weather_provider = "http://api.openweathermap.org";
$weather_key = "[APP KEY]";
$weather_query = "/data/2.5/weather?q=" . $output_location . "&units=metric&mode=json&APPID=" . $weather_key;
$weather_file = "current.json";

date_default_timezone_set('Europe/Dublin');

if ( $argc != 3 ){
echo("Error: Two arguments expected. Found " . ($argc -1 ) . "\n");
echo($argv[0] . " <type> <location>\n");
echo("Values for <type> are current, forecast5 and forecast16\n");
echo("Values for <location> contain a country code separated by city\n");
echo("e.g. " . $argv[0] . " \"current\" \"IE/Luimneach\"" . "\n");
echo($argv[0]);
exit(1);
}else{
$weather_type = $argv[1];
$location_holder = split('/', $argv[2]);
$location_city = $location_holder[1];
$output_location = "/" . $argv[2] . "/";
}
if(!is_dir($output_dir . $weather_type . $output_location)){
mkdir($output_dir . $weather_type . $output_location, 0644, true);
}

не понятно условие в конструкции.

if ( $argc != 3 ){

получается что else{ не сможет выполниться.

Или я чего то не понимаю.

Подскажите пожалуйста. Не могу понять что я не так настроил.

Error: Two arguments expected. Found -1 Values for are current, forecast5 and forecast16 Values for contain a country code separated by city e.g. "current" "IE/Luimneach"

у меня указано так

$output_dir = "openweathermap-master/";

$weather_type = "current/";

$output_location = "US/Washington";

$location_city = "41.299179/-91.692940";

$weather_provider = "http://api.openweathermap.org";

$weather_key = "тут api key";

$weather_query = "/data/2.5/weather?q=" . $output_location . "&units=metric&mode=json&APPID=" . $weather_key;

$weather_file = "current.json";

veleg
На сайте с 30.01.2011
Offline
142
#1

Ну если не равен трем то выполняется условие, в противном случае выполняется условие после else (то есть если args ==3)

Фигачу Телеграм-ботов ( https://teleg.run/veleg )
O9
На сайте с 03.05.2016
Offline
38
#2

Дело не только в настройке.

Данный скрипт ожидает 2 параметра при запуске. Причем это параметры командной строки (т. е. скрит - не для запуска через протокол HTTP).

Запуск должен быть вроде такого: `php myscript.php arg1 arg2`

Параметры, судя по коду, `weather_type` и `location`.`weather_type` - одно из: "current", "forecast5" и "forecast16". `location` должен быть в формате код "страны/город", к примеру, `US/Washington`

Попробуйте запустить вот так:

php myscript.php "current" "US/Washington"

По идее должно сработать.

S
На сайте с 30.09.2016
Offline
469
#3

Условие означает, что должно быть задано два аргумента - не больше и не меньше. Вы скрипт вообще из командной строки запускаете?

Отпилю лишнее, прикручу нужное, выправлю кривое. Вытравлю вредителей.
seosniks
На сайте с 13.08.2007
Offline
389
#4
Sitealert:
Условие означает, что должно быть задано два аргумента - не больше и не меньше. Вы скрипт вообще из командной строки запускаете?

Все выкинул так работает


date_default_timezone_set('Europe/Dublin');
if(!is_dir($output_dir . $weather_type . $output_location)){
mkdir($output_dir . $weather_type . $output_location, 0644, true);
}
$ch = curl_init($weather_provider . $weather_query);
$filename = date("Y-m-d-H-i").'.'.$rashirenie;
$filepath = $output_dir . $weather_type . $output_location;
$fp = fopen($filepath . $filename,"w");
curl_setopt($ch, CURLOPT_FILE, $fp); // File to write output to
curl_setopt($ch, CURLOPT_HEADER, 0); // Include or suppress header
curl_exec($ch); // выполняем запрос curl

if(curl_errno($ch)){
echo "Error: " . curl_error($ch);
}
curl_close($ch);
fclose($fp);

На счет условия я понял, только переменная как работает? Откуда она должна брать данные?

Ведь $argc нигде не объявлена и отсутствует еще где либо.

Вот весь листинг скрипта


$output_dir = "/var/openweathermap.org/";
$weather_type = "current";
$output_location = "[OUTPUT LOCATION]";
$location_city = "[CITY]";
$weather_provider = "http://api.openweathermap.org";
$weather_key = "[APP KEY]";
$weather_query = "/data/2.5/weather?q=" . $output_location . "&units=metric&mode=json&APPID=" . $weather_key;
$weather_file = "current.json";

date_default_timezone_set('Europe/Dublin');

if ( $argc != 3 ){
echo("Error: Two arguments expected. Found " . ($argc -1 ) . "\n");
echo($argv[0] . " <type> <location>\n");
echo("Values for <type> are current, forecast5 and forecast16\n");
echo("Values for <location> contain a country code separated by city\n");
echo("e.g. " . $argv[0] . " \"current\" \"IE/Luimneach\"" . "\n");
echo($argv[0]);
exit(1);
}else{
$weather_type = $argv[1];
$location_holder = split('/', $argv[2]);
$location_city = $location_holder[1];
$output_location = "/" . $argv[2] . "/";
}
if(!is_dir($output_dir . $weather_type . $output_location)){
mkdir($output_dir . $weather_type . $output_location, 0644, true);
}

switch ($weather_type){
case "current":
$weather_query = "/data/2.5/weather?q=" . $location_city . "&units=metric&mode=json&APPID=" . $weather_key;
$weather_file = "current.json";
break;
case "forecast5":
$weather_query = "/data/2.5/forecast?q=" . $location_city . "&units=metric&mode=json&APPID=" . $weather_key;
$weather_file = "forecast5.json";
break;
case "forecast16":
$weather_query = "/data/2.5/forecast/daily?q=" . $location_city . "&units=metric&mode=json&cnt=16&APPID=" . $weather_key;
$weather_file = "forecast16.json";
break;
}

echo("Query: " . $weather_query . "\n");
$ch = curl_init($weather_provider . $weather_query);
$filename = date("Y-m-d-H:i") . ".json";
$filepath = $output_dir . $weather_type . $output_location;
$fp = fopen($filepath . $filename,"w");

curl_setopt($ch, CURLOPT_FILE, $fp); // File to write output to
curl_setopt($ch, CURLOPT_HEADER, 0); // Include or suppress header
curl_exec($ch);

if(curl_errno($ch)){
echo "Error: " . curl_error($ch);
}
curl_close($ch);

fclose($fp);

if(filesize($filepath . $filename) > 100){
unlink($filepath . "current.json");
symlink($filepath . $filename, $filepath . "current.json");
}else{
unlink($filepath . $filename);
}

?>
O9
На сайте с 03.05.2016
Offline
38
#5
Ведь $argc нигде не объявлена и отсутствует еще где либо.

`$argc` и `$argv` не нужно объявлять - это предопределенные переменные, см. тут: http://php.net/manual/ru/reserved.variables.php Эти переменные создает сам движок автоматически.

S
На сайте с 30.09.2016
Offline
469
#6
seosniks:
$argc нигде не объявлена и отсутствует еще где либо

Блин... Не буду цитировать и занимать здесь место. Почитайте здесь. Короче, $argc - это количество аргументов+1 (т.е. + название скрипта) из командной строки. А если хотите запускать без командной строки и определять аргументы иным образом - надо скрипт переделывать.

Гы... Чё-то мы тупим по полчаса, а потом одновременно отвечаем... :) Всё, я ушёл. :)

Авторизуйтесь или зарегистрируйтесь, чтобы оставить комментарий