PHP process ram and cpu usage (windows) - windows

I making a webadmin system and I want to monitor the CPU and RAM usage of a process in PHP
Can anyone help me?

"Counters and Logs to Monitor" => http://support.microsoft.com/kb/300504
Save as CSV and read it() by PHP
[OR]
http://pecl.php.net/package/win32ps
[OR]
Use WMI:
<?PHP
#error_reporting(1);
$wmi = new COM("WinMgmts:{impersonationLevel=impersonate}") ;
$cpus = $wmi->ExecQuery("SELECT LoadPercentage FROM Win32_Processor");
foreach ($cpus as $cpu) :
echo $cpu->LoadPercentage . '%';
endforeach;
?>

Use this it works perfectly. Combine this with AJAX and a JAVASCRIPT timer so you get every xy seconds the usage of your cpu&ram.
function get_server_cpu_usage(){
$load = sys_getloadavg();
return $load[0];
}
function get_server_memory_usage(){
$free = shell_exec('free');
$free = (string)trim($free);
$free_arr = explode("\n", $free);
$mem = explode(" ", $free_arr[1]);
$mem = array_filter($mem);
$mem = array_merge($mem);
$memory_usage = $mem[2]/$mem[1]*100;
return $memory_usage;
}
echo '<h4>Server Memory usage: ' . number_format(get_server_memory_usage(), 2) . '%</h4><span style="width:' . get_server_memory_usage() . '%"></span<br>
<h4>Server CPU usage: ' . get_server_cpu_usage() . '% </h4><span style="width:' . get_server_cpu_usage() . '%"></span>';

Related

PHP: eval don't have value

I stored a Controller#Action in the database, but when I try to run it it don't has value.
I know that eval is very dangerous. If there is an alternative what I can use in this situation I'm open for it.
My code where I wan't to run it:
//$action = "ExchangeController::module_getAllValutaByBank";
//$params = "K&H";
$test = eval('\App\Http\Controllers\ModuleControllers' . "\\" . $action . "('" . $params . "');");
Debugbar::info($test);
The code what I want to eval:
It's an API request to the local ForexChange site. #param bank's name
#return stuctured string
public static function module_getAllValutaByBank($bankName){
$return = '';
$data['bankName'] = $bankName;
$response = self::getRequest($data);
if(is_array($response)){
$return .= $response[0]['bank'] . "\n";
foreach($response as $key => $item){
$return .= $item['valuta'] . " - " . round($item['buy'], 2) . " - " . round($item['sell'], 2) . "\n";
}
} else {
$return = $response;
}
Debugbar::info($return);
return $return;
}
Output of Debugbar::info($return);
K&H Bank GBP - 338.51 - 363.07 AUD - 189.9 - 207.8 DKK - 39.75 - 43.93
JPY - 2.26 - 2.48 CAD - 188.73 - 206.51 NOK - 30.92 - 34.18 CHF -
256.89 - 275.53 SEK - 29.18 - 32.26 USD - 246.14 - 260.32 CZK - 11.51 - 12.97 PLN - 69.87 - 78.79 EUR - 302.92 - 320.38 HRK - 39.39 - 44.41
Output of Debugbar::info($test);
null
Where it went wrong?
EDIT:
Found the solution:
$test = call_user_func('\App\Http\Controllers\ModuleControllers' . "\\" . $action, $params));
Found the solution:
$test = call_user_func('\App\Http\Controllers\ModuleControllers' . "\\" . $action, $params));

Php Generate random number without repeat

$C = $_POST['Cc'];
$X = $_POST['X'];
$CX = $_POST['Cc'] . $_POST['X'];
$NC = preg_replace_callback("/x/" ,function() {return rand(0,9);}, $CX);
$New = $NC ;
$NNew = str_repeat($New,10);
echo $NNew;
what's wrong when i output it , it gives me the same number How to make It Don't Give me the same Numbers ??
It's basically you are not changing the seed for the rand method. Each time it's getting same seed and generating same number.
Read this PHP manual : http://php.net/manual/en/function.srand.php
Check the code snippet below:
<?php
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return $sec + $usec * 1000000;
}
srand(make_seed());
$randval = rand(0,9);
echo $randval;
?>
Or you can use mt_rand() which is seeded differently on each execution.

Commission Junction Simple Pixel Magento

