Here's my PHP code for a shell-script:
#!/usr/bin/php -q
<?php
$user = get_current_user();
$line = date("c") . " - " . $user + "\r\n";
echo "---------------------\n";
echo "user => $user\n";
echo "---------------------\n";
echo "date('c') => " . date("c") . "\n";
echo "---------------------\n";
echo "date('Ymd') => " . date("Ymd") . "\n";
echo "---------------------\n";
echo "line => $line\n";
echo "---------------------\n";
echo date("c") . " - " . $user + "\n";
echo "---------------------\n";
echo date("c") . $user + "\n";
echo "---------------------\n";
echo date("c") . " - " . "\n";
echo "---------------------\n";
$ret = file_put_contents("/var/lib/foo/bar/test.txt", $line, FILE_APPEND);
echo "file_put_contents => $ret\n";
?>
When I run it, I get this output:
roffle:/var/lib/foo/bar # php Test.php
---------------------
user => wwwrun
---------------------
date('c') => 2014-07-27T16:39:34-04:00
---------------------
date('Ymd') => 20140727
---------------------
line => 2014
---------------------
2014---------------------
2014---------------------
2014-07-27T16:39:34-04:00 -
---------------------
file_put_contents => 4
roffle:/var/lib/foo/bar #
Why is $line truncated along with the first two calls to echo date("c") and why is the third call to date("c") okay?
Looks like you've just mixed up + with the . for concatenation in the lines in question.
Related
I am trying to compare two strings. When compared they are unequal to the computer. But to the human eye the strings appear to be the same.
When I run a test to check the bin2hex with php they are clearly unequal. Some how a set of double quotes is be read as html. Here are some examples:
$string1 = strlen(html_entity_decode($_SESSION['pageTitleArray'][$b]));
$string2 = strlen(html_entity_decode($value));
echo 'Checking: ' . $_SESSION['pageTitleArray'][$b] . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'testing ' . $string1 . " = "bin2hex($string1) . " " . bin2hex($string2);
echo '<br>';
echo 'With: ' . $value . " " . bin2hex($value);
The code above will out put the following information.
Checking: 1 PAIR OF BBC HEAD GASKET GASKETS MULTI LAYERED STEEL 4.585"
312050414952204f46204242432048454144204741534b4554204741534b455453204d554c5449204c41594552454420535445454c20342e35383522
testing 3630 3632 With: 1 PAIR OF BBC HEAD GASKET GASKETS MULTI
LAYERED STEEL 4.585″
312050414952204f46204242432048454144204741534b4554204741534b455453204d554c5449204c41594552454420535445454c20342e3538352623383234333b
false
I am kinda lost on what to do... Any help would be greatly appreciated. Below is the rest of the code so you can get a total feel for what I'm trying to accomplish.
for($b = 0; $b < count($_SESSION['pageTitleArray']); $b++)
{
foreach($_SESSION['pushIdArrayQuery'] as $key => $value)
{
$string1 = strlen(html_entity_decode($_SESSION['pageTitleArray'][$b]));
$string2 = strlen(html_entity_decode($value));
echo 'Checking: ' . $_SESSION['pageTitleArray'][$b] . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'testing ' . $string1 . " = "bin2hex($string1) . " " . bin2hex($string2);
echo '<br>';
echo 'With: ' . $value . " " . bin2hex($value);
if(trim($_SESSION['pageTitleArray'][$b]) == trim($value))
{
echo '<br>';
echo '<h1>Success</h1>';
echo '<br>';
echo '<b>Key: </b>' . $key;
echo '<br>';
echo 'Page Id: ' . $_SESSION['pushTitleArrayQuery'][$key];
echo '<br> ';
}
else {
echo '<br>';
echo 'false';
echo '<br>';
}
}
}
You have two different types of quotations mark (" on the first string and ″ on the second one).
To human eyes they seems similar but they are complete different characters to PHP.
This is how I fixed the problem. Notice, I removed any html attributes with the html_entity_decode() function. Then, from there I was able to strip away all other special characters by using preg_replace() and compare the results.
//Loop through all the page titles from the directories
for($b = 0; $b < count($_SESSION['pageTitleArray']); $b++)
{
//Loop through the page titles gathered from the database
foreach($_SESSION['pushTitleArrayQuery'] as $key => $value)
{
//use html decode to remove the quotes with ENT_NOQUOTES
$removeHtml = html_entity_decode($value, ENT_NOQUOTES);
//Test to make sure the encoding are the same for both variables.
$detectEncoding = mb_detect_encoding($value, "auto");
//remove all non alphanumeric variables in the first string.
$string1 = preg_replace("/[^a-zA-Z0-9]/", "", $_SESSION['pageTitleArray'][$b]);
//remove all non alphanumeric variables in the second string.
$string2 = preg_replace("/[^a-zA-Z0-9]/", "", $removeHtml);
//Print out to see what the results look like from decode and encoding functions
echo 'Testing the removal of html quotes: ' . $removeHtml . ' Encoding: ' . $detectEncoding;
echo '<br>';
//Show what variables are being compaired.
echo 'Checking: ' . $string1 . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'With: ' . $string2 . " " . bin2hex($value);
//If statement to check if the to strings match.
if(trim($string1) === trim($string2))
{
echo '<br>';
echo '<h1>Success</h1>';
echo '<br>';
echo '<b>Key: </b>' . $key;
echo '<br>';
echo 'Page Title: ' . $_SESSION['pushTitleArrayQuery'][$key];
echo '<br>';
echo 'Page Id: ' . $_SESSION['pushIdArrayQuery'][$key];
echo '<br> ';
}
else {
echo '<br>';
echo 'false';
echo '<br>';
}
echo '<br>';
}
}
I have created a page that asks the user for a date and outputs results from an api. The api requires a start date and end date that can be no more than 7days apart. I have set it up so a user can enter a date and the end date will automatically be set for 7 days later.
I am having issues using the date function, It appears now that the code will automatically use todays date before the user can input their choose.
I want the user to be able to choose there date whether it be todays or a future date, I want my api call to wait for users input but not sure how this can be done.
<?php
$startDate = date('Y-m-d', strtotime(isset($_GET['start'])? $_GET['start'] :date('Y-m-d')));
$endDate = date('Y-m-d', strtotime('+7 days', strtotime($startDate)));
if($startDate){
echo "$endDate";
$params = array(
'start_date' => $startDate,
'end_date' => $endDate,
'api_key' => 'coXJeNygdeuxVKs9yJLecWbfuXsY54Wi9gq37HuN'
);
$data = json_decode(callAPI('GET', 'https://api.nasa.gov/neo/rest/v1/feed', $params));
echo "<h1>Near-Earth Object (NEO) Report between " . $params['start_date'] . " and " . $params['end_date'] . "</h1>";
foreach ($data->near_earth_objects as $date => $count) {
echo "<p>" . sizeof($count) . " objects detected on $date</p>";
echo "<ol>";
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<li>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</a><br>";
echo "Estimated Diameter: " . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . "-" . $near_earth_object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<li>Close approach on " . $close_approach->close_approach_date . " velocity " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul></li>";
}
echo "</ol>";
}
}
?>
It is nearly at what you wanted to begin with. Just need to add an else to the if statement and update the start/end dates to return false when no date is entered. Note: I also moved the header above the if and added a tertiary condition to display the date if it is already entered so that it is always displayed.
<?php
$startDate = isset($_GET['start']) ? date('Y-m-d', strtotime($_GET['start'] )) : false;
$endDate = $startDate ? date('Y-m-d', strtotime('+7 days', strtotime($startDate))) : false;
$params = array(
'start_date' => $startDate,
'end_date' => $endDate,
'api_key' => 'coXJeNygdeuxVKs9yJLecWbfuXsY54Wi9gq37HuN'
);
echo '<h1>Near-Earth Object (NEO) Report',
( $startDate ? ' between ' . $params['start_date'] . ' and ' . $params['end_date'] . '</h1>' : '</h1>');
if($startDate) {
echo "$endDate";
$data = json_decode(callAPI('GET', 'https://api.nasa.gov/neo/rest/v1/feed', $params));
foreach ($data->near_earth_objects as $date => $count) {
echo "<p>" . sizeof($count) . " objects detected on $date</p>";
echo "<ol>";
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<li>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</a><br>";
echo "Estimated Diameter: " . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . "-" . $near_earth_object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<li>Close approach on " . $close_approach->close_approach_date . " velocity " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul></li>";
}
echo "</ol>";
}
} else {
?><form action="" method="GET">
<label for="startdate">Please enter a start date (end date will be 7 days after the start date):</label>
<input id="startdate" type="date" name="start" />
<input type="submit" />
</form><?php
}
How do you get the timezone offset text? For example if I pass in:
America/New_York
...I would like to receive back:
-04:00
I created a function called getTimezoneOffsetText
<?php
function getTimezoneOffsetText($timezone){
date_default_timezone_set( "UTC" );
$daylight_savings_offset_in_seconds = timezone_offset_get(timezone_open($timezone), new DateTime());
$mod = $daylight_savings_offset_in_seconds/60 % 60;
$min = abs($mod);
return sprintf('%+03d', $daylight_savings_offset_in_seconds/60/60) . ':' . sprintf('%02d', $min);
}
$offset1 = 'America/New_York';
$offset2 = 'Asia/Kabul';
$offset3 = 'Asia/Kathmandu';
$offset4 = 'Israel';
$offset5 = 'Greenwich';
$offset6 = 'America/Caracas';
echo '<pre>';
echo $offset1 . ":\t" . getTimezoneOffsetText($offset1) . '<br/>';
echo $offset2 . ":\t\t" . getTimezoneOffsetText($offset2) . '<br/>';
echo $offset3 . ":\t\t" . getTimezoneOffsetText($offset3) . '<br/>';
echo $offset4 . ":\t\t\t" . getTimezoneOffsetText($offset4) . '<br/>';
echo $offset5 . ":\t\t" . getTimezoneOffsetText($offset5) . '<br/>';
echo $offset6 . ":\t" . getTimezoneOffsetText($offset6) . '<br/>';
echo '</pre>';
It generates this data:
America/Caracas: -04:30
Asia/Kabul: +04:30
Asia/Kathmandu: +05:45
Israel: +03:00
Greenwich: +00:00
America/New_York: -04:00
Note that it gets half hour and other "non-standard" timezones such as Caracas, Kabul and Kathmandu. I'm curious though if there is already a function that exists that accomplishes this.
I'm trying to show a list of all nearby weather stations.
I have the code:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string);
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (count($station) > 1)
{
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
}
}
But currently it's not showing anything, i have searched for examples but i couldn't find any solution fot this problem.
Alternatively, you could use a simple foreach to iterate those values. Consider this example:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string, true); // <-- second parameter to TRUE to use it as an array
$desired_values = $parsed_json['location']['nearby_weather_stations']['pws']['station'];
foreach($desired_values as $key => $value) {
echo "<hr/>";
echo "City: " . $value['city'] . "<br/>";
echo "State: " . $value['state'] . "<br/>";
echo "Latitude: " . $value['lat'] . "<br/>";
echo "Longitude: " . $value['lon'] . "<br/>";
echo "<hr/>";
}
Sample Fiddle
This is supposed to return raw values for Rx and Tx for each adapter (output is in pairs) ONLY of the adapter has transferred more than zero data.
<?php
//windows network usage testing
function win_netinfo(){
ob_start();
$wmi = new COM("Winmgmts://");
$nets = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface WHERE BytesSentPersec > 1");
foreach ($nets as $net)
{
$net_txbytes = $net->BytesSentPersec;
$net_rxbytes = $net->BytesReceivedPersec;
if ($net_txbytes < 0) {
$net_txbytes = $net->BytesTotalPersec - $net->BytesReceivedPersec;
}
if ($net_rxbytes < 0) {
$net_rxbytes = $net->BytesTotalPersec - $net->BytesSentPersec;
}
return $net_txbytes . "</br>"; //When it RETURNS it only shows the FIRST value... :/ WHAT DO?
}
}
echo win_netinfo();
?>
Output should be like this:
21936313136
12345163517
13647613
87653467
546254
246247
87653642
24583462
(Every other line is Rx or Tx, for each adapter).
Current code that works:
<?php
# Peport All Errors
error_reporting(E_ALL);
# Create Object
$wmi = new COM("Winmgmts://");
# Get net info
$oss = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface");
# Show net info
foreach($oss as $os)
{
echo "BytesReceivedPerSec: " . $os->BytesReceivedPerSec . "<br />";
echo "BytesSentPerSec: " . $os->BytesSentPerSec . "<br />";
echo "BytesTotalPerSec: " . $os->BytesTotalPerSec . "<br />";
echo "Caption: " . $os->Caption . "<br />";
echo "CurrentBandwidth: " . $os->CurrentBandwidth . "<br />";
echo "Description: " . $os->Description . "<br />";
echo "Frequency_Object: " . $os->Frequency_Object . " kb<br />";
echo "Frequency_PerfTime: " . $os->Frequency_PerfTime . "<br />";
echo "Frequency_Sys100NS: " . $os->Frequency_Sys100NS . "<br />";
echo "Name: " . $os->Name . "<br />";
echo "OutputQueueLength: " . $os->OutputQueueLength . "<br />";
echo "PacketsOutboundDiscarded: " . $os->PacketsOutboundDiscarded . "<br />";
echo "PacketsOutboundErrors: " . $os->PacketsOutboundErrors . "<br />";
echo "PacketsReceivedNonUnicastPerSec: " . $os->PacketsReceivedNonUnicastPerSec . "<br />";
echo "PacketsReceivedPerSec: " . $os->PacketsReceivedPerSec . "<br />";
echo "PacketsReceivedUnicastPerSec: " . $os->PacketsReceivedUnicastPerSec . "<br />";
echo "PacketsReceivedUnknown: " . $os->PacketsReceivedUnknown . "<br />";
echo "PacketsSentNonUnicastPerSec: " . $os->PacketsSentNonUnicastPerSec . "<br />";
echo "PacketsSentPerSec: " . $os->PacketsSentPerSec . "<br />";
echo "PacketsSentUnicastPerSec: " . $os->PacketsSentUnicastPerSec . "<br />";
echo "Timestamp_Object: " . $os->Timestamp_Object . "<br />";
echo "Timestamp_PerfTime: " . $os->Timestamp_PerfTime . "<br />";
echo "Timestamp_Sys100NS: " . $os->Timestamp_Sys100NS . "<br />";
echo "<br /><br /><br />";
}
?>
Your returning after the first iteration hence only 1 result, below is how i would do it by creating an array and returning that instead:
<?php
//windows network usage testing
function win_netinfo(){
$wmi = new COM("Winmgmts://");
$nets = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface WHERE BytesSentPersec > 1");
$return=array();
$i=0;
foreach ($nets as $net){
$return[$i]['name']=$net->Name;
if ($net->BytesSentPersec < 0) {
$return[$i]['net_txbytes'] = $net->BytesTotalPersec - $net->BytesReceivedPersec;
}else{
$return[$i]['net_txbytes'] = $net->BytesSentPersec;
}
if ($net->BytesReceivedPersec < 0) {
$return[$i]['net_rxbytes'] = $net->BytesTotalPersec - $net->BytesSentPersec;
}else{
$return[$i]['net_rxbytes'] = $net->BytesReceivedPersec;
}
$i++;
}
return $return;
}
$adapters=win_netinfo();
/*Array
Array
(
[0] => Array
(
[name] => VirtualBox Host-Only Ethernet Adapter
[net_txbytes] => 5095956
[net_rxbytes] => 0
)
[1] => Array
(
[name] => Belkin 54g Wireless USB Network Adapter
[net_txbytes] => 532337967
[net_rxbytes] => 5252455518
)
)
*/
?>
And to output the array, something like this:
<?php
foreach($adapters as $adapter){
echo '<p>'.$adapter['name'].' - Sent: '.$adapter['net_txbytes'].' bytes - Received: '.$adapter['net_rxbytes'].' bytes</p>';
}
?>