【问题标题】:PHP - ask user input for dates and pass to scriptPHP - 询问用户输入日期并传递给脚本
【发布时间】:2020-06-08 08:58:21
【问题描述】:

我在这里有一个 php 脚本来为我自己在我们的数据中心创建登录名,但是如果我在星期一 12:00 之后运行它,这个脚本将在下周进行登录,而且很多时候我都不在那里整整一周,所以我想通过询问用户输入来改进这个脚本,并传递我将在那里的日期,所以脚本只在这些日期拾取。我知道我必须使用标准输入来执行此操作,并且我确实有一部分有效,但我不知道如何将其集成到当前脚本中以及如何确保我可以提供多个日期

我的标准输入部分确实要求我约会,但不知道如何组合它:

<?php

function promptDateFromUser(string $prompt, string $dateFormat): DateTimeInterface                    
{
    echo "{$prompt} [$dateFormat]: ";

    $stdin = fopen('php://stdin', 'r');
    $line = trim(fgets(STDIN));
    fclose($stdin);
    $dateTime = DateTimeImmutable::createFromFormat('Y-m-d', $line);
    if (! $dateTime instanceof DateTimeInterface) {
        throw new UnexpectedValueException('Invalid datetime format');
    }
}
$dateTime = promptDateFromUser("Please insert date:", 'Y-m-d');
?>

我现在的登录脚本:

<?php
require 'shared.php';
restore_exception_handler();
restore_error_handler();

$md = new RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';

$date  = new DateTime();
$hour = (int)$date->format('H');
$dow  = (int)$date->format('w');
if (($dow === 1 && $hour > 12) || ($dow > 1 && $dow < 6)) {

    $add = 'P' . (8 - $dow) . 'D';
    $date->add(new DateInterval($add));
}

if (($dow === 1 && $hour <= 12) || $dow === 0 || $dow === 6) {
    if ($dow === 6) {
        $date->add(new DateInterval('P2D'));
    } elseif ($dow === 0 ) {
        $date->add(new DateInterval('P1D'));
    }
}

$tomorrow    = $date->format('Y-m-d');

$duration       = 720;
$customerId  = 30;
$purpose       = 'DCG visit';
$phoneNumber = '';

$name                 = 'SOME NAME, REMOVED FOR PUBLICATION';
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");

$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
    $rackSpace = $space;
}

Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
    throw new UserException(ErrorCodes::PERMISSION_DENIED);
}

for ($x = 0; $x < 5; $x++) {
    $start = $tomorrow." 8:00:00";
    $end  = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
    $shouldSms = strlen((string)$phoneNumber) > 0;

    $req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);

    $users = BioAccessUser::getAll();
    foreach ($users as $user) {
        if ($user->name === 'USER NAME') { 
           $req->addBioAccessUser($user, $md);
        }
    }
    $req->request();

    echo "Access requested for: ", $tomorrow, PHP_EOL;
    $date->add(new DateInterval('P1D'));
    $tomorrow = $date->format('Y-m-d');
}
?>

我是一个大的 php 菜鸟,所以非常感谢一些解释!

【问题讨论】:

  • 良好的代码缩进将帮助我们阅读代码,更重要的是,它将帮助您调试代码Take a quick look at a coding standard 为您自己的利益。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。
  • 等等,您有一个无需人工交互即可在系统上启动会话的系统?所以如果你不在那里,会话仍然被创建?请告诉我你不在我的银行工作,否则我将不得不转移我的美元:)

标签: php shell


【解决方案1】:

在朋友的帮助下,我设法解决了这个问题:

#!/usr/bin/env php
<?php

include('shared.php');
restore_exception_handler();
restore_error_handler();

// Constants

$timeout = 45;
$md = new \RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$duration = "720";
$customerId = "30";
$purpose = "DCG visit";
$phoneNumber = "";

$name="SOME NAME, REMOVED FOR PUBLICATION";

// Functions

function requestInput($msg) {
    global $timeout;
    echo "$msg\n\nThe timeout for this selection is $timeout seconds.\n\n> ";
    $fd = fopen('php://stdin', 'r');
    $read = array($fd);
        $write = $except = array(); // we don't care about this
        if(stream_select($read, $write, $except, $timeout)) {
            $choice = trim(fgets($fd));
        }
        echo "\nYou typed: $choice\n\n";
        return $choice;
}

// Start of program

$date = new DateTime();
$weekchoice = (int)requestInput("Which week would you like to request access for?\n1) Current week\n2) Next week\n3) Specific week number");

if ($weekchoice == 3) {
    $weeknumber = (int)requestInput("Please enter a numeric week number");
        } else {
            $weeknumber = (int)$date->format("W");
                if ($weekchoice == 2) {
                $weeknumber += 1;
                }
        }

// We override $date with the start of the chosen week
$date->setISODate($date->format("Y"), $weeknumber);

echo "Thanks, you chose week $weeknumber which starts with " . $date->format("l d F, Y") . " \n\n";

$dayschoice = requestInput("Please enter the days you want access, as a space separated list:\n1) Monday\n2) Tuesday\n3) Wednesday\n4) Thursday\n5) Friday\n\nExample: 1 3 5");

$daylist = explode(' ', $dayschoice);

$processedDays = [];
foreach ($daylist as $eachday) {
    $iday = (int)$eachday;
        if ($iday == 0 || $iday % 7 == 0) { // No Sundays, also (int)"" -> 0, which is terrible
            continue;
        }
        $add_days = $iday - 1; // Sums 0 if Monday, 1 if Tuesday and so on...
        $newdate = new DateTime($date->format("Y-m-d"));
        $newdate->modify("+$add_days days");
        $processedDays[] = $newdate;
        $formatted = $newdate->format("l d F Y");
        echo "Processing day $iday, which is $formatted\n";
}

$hour = $date->format('H');
$tomorrow = $date->format('Y-m-d');

$confirm = requestInput("\nRequest access for these days? Yes/No");
if ($confirm != "Yes") {
    echo 'Good bye!';
        exit(0);
}

foreach ($processedDays as $reqDay) {
    echo "Submitting " . $reqDay->format("l d F Y") . "\n";

    $colo = Colo::getByName($name);
    Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");

    $spaces = $colo->getRackSpaces();
    foreach ($spaces as $space) {
        $rackSpace = $space;
    }

    Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
    if ($colo->getCustomerId() != $customerId) {
            throw new UserException(ErrorCodes::PERMISSION_DENIED);
    }
}

foreach ($processedDays as $reqDay) {
    $start = $reqDay->format('Y-m-d')." 8:00:00";
    $end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
    $shouldSms = strlen((string)$phoneNumber) > 0;
    $req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);

    $users = BioAccessUser::getAll();
    foreach ($users as $user) {
        if ($user->name === 'USER NAME') {
            $req->addBioAccessUser($user, $md);
        }
    }

    $req->request();
    echo "Access requested: ", $reqDay->format('l d F Y'), PHP_EOL;
    $tomorrow = $date->format('Y-m-d');
}

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多