cURL not POSTing to PHP - php

I've been working with PHP + cURL on a fun side project of homemade server monitoring. Right now, I've been trying to use cURL to send POST data to a PHP file with this command:
echo "temp=`sensors | grep 'Core 1' | cut -c9-21 | tr -d ' '`" | curl -s -d #- http://10.0.0.201/statusboard/temp.php
The problem is, it doesn't seem to be posting any data whatsoever
PHP:
<?php
//add your server aliases here
$servers = array(
"10.0.0.201" => "Larry",
"10.0.0.56" => "Le Mac Pro",
);
if(isset( $_POST['temp'], $_POST['df'] )){
preg_match('/\d+\.\d{2}/', $_POST['temp'],$temp);
preg_match('/\d+%/', $_POST['df'],$df);
$stats = array(
"temp" => $temp[0],
"ip" => $_SERVER["REMOTE_ADDR"]
);
save_to_stats($stats);
}else{
output_stats_table();
echo "empty";
echo "<table>";
foreach ($_POST as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
function save_to_stats($stats){
$data = json_decode( file_get_contents("temps.json"), true );
$data[ $stats['ip'] ] = $stats;
file_put_contents("stats.json", json_encode($data), LOCK_EX);
}
function output_stats_table(){
global $servers;
//display data
$data = json_decode( file_get_contents("temps.json"), true );
?>
<table id="projects">
<?php foreach($data as $server => $stats): ?>
<tr>
<td class="server-status" style="width:48px;" ><?php if (time() - (int) $stats['time'] > $timeinsecondstoalert )
{
}
else
{
} ?></td>
<td class="server-name" style="width:200px; text-transform:lowercase;"><?php echo $servers[$stats['ip']] ; ?></td>
<td class="server-load" style="width:72px;"><?php echo $servers[$stats['temp']] ; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php
};
function number_of_bars($df){
$value = (int) str_replace('%', '', $df) / 10;
return round( ($value > 8 ? 8 : $value) * .8 );
}
I am totally mystified as to what the problem is. Without the POST data being made, the JSON file isn't either, therefore no data.

Problem is I do not know the output of the "sensors" program, it might even include some "horrible characters" ;-).
For starters I would first test curl with "easy options":
echo '{"temp": "Hello, world!"}' | curl -X POST -d #- http://10.0.0.201/statusboard/temp.php
please observe the "-X" option and in the receiving php script I would do:
error_log(print_r($_POST,1));
That way you at least know the parameters are correct, including your IP address etc.
Then you can go to the next step with more fancy input options - including piping the output of your program.

Related

how to get cookie values by name from an array

i have a cookie that i stored an array of values inside it. now when i try to access the information by the name of the cookies it keeps giving me the error "ILLEGAL STRING OFFSET". i dont understand what this error means in my situation.
what am i doing wrong?
why cant i access the details with the name of the cookie?
here is my code:
if (isset($_POST['save_details'])) {
if (isset($_COOKIE['historyDetails'])) {
$read_cookie=json_decode($_COOKIE['historyDetails']);
$cookieValue=$read_cookie;
}
$details['totalsalary_cookie'] = $total_salary;
if (isset($extra)) {
foreach($extra as $e){
$details=explode("#",$e);
$name=$details;
$details['extras_cookie']= $name;
}
}
$details['date_cookie']= date("d/m/y");
$details['time_cookie']= date("h:i:sa");
$cookieValue =$details;
setcookie("historyDetails", json_encode($cookieValue), $one_week);
}
echo "<ul>";
echo "<li>Salary details: Total salary is BD $total_salary";
if (count($extra_names)>0) {
echo "<li>Extras:</li>";
echo "<ol type = "."1".">";
for ($i=0; $i <count($extra_names) ; $i++) {
echo "<li>$extra_names[$i]</li>";
} echo "</ol>";
}
echo "</ul>";
die("</body></html>");
}elseif (isset($view_history)) {
//echo $_COOKIE["historyDetails"];
//print_r($_COOKIE);
?>
<table align="center" border="1">
<tr>
<th>Total Salary</th>
<th>Date</th>
<th>Time</th>
<th>Extras</th>
</tr>
<?php
if(isset($_COOKIE["historyDetails"])){
echo "<tr>";
echo "<td align=center>".$_COOKIE["historyDetails"]["totalsalary_cookie"]."</td>";
echo "<td align=center>".$_COOKIE["historyDetails"]["date_cookie"]."</td>";
echo "<td align=center>".$_COOKIE["historyDetails"]["time_cookie"]."</td>";
if(isset($_COOKIE["historyDetails"])){
echo "<td align=center>";
echo "<ul>";
$emp=explode("#",$_COOKIE["historyDetails"]["extras_cookie"]);
echo "<li>".$emp."</li>";
echo "</ul>";
echo "</td>";
}
else{
echo "<td align=center>"."No extras Found!"."</td>";
}
echo "</tr>";
}
die();
}
?>
any help?
Without knowing the content you are trying to set in the cookie I had to improvise to test this code. In my tests the contents of the cookie were urlencoded which is why - in conjunction with the fact that the value is json encoded, I suspect, you were not able to directly access the values held within the cookie by name.
<?php
$_POST['save_details']=true;
$cname='historyDetails';
$one_week=strtotime( 'now + 1 week' );
$total_salary=mt_rand(150000,250000);
$extra=array(
'banana' => 'yellow#curvy#healty',
'snow' => 'cold#white#fun'
);
if ( isset( $_POST['save_details'] ) ) {
if( isset( $_COOKIE[ $cname ] ) ) {
$cookieValue=json_decode( $_COOKIE[ $cname ] );
}
$details['totalsalary_cookie'] = $total_salary;
if( isset( $extra ) ) {
foreach( $extra as $e ){
$details=explode("#",$e);
$name=$details;
$details['extras_cookie']= $name;
}
}
$details['date_cookie']= date("d/m/y");
$details['time_cookie']= date("h:i:sa");
$cookieValue=$details;
setcookie( $cname, json_encode( $cookieValue, JSON_HEX_APOS ), $one_week );
}
if( isset( $_COOKIE['historyDetails'] ) ){
$json=json_decode( urldecode( $_COOKIE[ $cname ] ) );
printf('<pre>%s</pre>',print_r($json,true));
}
?>
This yields a cookie string like this:
%7B%220%22%3A%22cold%22%2C%221%22%3A%22white%22%2C%222%22%3A%22fun%22%2C%22extras_cookie%22%3A%5B%22cold%22%2C%22white%22%2C%22fun%22%5D%2C%22date_cookie%22%3A%2220%5C%2F03%5C%2F21%22%2C%22time_cookie%22%3A%2201%3A10%3A27pm%22%7D
But when decoded using the code shown yields:
stdClass Object
(
[0] => cold
[1] => white
[2] => fun
[extras_cookie] => Array
(
[0] => cold
[1] => white
[2] => fun
)
[date_cookie] => 20/03/21
[time_cookie] => 01:09:25pm
)
From that you should find it is easy enough to access items from the cookie:
echo $json->extras_cookie[0], $json->date_cookie; //etc