Let me start by saying I am NOT a programmer. I'm a retail web manager that knows enough about HTML5 to understand what is going on. Ok now on to my issue. We recently upgraded our eCommerce platform from 3DCart to Magento. It's a completely different monster and I'm fairly lost. I'm trying to integrate Magento's simple pixel (just returns the total not the individual items) into our confirmation page but all of our tests are failing. I've tried bits and pieces of other codes that I've found around the web but I'm still missing the "amount" parameter. Can anyone help me? Below is what we have on our site now (please note this is part of the copy/paste code I've found):
//-------------------------------------------
// START CJ CONVERSION TRACKING PIXEL
//-------------------------------------------
$cjmerchID = '1521251';
$cjaid = '382643';
$cjorder = Mage::getModel('sales/order')->loadByIncrementId(Mage::getSingleton('checkout/session')->getLastRealOrderId());
$cjitems = $cjorder->getAllItems();
$cjorderID = $cjorder->getIncrementId();
//$cjsubtotal = round($cjorder->getSubtotal(), 2);
$i = 1;
foreach ($cjitems as $itemId => $item)
{
$unitPrice = round($item->getPrice(), 2);
$sku = $item->getSku();
$qty = $item->getQtyToInvoice();
//echo $qty . '<br>';
$itemsStr .= '&ITEM;' . $i . '=' . $sku . '&AMT;' . $i . '=' . $unitPrice . '&QTY;' . $i . '=' . $qty . '';
$i++;
}
?>
?<img src="https://www.emjcd.com/u?CID=<?php echo $cjmerchID; ?>&OID;=<?php echo $cjorderID; ?>&TYPE;=<?php echo $cjaid; ?><?php echo $itemsStr; ?>&CURRENCY;=USD&METHOD;=IMG" height="1" width="20">
<?php
//-------------------------------------------
// END CJ CONVERSION TRACKING PIXEL
//-------------------------------------------
According to CJ this is what I'm doing wrong:
Thank you for providing the results of your test. I am seeing the pixel calls on our server. However, both tests failed as the incorrect Action ID is being used and the 'AMOUNT' parameter has no associated value and is being passed back blank. I've attached the integration instructions for your convenience.
The Action ID for the simple action that should be integrated to replace the existing pixel is 382643.
Integration Test
Advertiser: 3448671
Ad: 12313358
Action Id: 346589
Action Type: item_sale
Query String: AMOUNT=&OID=100056687&CID=1521251&CURRENCY=USD&METHOD=IMG&TYPE=346589
Sid: TrackingTest
Surfer: 476602316150531682:VJXkXAhFHzU2 Click Ref:
Action Status: active
img src="https://www.emjcd.com/u?AMOUNT=&CID=1521251&OID=100056687&TYPE=346589&CURRENCY=USD&METHOD=IMG" height="1" width="20"
Please update the pixel to pull in the subtotal (pre-taxed amount of purchase) and to have 'TYPE' populated with 382643.
Any help you can give would me most appreciated!
Diana
See if this code works. what i did is get the subtotal of total checkout order and append a new parameter in img href with AMOUNT. Let me know how the results work out
//-------------------------------------------
// START CJ CONVERSION TRACKING PIXEL
//-------------------------------------------
$cjmerchID = '1521251';
$cjaid = '382643';
$cjorder = Mage::getModel('sales/order')->loadByIncrementId(Mage::getSingleton('checkout/session')->getLastRealOrderId());
$cjitems = $cjorder->getAllItems();
$cjorderID = $cjorder->getIncrementId();
//New Codee
$totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
$subtotal = $totals["subtotal"]->getValue();
//$cjsubtotal = round($cjorder->getSubtotal(), 2);
$i = 1;
foreach ($cjitems as $itemId => $item)
{
$unitPrice = round($item->getPrice(), 2);
$sku = $item->getSku();
$qty = $item->getQtyToInvoice();
//echo $qty . '<br>';
$itemsStr .= '&ITEM;' . $i . '=' . $sku . '&AMT;' . $i . '=' . $unitPrice . '&QTY;' . $i . '=' . $qty . '';
$i++;
}
?>
?<img src="https://www.emjcd.com/u?CID=<?php echo $cjmerchID; ?>&OID;=<?php echo $cjorderID; ?>&TYPE;=<?php echo $cjaid; ?>&AMOUNT;=<?php echo $subtotal; ?><?php echo $itemsStr; ?>&CURRENCY;=USD&METHOD;=IMG" height="1" width="20">
<?php
//-------------------------------------------
// END CJ CONVERSION TRACKING PIXEL
//-------------------------------------------

mysql syntax error: mysql not allowing certain characters to be processed

Am one step away from reading from a file and writing the data to a table in my database. Everything works correctly except when writing to the table in my database. This is the error message i get:
could not load. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'm not following you so that I can follow you back ♡ )')' at line 1
This is my code:
$sql = mysql_connect("localhost", "root","root");
mysql_select_db("Tweet_Corpora");
if(!$sql){
die("could not connect: " . mysql_error());
}
$file = fopen("/Applications/MAMP/bin/mamp/uploads/corpus/set_2.txt","r") or exit("Unable to open file!");
while(!feof($file)){
$string = fgets($file);
$arr = (explode("\t", $string));
$test = "INSERT INTO Display (tweet_id, raw_tweet) VALUES ('mysql_real_escape_string($arr[0])','mysql_real_escape_string($arr[1])')";
$result = mysql_query($test);
if(!$result){
die("could not load. " . mysql_error());
}
}
What do i do? please help. Thank you in advance.
Here is the working code with a bit of twist:
$sql = mysql_connect("localhost", "root","root");
mysql_select_db("Tweet_Corpora");
if(!$sql){
die("could not connect: " . mysql_error());
}
$file = fopen("/Applications/MAMP/bin/mamp/uploads/corpus/set_2.txt","r") or exit("Unable to open file!");
while(!feof($file)){
$string = fgets($file);
$arr = (explode("\t", $string));
$idd= mysql_real_escape_string($arr[0]);
$tweet=mysql_real_escape_string($arr[1]);
$test = "INSERT INTO Display (tweet_id, raw_tweet) VALUES ('".$idd."','".$tweet."')";
$result = mysql_query($test);
if(!$result){
die("could not load. " . mysql_error());
}
}

