Different PHP script behavior online - php

I have the following problem. I have a script that gets the Airdate of TV Shows and i alter it before I save it to my database. Locally on my localhost it works perfect, but when I tried it online and uploaded it to my web server it shows a different behavior. I have no idea why it is so.
Here are some examples:
The Data I get: Aired 1/22/12
What the outcome of my script should be: 2012-01-22
What I get online: 2022/12--
The Data I get: Aired 8/29/11
What the outcome of my script should be: 2011-08-29
What I get online: 2029/11--
The Data I get: Airs 2/12/12
What the outcome of my script should be: 2012-02-12
What I get online: 2012/12--
Here is my PHP script:
if(strstr($serie['airdate'], 'Airs')) {
$date = substr($serie['airdate'], 5);
}
if(strstr($serie['airdate'], 'Aired')) {
$date = substr($serie['airdate'], 6);
}
$mm = strstr($date, "/", true);
$mmStrLen = strlen($mm);
if((strlen($mm)) == "1") {
$mm = "0".$mm;
}
$dd = substr($date, $mmStrLen+1);
$dd = strstr($dd, "/", true);
$ddStrLen = strlen($dd);
if((strlen($dd)) == "1") {
$dd = "0".$dd;
}
$yy = substr($date, $mmStrLen+1+$ddStrLen+1);
if((strlen($yy)) == "1") {
$yy = "0".$yy;
}
$serie['date'] = "20".$yy."-".$mm."-".$dd;
$serie['airdate'] is the data I get and $serie['date'] is where the altered value should be saved.
The PHP Version I use locally is 5.3.8 and the one of my webhoster is 5.2.17. But I guess this is not the root of the problem.

Can't format a comment as code, so I must write it as an answer.
Please try this on both sides
$x=explode(' ',$serie['airdate']);
if (sizeof($x)!=2) die("Error in step 1");
$x=explode('/',$x[1]);
if (sizeof($x)!=3) die("Error in step 2");
$serie['date']=sprintf("20%02d-%02d-%02d",$x[2],$x[0],$x[1]);

Take a look at the raw date string you are splitting locally vs at the server. I'm willing to bet that the OS date format is different locally than on the server, and your string splitting code is not designed to handle the different format the server is using.

Thats an awful lot of code to handle dates. Have tried using the strtotime() function? You can pair it with the date() function to easily reformat dates in PHP.

Related

Asynchronous API handling with PHP

I have this PHP function that logs the visitors to a .txt file (for security reasons). It uses an API to get their location. It works fine on localhost, but when it's actually live it logs empty values. I'm assuming it's because the functions runs before the API has had time to return the data. Is there a way to write something like a Javascript promise or some asynchronous function that will wait for the data to return before logging it?
This is what I currently have:
function getLocation() {
$query = #unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
$user = $_SERVER['REMOTE_ADDR'].' - '.date("H:i:s d-m-Y").' - '.$query['country'].', '.$query['regionName'].', '.$query['city'].', '.$query['zip'];
$file = '../logs/userlog.txt';
$currentFileData = file_get_contents($file);
$currentFileData .= $user . PHP_EOL;
file_put_contents($file, $currentFileData);
}
}
What the output should be:
127.0.0.1 - 11:59:33 03-04-2020 - South Africa, Western Cape, Cape Town, 8001
What the actual output is:
127.0.0.1 - 11:59:33 03-04-2020 - , , ,
Your help will be greatly appreciated!
You are not passing the IP address as stated in the documentation after the /php/ part of the URL. It should be
$query = #unserialize (file_get_contents('http://ip-api.com/php/' . $_SERVER['REMOTE_ADDR']));
SOLVED: Thanks to #DanielProtopopov's post I actually found on the documentation that this php version of the API has been deprecated. So using #DanielProtopopov's fix I have to use the JSON API for it to work:
$query = json_decode(file_get_contents('http://ip-api.com/json/' . $_SERVER['REMOTE_ADDR']));

Running PHP & Mysqli queries in Parallel