shell_exec returns NULL but works in shell

In my php script I'm calling another php scipt via shell_exec().
(The second script only works when executed in the shell, I don't know why but that should not matter here.)
This is the main script calling the other:
$result = shell_exec( 'php /html/wp-content/plugins/neuhof/includes/sync/load_products.php' );
$data = json_decode($result, true);
foreach($data as $product) {
if($product['ID'] !== NULL) {
$wc_product = wc_get_product( $product['ID'] );
?>
<tr id="<?php echo $product['Xhartid']; ?>">
<td class="title column-title has-row-actions column-primary page-title"><strong><?php echo $wc_product->get_name(); ?></strong>
<div class="row-actions">ID: <?php echo $product['ID']; ?> | <span class="view"> Anschauen </span></div>
</td>
<td><?php echo $product['operation']; ?></td>
<td class="state">Warten auf WP-Cron...</td>
</tr>
<?php
} else {
?>
<tr id="<?php echo $product['Xhartid']; ?>">
<td class="title column-title has-row-actions column-primary page-title"><strong><?php echo $product['Xhartbez']; ?></strong>
<div class="row-actions">Noch keine ID vergeben</div>
</td>
<td><?php echo $product['operation']; ?></td>
<td class="state">Warten auf WP-Cron...</td>
</tr>
<?php
}
}
This is the script that should be executed in the shell:
<?php
ini_set('display_errors', 0);
require_once( 'databases.php' ); // Notwendige Datenbankverbindungen
define('SHORTINIT', true); // load minimal WordPress
require_once '/html/wp-load.php'; // WordPress loader
// Mit dieser Funktion werden die Datenbank IDs aus dem ERP nutzbar gemacht
function decodeID($id) {
$unpacked = unpack('Va/v2b/n2c/Nd', $id);
return sprintf('%08X-%04X-%04X-%04X-%04X%08X', $unpacked['a'], $unpacked['b1'], $unpacked['b2'], $unpacked['c1'], $unpacked['c2'], $unpacked['d']);
}
$sql = "
SELECT
Xhartid,
Xbearbdat,
Xhartbez
FROM cms.dbo.xHauptartikel
WHERE Xinternet = '1'
ORDER BY Xhartid ASC
";
$erp_ids = $GLOBALS['erp']->query($sql)->fetchALL();
// Code für Abfrage mit WordPress ID
$sql = "
SELECT distinct
A.post_id as 'ID',
A.meta_value as 'Xhartid',
B.meta_value as 'Xbearbdat'
FROM
wp_postmeta A,
wp_postmeta B
WHERE
A.meta_key = 'Xhartid'
AND
B.meta_key = 'Xbearbdat'
AND
A.post_id = B.post_id
order by Xbearbdat
asc
";
$b = $GLOBALS['cms']->query($sql)->fetchALL();
foreach( $erp_ids as $keya => $a ) {
foreach( $b as $key => $row ) {
if(decodeID($a['Xhartid']) == $row['Xhartid'] ) {
if($a['Xbearbdat'] == $row['Xbearbdat']) {
// Ist akutell
} else {
// Aktualisieren
$list[decodeID($a['Xhartid'])]['operation'] = 'Aktualisieren';
$list[decodeID($a['Xhartid'])]['ID'] = $row['ID'];
$list[decodeID($a['Xhartid'])]['Xhartid'] = $row['Xhartid'];
}
unset($b[$key]);
unset($erp_ids[$keya]);
}
}
}
// Erstellen
foreach($erp_ids as $row) {
$list[decodeID($row['Xhartid'])]['operation'] = 'Erstellen';
$list[decodeID($row['Xhartid'])]['ID'] = NULL;
$list[decodeID($row['Xhartid'])]['Xhartid'] = decodeID($row['Xhartid']);
$list[decodeID($row['Xhartid'])]['Xhartbez'] = $row['Xhartbez'];
}
// Löschen
foreach($b as $row) {
$list[$row['Xhartid']]['operation'] = 'Löschen';
$list[$row['Xhartid']]['ID'] = $row['ID'];
$list[$row['Xhartid']]['Xhartid'] = $row['Xhartid'];
}
if($argv[1] == 'count') {
$ids = 0;
foreach( $list as $product ) {
$ids++;
}
echo $ids;
} elseif ($argv[1] == 'list') {
$ids = NULL;
foreach( $list as $product ) {
$ids[] = $product['Xhartid'];
}
echo json_encode($ids, JSON_UNESCAPED_UNICODE);
} else {
echo json_encode($list, JSON_UNESCAPED_UNICODE);
}
The script returns NULL and even if I try exec() and get the errors, they are also NULL.
I have no idea why this is not working, since shell_exec('ls') and simple "hello world" scripts are working fine!
(The second script only works when executed in the shell, I don't know why but that should not matter here.)
This is probably because MSSQL connection from second script that you have mentioned is blocked in your webserver environment/php configuration used by webserver.
When you are running second script from shell it may work fine as it is working on different environment. But when you are running second script using shell_exec in php script runned by your webserver it is started with the same webserver environment where it was blocked.
So if you are trying to use shell_exec as a "hack" to omit limitations in your webserver environment then it will not work.
You should contact your server administrator to resolve this.

How to remove a specific data from an API?

I'm working on a site which gives metrics of site, it uses API of gtmetrix. So i want to remove a specific data from the coming result but I just dont know how to do it. Some help would be appreciated!
<?php
require_once('service.inc.php');
$test = new Services_WTF_Test("email", "api_key");
$url_to_test = "https://google.me/";
echo "Testing $url_to_test\n";
$testid = $test->test(array(
'url' => $url_to_test
));
if ($testid) {
echo "Test started with $testid\n";
}
else {
die("Test failed: " . $test->error() . "\n");
}
echo "Waiting for test to finish\n";
$test->get_results();
if ($test->error()) {
die($test->error());
}
$testid = $test->get_test_id();
echo "Test completed succesfully with ID $testid\n'<br>";
$results = $test->results();
if ($results): ?>
<?php
foreach($results as $result => $data): ?>
<strong><?php $ukey = strtoupper($result);
echo $ukey; ?>:</strong>
<?php echo $data; ?><br><br>
<?php endforeach;
endif;
?>
The Output Is:
FIRST_CONTENTFUL_PAINT_TIME: 1495
PAGE_ELEMENTS: 44
REPORT_URL: https://gtmetrix.com/reports/google.me/BFylJNX3
REDIRECT_DURATION: 0
FIRST_PAINT_TIME: 1495
DOM_CONTENT_LOADED_DURATION:
DOM_CONTENT_LOADED_TIME: 1908
I want to remove the 3rd data from the api REPORT_URL:
You can skip REPORT_URL in foreach
$ukey = strtoupper( $result );
if( $ukey != 'REPORT_URL' ) {
echo '<strong>' . $ukey . '</strong>';
echo $data . '<br><br>';
}

get td values display as static in codeigniter

Hi guys i am trying to display the first td values as static so i have keep those values in one array and i try to increase the values and try to display but when i get it is displaying depending on foreach values if i have one record in foreach it is displaying one value and if i have 2 records it is displaying 2 values.
But i want to display all td value if i have values in foreach or not also.
Here is my code:
<tbody>
<?php
$arr = array(0=>'On Hold',1=>'Asset Incomplete',2=>'SME Discussion',3=>'a',4=>'b',5=>'c',6=>'d',7=>'e',8=>'f',9=>'g',10=>'h');
$i = 0;
foreach($getCourse as $report)
$status= $report->status;
{
?>
<tr>
<td><?php echo $arr[$i]; ?>
<?php $i++; ?></td>
<td><?php
if($status==1)
{
echo "On Hold";
}
elseif($status==2)
{
echo "Asset Incomplete";
}
elseif($status==3)
{
echo "Yet to Start";
}
elseif($status==4)
{
echo "SME Discussion";
}
elseif($status==5)
{
echo "Development";
}
elseif($status==6)
{
echo "PB Review";
}
elseif($status==7)
{
echo "PB Fixes";
}
elseif($status==8)
{
echo "PB2 Review";
}
elseif($status==9)
{
echo "PB2 Fixes";
}
elseif($status==10)
{
echo "Alpha Development";
}
elseif($status==11)
{
echo "Alpha Review";
}
elseif($status==12)
{
echo "Alpha Fixes";
}
elseif($status==13)
{
echo "Beta Review";
}
elseif($status==14)
{
echo "Beta Fixes";
}
elseif($status==15)
{
echo "Gamma";
}
?></td>
<td><?php echo $report->coursename; ?></td>
<td><?php echo $report->statuscount;?></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
Here is my controller:
public function index()
{
if ($this->session->userdata('is_logged')) {
$data['getCourse']=$this->Report_model->getTopicReports();
$this->load->view('template/header');
$this->load->view('reports/report',$data);
$this->load->view('template/footer');
}
else {
redirect("Login");
}
}
Here is my model:
public function getTopicReports()
{
$this->db->select('count(t.status) as statuscount,t.topicName as topicname,c.coursename,t.status')
->from('topics t')
->join('course c', 't.courseId = c.id')
->where('t.courseid',1)
->where('t.status',5);
$query = $this->db->get();
return $query->result();
}
This is how i want to display here is my referrence image:
Can anyone help me how to do that thanks in advance.
FINAL UPDATED & WORKING VERSION
For me this was tricky. This turned out to be what I felt to be a awkward indexing issue.
The problem is that your data is not optimized very well to accommodate the task you are asking for. You have to make odd comparisons as you traverse the table. I was able to get it accomplished.
I would actually be very interested in seeing a more refined approach. But until that happens this code will dynamically generate a table that matches the output of the sample pictures that you posted in your question.
I have tested this code with some sample data that matches the array structure that you posted in your comments.
Here is the code:
//Create an array with your status values.
$rowName = array(
'On Hold',
'Asset Incomplete',
'Yet to Start',
'SME Discussion',
'Development',
'PB Review',
'PB Fixes',
'PB2 Review',
'PB2 Fixes',
'Alpha Development',
'Alpha Review',
'Alpha Fixes',
'Beta Review',
'Beta Fixes',
'Gamma'
);
//Generate a list of class names and get rid of any duplicates.
foreach($getCourse as $report){
$courseNames[] = $report->coursename;
}
$courseNames = array_unique($courseNames);
//Create the header.
echo
'<table>
<thead>
<tr>
<th>#</th>';
foreach($courseNames as $course){
echo '<th>' . $course . '</td>';
}
echo
'<th>Total</th>
</tr>
</thead>
<tbody>';
//Iterate across the array(list) of status values.
for($i = 0; $i < count($rowName); $i++){
echo
'<tr>';
echo '<td>' . $rowName[$i] . '</td>';
//Iterate through all combinations of class names and status values.
for($j = 0; $j < count($courseNames); $j++){
//Set flags and intial values.
$found = FALSE;
$total = 0;
$value = NULL;
for($k = 0; $k < count($getCourse); $k++){
//***Note - The ""$getCourse[$k]->status - 1" is because the status values in your data do not appear
//to start with an index of 0. Had to adjust for that.
//Sum up all the values for matching status values.
if(($getCourse[$k]->status - 1) == $i){
$total += $getCourse[$k]->statuscount;
}
//Here we are checking that status row and the status value match and that the class names match.
//If they do we set some values and generate a table cell value.
if(($getCourse[$k]->status - 1) == $i && $courseNames[$j] == $getCourse[$k]->coursename){
//Set flags and values for later.
$found = TRUE;
$value = $k;
}
}
//Use flags and values to generate your data onto the table.
if($found){
echo '<td>' . $getCourse[$value]->statuscount . '</td>';
}else{
echo '<td>' . '0' . '</td>';
}
}
echo '<td>' . $total . '</td>';
echo
'</tr>';
}
echo '</tbody>
</table>';
Try this. I am storing course status in $used_status then displaying the remaining status which are not displayed in foreach.
$arr = array ( '1' =>'On Hold', '2' => 'Asset Incomplete', '3' => 'SME Discussion', '4' => 'a', '5' => 'b', '6' => 'c', '7' =>'d', '8' => 'e', '9' => 'f', '10' => 'g', '11' => 'h' );
$used_status = array();
foreach($getCourse as $report) { ?>
<tr>
<td>
<?php $course_status = isset($arr[$report->status]) ? $arr[$report->status] : "-";
echo $course_status;
$used_status[] = $course_status; ?>
</td>
<td>
<?php echo $report->coursename; ?>
</td>
<td>
<?php echo $report->statuscount; ?>
</td>
</tr>
<?php }
foreach($arr as $status) {
if(!in_array($status, $used_status)) { ?>
<tr>
<td>
<?php echo $status; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
</tr>
<?php }
} ?>

How to display the php values into html table?

I have almost did the displaying of values.But i am getting an extra td I hope the complete code is right.
Can anyone see it once.
php
<?php
session_start();
$link = mysqli_connect('localhost','root','','hoteldetails');
$sno[]="";
$roomImage[]="";
$roomNo[] = "";
$hotelName[]="";
$roomPrice[]="";
$loc[]="";
if(isset($_POST['sub']))
{
// mysqli_s(elect_db($link, "hotels");
$location=$_POST['searchVal'];
$sql = "select * from roomdetails where Location = '$location'";
$sqldata= mysqli_query($link ,$sql);
while($row = mysqli_fetch_array($sqldata)){
$sno[]=$row['S.No'];
$roomImage[] = $row['RoomImage'];
$roomNo[] = $row['RoomNo'];
$hotelName[] = $row['HotelName'];
$roomPrice[] = $row['RoomPrice'];
$loc[] = $row['Location'];
}
//two arrays to display ,$combine = array_combine($one,$two);
}
?>
html
<?php
echo "<table border='1'>";
echo "<tr><th>Hotel</th><th>Location</th></tr>";
foreach($sno as $id => $key):
echo "<tr>";
echo "<td>";?><img src="<?php echo $roomImage[$id];?>" height="100" width="100"><?php echo "</td>";
echo "<td>".$roomNo[$id]."</td>";
echo "<td>".$hotelName[$id]."</td>";
echo "<td>".$roomPrice[$id]."</td>";
echo "<td>".$loc[$id]."</td>";
echo "</tr>";
endforeach;
echo "</table>";
//echo $html;
?>
Is there anything wrong in it . Please is this process is right to display the values from mysql into html.
First, format your code, using tools like http://phpbeautifier.com for example.
Next, you have lines that contain both an echo and a ?> ... <?php instruction that tells php to echo stuff without any PHP parsing.
This is quite unreadable and unmaintainable.
You should better go for some "templating-like" practices using only HTML and using PHP only to output some vars, like this:
<?php
foreach ($data as $item) {
?>
<tr>
<td>Name: <?php echo $item['name']; ?></td>
<td>Price: <?php echo $item['price']; ?></td>
</tr>
<?php
}
This would drastically improve readability, maintainability, and especially your capacity of debugging the code.
And finally, you should take care of your php.ini configuration and check that display_errors is set to 1 and error_reporting is set to E_ALL.
This way, any error like PHP - Notice : Undefined index ... will be shown in the output so you can debug it.

Categories