how to get cookie values by name from an array - php

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

Related

Associative Array and Boolean Check in PHP

I'm not too sure how to call the Associative array to verify if the number is true or false because I am doing a simple checker for enrollment class. The max class capacity is 40 and the file is combined with HTML and PHP.
I did it like this:-
<?php
//Create the association array.
$classInfo = array("J1" => 20 ,"J2" => 30,"J3" => 10,"J4" => 43,
"J5" => 40,"J6" => 45,"J7" => 15,"J8" => 34,"J9" => 10,"J10" => 45);
$class = array_keys($classInfo);
$totalEnroll = count($classInfo);
?>
The Code:-
<table width="300" style="border: 1px solid black">
<tr>
<?php
// class and enroll Lists
echo "<td width=20>";
echo "Class"."&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"." Enroll"."<br><hr>";
for($i=0; $i < $totalEnroll; ++$i) {
echo $class[$i] . "&nbsp&nbsp&nbsp&nbsp&nbsp" .
$classInfo[$class[$i]] . "<br>";
}
echo "</td>";
// Enroll to check whether the classroom is full.
echo "<td width=20>";
echo "Class States" . "<br><hr>";
for($check = 0; $check < 10; $check++){
if($classInfo[$totalEnroll[$check]] >= 0 &&
$classInfo[$totalEnroll[$check]] <= 40){
echo "Full";
echo " <br>";
} else {
echo "Not Full";
echo " <br>";
}
}
echo "</td>";
?>
</tr>
</table>
The Output That I want:-
Class
Enroll
Full States
J1
20
Not Full
J5
40
Full
Do check on the part say `//Enroll to check whether the classroom is full. This is where the code of the enrollment class is checked.
However, by the way, the output can it be aligned more cleanly in a table-like column.
You are displaying the data in two separate loops which makes it difficult to align the data, you should make it into 1 loop and use the <tr> and <td> tags around each group of items...
<table width="300" style="border: 1px solid black">
<?php
foreach ( $classInfo as $className => $enrolled ) {
echo "<tr>";
// class and enroll Lists
echo "<td>{$className}</td>";
echo "<td>{$enrolled}</td>";
// Enroll to check whether the classroom is full.
echo "<td>";
if($enrolled <= 40){
echo "Full";
} else {
echo "Not Full";
}
echo "</td>";
echo "</tr>";
}
?>
</table>
(This doesn't include a header, but I'm sure you can add that).

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 }
} ?>

cURL not POSTing to 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.

PHP or JQUERY JSON Handling

I have a simple JSON StdClass Object from a PHP, and I wish to format it into a table/list/div and eliminate other keys and values in the process. The JSON looks like this:
stdClass Object (
[msc] => 150
[number] => 309
[status] => OK
[msc_mcc] => 652
[imsi] => 652010154107728
[mcc] => 652
[operator_country] => Botswana
[msc_operator_name] => MSC
[msc_operator_country] => Botswana
[msc_mnc] => 01
[mnc] => 01
[id] => 1072540715
[msc_location] =>
[operator_name] => MSC )
I have tried PHP and did make a table, but the problem is I need to pick certain values other that the whole body, and also I need to eliminate empty values
function print_nice($elem,$max_level=10,$print_nice_stack=array()){
if(is_array($elem) || is_object($elem)){
if(in_array($elem,$print_nice_stack,true)){
echo "<font color=red>RECURSION</font>";
return;
}
$print_nice_stack[]=&$elem;
if($max_level<1){
echo "<font color=red>nivel maximo alcanzado</font>";
return;
}
$max_level--;
echo "<table class='table table-bordered table-striped'>";
if(is_array($elem)){
echo '<tr><th colspan=2><strong><font><h3>Results, with love</h3></font></strong></th></tr>';
}else{
echo '<tr><th colspan=2 class=hdrs><strong>';
echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></th></tr>';
}
$color=0;
foreach($elem as $k => $v){
if($max_level%2){
$rgb=($color++%2)?"#f5f5f5":"#efeeee";
}else{
$rgb=($color++%2)?"#f5f5f5":"#efeeee";
}
echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
echo '<strong>'.$k."</strong></td><td>";
print_nice($v,$max_level,$print_nice_stack);
echo "</td></tr>";
}
echo "</table>";
return;
}
if($elem === null){
echo "<font color=green>NULL</font>";
}elseif($elem === 0){
echo "0";
}elseif($elem === true){
echo "<font color=green>TRUE</font>";
}elseif($elem === false){
echo "<font color=green>FALSE</font>";
}elseif($elem === ""){
echo "<font color=green>EMPTY STRING</font>";
}else{
echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
}
}
get_object_vars() and in_array() may be helpful here
For example:
<?php
$object = json_decode($jsonstring);
?>
<table>
<?php
foreach (get_object_vars($object) as $k => $v)
{
if (in_array($k, array('msc', 'number', 'status')) && ! empty($v))
{
echo '<tr>';
echo "<td>{$k}</td><td>{$v}</td>";
echo '</tr>';
}
}
?>
</table>
Where $object is the name of your json_decoded variable
Edit:
Added a check for empty values too

Categories