I'm tying to extract data from thousands of premade sql files. I have a script that does what I need using the Mysqli driver in PHP, but it's really slow since it's one sql file at a time. I modified the script to create unique temp database names, which each sql file is loaded into. Data is extracted to an archive database table, then the temp database is dumped. In an effort to speed things up, I created a script structured 4 scripts similar to the one below, where each for loop is stored in it's own unique PHP file (the code below is only for a quick demo of what's going on in 4 separate files), they are setup to grab only 1/4 of the files from the source file folder. All of this works perfectly, the scripts run, there is zero interference with file handling. The issue is that I seem to get almost zero performance boost. Maybe 10 seconds faster :( I quickly refreshed my PHPmyadmin database listing page and could see the 4 different databases loaded at anytime, but I also noticed that it looked like it was still running more or less sequentially as the DB names were changing on the fly. I went the extra step of creating an unique user for each script with it's own connection. No improvement. Can I get this to work with mysqli / PHP or do I need to look into some other options? I'd prefer to do this all in PHP if I can (version 7.0). I tested by running the PHP scripts in my browser. Is that the issue? I haven't written any code to execute them on the command line and set them to the background yet. One last note, all the users in my mysql database have no limits on connections, etc.
$numbers = array('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20');
$numCount = count($numbers);
$a = '0';
$b = '1';
$c = '2';
$d = '3';
$rebuild = array();
echo"<br>";
for($a; $a <= $numCount; $a+=4){
if(array_key_exists($a, $numbers)){
echo $numbers[$a]."<br>";
}
}
echo "<br>";
for($b; $b <= $numCount; $b+=4){
if(array_key_exists($b, $numbers)){
echo $numbers[$b]."<br>";
}
}
echo "<br>";
for($c; $c <= $numCount; $c+=4){
if(array_key_exists($c, $numbers)){
echo $numbers[$c]."<br>";
}
}
echo "<br>";
for($d; $d <= $numCount; $d+=4){
if(array_key_exists($d, $numbers)){
echo $numbers[$d]."<br>";
}
}
Try this:
<?php
class BackgroundTask extends Thread {
public $output;
protected $input;
public function run() {
/* Processing here, use $output for... well... outputting data */
// Here you would implement your for() loops, for example, using $this->input as their data
// Some dumb value to demonstrate
$output = "SOME DATA!";
}
function __construct($input_data) {
$this->input = $input_data;
}
}
// Create instances with different input data
// Each "quarter" will be a quarter of your data, as you're trying to do right now
$job1 = new BackgroundTask($first_quarter);
$job1->start();
$job2 = new BackgroundTask($second_quarter);
$job2->start();
$job3 = new BackgroundTask($third_quarter);
$job3->start();
$job4 = new BackgroundTask($fourth_quarter);
$job4->start();
// ==================
// "join" the first job, i.e. "wait until it's finished"
$job1->join();
echo "First output: " . $job1->output;
$job2->join();
echo "Second output: " . $job2->output;
$job3->join();
echo "Third output: " . $job3->output;
$job4->join();
echo "Fourth output: " . $job4->output;
?>
When using four calls to your own script through HTTP, you're overloading your connections for no useful reason. Instead, you're taking away spaces for other users who may be trying to access your website.

How can I retrieve Unicode characters from IMAP in PHP?

I'm trying to parse an email that is partially written in English and partially written in Japanese using PHP. Here's the code I have so far:
if ($mbox = imap_open($mailbox, $username, $password)) {
$inbox = imap_check($mbox);
$total = (int) $inbox->Nmsgs;
$min = max(1, $total - 10);
// fetch 10 most recent emails
if ($total > 0 && ($emails = imap_fetch_overview($mbox, "{$min}:{$total}"))) {
foreach ($emails as $email) {
$body = imap_body($mbox, $email->uid, FT_UID);
// for testing purposes
echo $body;
// parsing logic here
}
}
}
So as you can see I'm just echoing out the plaintext body of the email, just to test things, and here's part of the echoed response I get when I run this script:
Your Japanese word of the day is: ç”·ã®å­
However, the following is what I should see in place of that, based on what's actually in the email:
Your Japanese word of the day is: 男の子
So clearly something's being lost in translation (pun intended). I'm using some simple string manipulation to try and parse the Japanese characters, and then insert them into a MySQL database. However, it's currently inserting those gobbledygook characters instead. What am I missing?
Edit: I'm using PHP version 5.4.45
So I'm not really sure how to get this working in PHP 5. I decided to try upgrading my server to PHP 7 and suddenly all of the code just started working.

Loop Making PHP output and browser-viewed source code vanish

I recently started coding a script meant for html output that (hopefully) will reduce some busy work at my job. It is a script adapted from a functional script I wrote in python, but I do not think that is the issue.
I have the following code at the start of the php script to identify errors:
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
I have put the program on a server and attempted to run it. My first problem is that partway through the program, it starts dumping the source code (minus HTML tags) to the window partway through an if statement as such:
$moonSet[0]){
$t = 3;
} # Case 4, set time greater than rise time
else {
$t = 4;
}
For reference, the actual section of code interrupted is as such:
# Case 1, no rise time on current date
if ($moonRise[0] == 0){
$t = 1;
} # Case 2, no set time on current/next date
elseif ($moonSet[0] == 0){
$t = 2;
} # Case 3, rise time greater than set time
elseif ($moonRise[0] > $moonSet[0]){
$t = 3;
} # Case 4, set time greater than rise time
else {
$t = 4;
}
I believe the version of php used on the server is at least PHP 5.x, as the source code is dumped to the window when the html coding uses <??> instead of <?php?>. The problem is that when I use <?php?> all the output vanishes--the HTML tags included. Looking at the source code, it only shows a 1 to indicate the first line of code, suggesting that no code is actually in the file. This only happens when I use <?php?> instead of <??>.
I then tried to gradually step through the code to identify why, one, the code suddenly interrupts the if statement, and two, why using <?php?> torches the output.
What I ended up discovering is that the <?php?> code works just fine until I added in a loop. The program uses a MySQL query, and from what I can tell, the query worked just fine. The program executed, output at both the beginning and end of the test code was displayed to screen.
The SQL code is as such:
$connection = mysql_connect("localhost", "webuser", "webuser");
mysql_select_db("dbAstro", $connection);
$queryTides = "SELECT tideDateTime, tideHeight, tideHorL FROM tblTides WHERE DATE(tideDateTime) BETWEEN '$targetDate[0] 00:00:00' AND '$targetDate[2] 23:59:59' ORDER BY tideDateTime";
$querySun = "SELECT sunDate, sunRise, sunSet FROM tblSunRiseSet WHERE DATE(sunDate) BETWEEN '$targetDate[0] 00:00:00' AND '$targetDate[2] 23:59:59' ORDER BY sunDate";
$queryMoon = "SELECT moonDate, moonRise, moonSet FROM tblMoonRiseSet WHERE DATE(moonDate) BETWEEN '$targetDate[0] 00:00:00' AND '$targetDate[2] 23:59:59' ORDER BY moonDate";
$queryTwi = "SELECT twilightDate, twilightBeg, twilightEnd FROM tblCivilTwilight WHERE DATE(twilightDate) BETWEEN '$targetDate[0] 00:00:00' AND '$targetDate[2] 23:59:59' ORDER BY twilightDate";
#Query results stored in separate result locations for later reference.
$resultTi = mysql_query($queryTides, $connection);
$resultSu = mysql_query($querySun, $connection);
$resultMo = mysql_query($queryMoon, $conneciton);
$resultTwi = mysql_query($queryTwi, $connection);
The difference between using the <?php?> and <??> tags so far is that <??> will not display a printf('') command. <?php?> displayed the printf('') command, but with a message that a null value is in the database--which there are some null values in the database.
The problem is when the script enters a loop. Upon putting a loop command, either while or for, the <?php?> script vanishes from both the output and when viewing the source code in a browser. <??> as a tag still outputs the HTML, but does not output any of the php commands--a basic printf('') or an echo command.
I want to stress that it does this with any loop--not just a while loop that searched the SQL queries (the intended goal, shown abbreviated below):
$b = 0;
while ($astroRow = mysql_fetch_assoc($resultTi)) {
$tideTime[$b] = date_format("$astroRow[tideDateTime]", "hi");
$b++;
}
When I attempted to replace the loop with something extremely basic, like this:
for ($a = 0; $a < 2; $a++) {
echo $a;
}
the same pattern occurred. One would start dumping output to screen or show no output from php, and the <?php?> tags would show no code or output whatsoever.
I am at a loss. I do not know what the problem is, and attempting to search help sites has not led me to an answer to my problem. Would anyone have an idea what exactly is going on?