Simultaneous AJAX calls during HTTP streaming

I have an Apache server running a web application. In this webapplication I show a video using JWPlayer. JWPlayer uses http pseudostreaming to fetch the video from a PHP script which serves up this video. All this works well and the video is streamed well.
The problem I am having is while the video is streaming I also use AJAX calls to fetch some XML files which are used by Adobe Flash files on the same page. While streaming these XML file fetches are kept 'pending' until the entire video is loaded. Using Chrome I can see that the video gets loaded byte by byte. When the video is entirely loaded, then the XML files are fetched. Also if I open another tab in my browser while a video is streaming and try to load the web application again, it will also not show until the video is entirely loaded.
This seems te be an Apache setting of some sort. The MPM settings for apache are:
ThreadsPerChild 150
MaxRequestsPerChild 0
This seems to be correct. Any ideas what could be wrong?
If you are using PHP sessions then this is probably what is causing the IO blocking.
php blocking when calling the same file concurrently
I was making a system with private video streaming. So, i was needing a streaming via php, because using php programming i was able to restringe user access.
I was having troubles to streaming video and execute other script on the server.
Using the session_write_close() solve the problem to open another scripts and i found that script on web that helps me sooooo much.
I want to share, because that script makes a real streaming.
I found it on http://www.tuxxin.com/php-mp4-streaming/ website.
All thanks to the author of this code =D
ENJOY !
<?php
$file = 'video360p.mp4';
$fp = #fopen($file, 'rb');
$size = filesize($file); // File size
$length = $size; // Content length
$start = 0; // Start byte
$end = $size - 1; // End byte
header('Content-type: video/mp4');
//header("Accept-Ranges: 0-$length");
header("Accept-Ranges: bytes");
if (isset($_SERVER['HTTP_RANGE'])) {
$c_start = $start;
$c_end = $end;
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if (strpos($range, ',') !== false) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
if ($range == '-') {
$c_start = $size - substr($range, 1);
}else{
$range = explode('-', $range);
$c_start = $range[0];
$c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
}
$c_end = ($c_end > $end) ? $end : $c_end;
if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
$start = $c_start;
$end = $c_end;
$length = $end - $start + 1;
fseek($fp, $start);
header('HTTP/1.1 206 Partial Content');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);
$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {
if ($p + $buffer > $end) {
$buffer = $end - $p + 1;
}
set_time_limit(0);
echo fread($fp, $buffer);
flush();
}
fclose($fp);
exit();
?>

Resources