PHP and Windows WMI, CPU Temperature and false readings?

I wrote this PHP function:
<?php
//windows cpu temperature
function win_cpu_temp(){
$wmi = new COM("winmgmts://./root\WMI");
$cpus = $wmi->execquery("SELECT * FROM MSAcpi_ThermalZoneTemperature");
foreach ($cpus as $cpu) {
$cpupre = $cpu->CurrentTemperature;
}
$cpu_temp = ($cpupre/10)-273.15 . ' C';
return $cpu_temp;
}
echo win_cpu_temp();
?>
My problem, is that the script displays 59.55 C which I had thought was correct. I checked this value several hours later, and it's exactly the same. I just put the CPU to work at 90% compressing video for ten minutes, and this value is the same still.
Can anyone help me find the "true" value for this function?
I've read (to no avail):
MSAcpi_ThermalZoneTemperature class not showing actual temperature
How is, say, "Core Temp" getting its values? Same computer, it reports between 49 and 53 Celsius.
With a little digging around I found the common issue with using MSAcpi_ThermalZoneTemperature was that it is dependent upon being implemented on your system.
You could try querying Win32_TemperatureProbe and see if you have any luck there.
Neither MSAcpi_ThermalZoneTemperature or Win32_TemperatureProbe worked on my system, although if you have admin access, you can use http://openhardwaremonitor.org/ which provides a WMI interface for all available sensor data.
This worked great for me and I was able to accurately report CPU Core temp from a PHP script:
function report_cpu_temp(){
$wmi = new COM('winmgmts://./root/OpenHardwareMonitor');
$result = $wmi->ExecQuery("SELECT * FROM Sensor");
foreach($result as $obj){
if($obj->SensorType == 'Temperature' && strpos($obj->Parent, 'cpu') > 0)
echo "$obj->Name ($obj->Value C)"; // output cpu core temp
else
echo 'skipping ' . $obj->Identifier ;
echo '<br />';
}
}
Hope this helps.

Categories