PHP: Array with foreach loop? - php

I have a and Array which looks like this:
$sms = array(
'from' => 'DummyFrom',
'to' => '+46709751949',
'message' => 'Hello hello!'
);
echo sendSMS ($sms) . "\n";
what i'm trying to do is to put this array within a foreach loop so it can be executed multiple time (based on the given times from mysql database). to explain it better, I did something like this:
if (is_array($g_numbers)) {
foreach ($g_numbers as $number) {
$sms = array(
'from' => 'DummyFrom',
'to' => "" . $number . "",
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}
but that is wrong and its stops the PHP page to execute properly without any errors!
Could someone please advise on this issue?
My full code :
<?php
$people = array();
$sql = "SELECT id, g_name, numbers FROM groups WHERE g_name='$groups'";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$g_id = $row['id'];
$g_name = $row['g_name'];
$g_numbers = $row['numbers'];
$people[$g_numbers] = $g_numbers;
}
?>
<?
// Example to send SMS using the 46elks service
// Change $username, $password and the mobile number to send to
function sendSMS($sms)
{
// Set your 46elks API username and API password here
// You can find them at https://dashboard.46elks.com/
$username = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$password = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic " . base64_encode($username . ':' . $password) . "\r\n" . "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($sms),
'timeout' => 10
)
));
$response = file_get_contents('https://api.46elks.com/a1/SMS', false, $context);
if (!strstr($http_response_header[0], "200 OK"))
return $http_response_header[0];
return $response;
}
if (is_array($g_numbers)) {
foreach ($g_numbers as $number) {
$sms = array(
'from' => 'DummyFrom',
/* Can be up to 11 alphanumeric characters */
'to' => "" . $number . "",
/* The mobile number you want to send to */
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}
?>

This will work because tables values are stored in $people:
if (is_array($people)) {
foreach ($people as $number) {
$sms = array(
'from' => 'DummyFrom',
/* Can be up to 11 alphanumeric characters */
'to' => "" . $number . "",
/* The mobile number you want to send to */
'message' => 'Hello hello!'
);
echo sendSMS($sms) . "\n";
}
}

Related

Shortcode parameter not working in WordPress

I am trying to pass amount parameters in url from the shortcode. The from and to attributes are working fine but the amount attribute is not working. The output shows the value of 1.
using the shortcode like this:
[exchange_rate from="USD" to="EUR" amount="100"]
function exchange_rate_shortcode($atts) {
$atts = shortcode_atts(array(
'from' => 'AED',
'to' => 'NPR',
'amount' => '1',
), $atts);
$url = "https://api.fastforex.io/convert?from=" . $atts['from'] . "&to=" . $atts['to'] . "&amount=" . $atts['amount'] . "&api_key=xxxx-xxxxx-xxxx";
$result = file_get_contents($url);
$result = json_decode($result, true);
return number_format((float)$result['result']['rate'], 2, '.', '') . " " . $atts['to'];
}
add_shortcode('exchange_rate', 'exchange_rate_shortcode');
Perhaps you somehow wrote the word "amount" wrong and therefore an error occurs. To avoid confusion, use the build_query function.
Your code will look like this:htt
function exchange_rate_shortcode($atts)
{
$atts = shortcode_atts(array(
'from' => 'AED',
'to' => 'NPR',
'amount' => '1',
'api_key' => 'xxxx-xxxxx-xxxx',
), $atts);
// to make sure the correct value type is specified
$atts['amount'] = (float)$atts['amount'];
$url = "https://api.fastforex.io/convert?" . build_query($atts);
$result = file_get_contents($url);
if ( ! empty($result)) {
$result = json_decode($result, true);
return number_format((float)$result['result']['rate'], 2, '.', '') . " " . $atts['to'];
}
return '';
}
add_shortcode('exchange_rate', 'exchange_rate_shortcode');

Echo value in array_push

I have this code:
include "xmlapi.php";
$pass = 'testing1234';
$auser = 'testing';
$server = "0.0.0.0";
$port = 2087;
$remote_api = new xmlapi($server);
$remote_api->password_auth($auser, $pass);
$remote_api->set_port($port);
$remote_api->set_output('json');
$json_list = $remote_api->xmlapi_query('listaccts', array( 'api.version'=> 1));
$list = json_decode($json_list, true);
if ( ! is_array($list)
|| ! array_key_exists('data', $list)
|| ! is_array($list['data'])
|| ! array_key_exists('acct', $list['data'])
) {
die("Invalid response!");
}
$email_list = array();
foreach ($list['data']['acct'] as $acct) {
$username = $acct['user'];
$json_emails = $remote_api->api2_query($username, 'Email', 'listpopswithdisk', array());
$acct_emails = json_decode($json_emails, true);
if ( is_array($acct_emails)
&& array_key_exists('cpanelresult', $acct_emails)
&& is_array($acct_emails['cpanelresult'])
&& array_key_exists('data', $acct_emails['cpanelresult'])
&& is_array($acct_emails['cpanelresult']['data'])
) {
foreach ($acct_emails['cpanelresult']['data'] as $an_email) {
array_push(
$email_list,
array(
'cpanel_account' => $username,
'domain' => $an_email['domain'],
'email' => $an_email['user'],
'full_email' => $an_email['email'],
'diskused' => $an_email['diskused'],
)
);
echo $an_email['email'] . ' - ';
echo $an_email['diskused'] . ' - ';
echo $an_email['user'] . '<br>';
}
}
}
I used this code to connect to my cpanel and list all the email on the server.
At first I just use var_dump to see if it works. And tried to use foreach loop but not success.
How can I do a loop to echo all the data, so I can put the data in a table or something like that.
Please help me with this, thank you.
You need to parse the array containing the email accounts and print into a <table>
Try to adapt this code:
$email_list = [
['email' => 'first#email.com', 'diskused' => 'the diskused', 'user' => 'the first user'],
['email' => 'second#email.com', 'diskused' => 'the diskused', 'user' => 'the second user'],
['email' => 'third#email.com', 'diskused' => 'the diskused', 'user' => 'the third user'],
];
if (count($email_list)) {
print '<table>';
/* Set the header fields to print and Titles */
$headers = [
'email' => 'Email',
'diskused' => 'Diskused',
'user' => 'User'
];
/* Print table headers */
print '<tr>';
foreach ($headers as $headerTitle) {
print '<th>'.$headerTitle.'</th>';
}
print '</tr>';
/* Parse all rows */
foreach ($email_list as $row) {
print '<tr>';
/* Print all values */
foreach (array_keys($headers) as $headerKey) {
print '<td>'.$row[$headerKey].'</td>';
}
print '</tr>';
}
print '</table>';
}

IPB php function works but is slow. SQL needs to be faster

I'm only using a small part of this function actually but I wanted to post it all to provide the big picture. There is a part of the query in this function that finds recent attachments a user has posted to the forums. The block is on the user profile. IT works but the problem is ... it's VERY slow!! Core attachments locks up for 30+ seconds and makes my site unusable.
Any one who could help it would be much appreciated.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
$tids = '';
if ($topicIds)
{
$tids = ' AND forums_topics.tid IN (' . $topicIds . ')';
}
$mids = '';
if ($membersIds)
{
$mids = ' AND core_attachments.attach_member_id IN (' . $membersIds . ')';
}
$whereT = array();
$joinsT = array();
$findInPosts = ' AND ' . \IPS\Db::i()->findInSet('queued', array('0'));
$joinsT[] = array(
'select' => 'forums_posts.*',
'from' => 'forums_posts',
'where' => array("forums_posts.pid=core_attachments_map.id2" . $findInPosts),
);
$findInTopics = ' AND ' . \IPS\Db::i()->findInSet('approved', array('1'));
$joinsT[] = array(
'select' => 'forums_topics.*',
'from' => 'forums_topics',
'where' => array("forums_topics.tid=forums_posts.topic_id" . $findInTopics . $fids . $tids),
);
$select = 'core_attachments.attach_id AS custom_data, core_attachments.*';
if ($group)
{
$select = 'core_attachments.attach_id AS custom_data, COUNT(attach_is_image) as cnt_images, SUM(attach_hits) as summ_attach_hits, core_attachments.*';
}
$joinsT[] = array(
'select' => $select,
'from' => 'core_attachments',
'where' => array('core_attachments.attach_is_image=1 AND core_attachments.attach_is_archived=0 AND core_attachments.attach_id=core_attachments_map.attachment_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_members.member_id, core_members.member_group_id, core_members.mgroup_others, core_members.name, core_members.members_seo_name',
'from' => 'core_members',
'where' => array('core_attachments.attach_member_id=core_members.member_id' . $mids),
);
$joinsT[] = array( 'select' => 'core_permission_index.perm_id',
'from' => 'core_permission_index',
'where' => array("core_permission_index.app='forums' AND core_permission_index.perm_type='forum' AND core_permission_index.perm_type_id=forums_topics.forum_id"),
);
$groupT = $group;
$whereT[] = array(
"core_attachments_map.location_key='forums_Forums' AND " .
\IPS\Db::i()->findInSet('perm_view', array_merge(array(\IPS\Member::loggedIn()->member_group_id), array_filter(explode(',', \IPS\Member::loggedIn()->mgroup_others)))) . " OR perm_view='*'" .
$fids . $tids . $mids
);
$table = new \IPS\Helpers\Table\Db(
'core_attachments_map',
\IPS\Http\Url::internal('app=core&module=system&controller=nbattachpictures', 'front', 'nbattachpictures'),
$whereT,
$groupT
);
$table->joins = $joinsT;
$table->limit = $limit;
$table->sortBy = $order;
$table->sortDirection = $sort;
$table->rowsTemplate = array(\IPS\Theme::i()->getTemplate('plugins', 'core', 'global'), 'nbAttachmentsBlocksRows');
$table->parsers = array(
'custom_data' => function( $val, $row )
{
return array(
'topic_data' => \IPS\Http\Url::internal("app=forums&module=forums&controller=topic&id={$row['tid']}", 'front', 'forums_topic', array($row['title_seo'])),
'summ_attach_hits' => $row['summ_attach_hits'],
'jewel' => $this->attachJewel($row['summ_attach_hits']),
);
},
);
return $table;
}

PHP- sendgrid add multiple emails to a recipient list returns error 500

I have the following code:
static function getContext($data) {
// use key 'http' even if you send the request to https://...
$options = array (
'http' => array (
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query ( $data )
)
);
return stream_context_create ( $options );
}
static function addEmailsToRecipientList($name, $emails) {
$url = 'https://sendgrid.com/api/newsletter/lists/email/add.json';
$temp = array();
foreach($emails as $email){
$temp[] = array('email' => $email, 'name' => 'unknown');
}
$data = array (
'list' => $name,
'data' => json_encode($temp),
'api_user' => $api_user_name,
'api_key' => $api_password
);
$context = SendGridAPI::getContext ( $data );
return file_get_contents ( $url, false, $context );
}
When I pass to addEmailsToRecipientList a name of an existing list and an array of email addresses that I want to add to it, I get an error 500 (internal server error).
Adding a single email ($temp = array('email' => $email, 'name' => 'unknown')) works fine.
What am I doing wrong?
Thanks a lot!
Solved it! :)
//listname: the name of an existing recipients list
//$emails: an array of emails
static function addEmailsToRecipientList($listname, $emails){
$username= 'sendgrid_username';
$password= 'sendgrid_password';
$url = 'https://sendgrid.com/api/newsletter/lists/email/add.json?api_user='.$username.'&api_key='.$password;
$str= '&list=' . $listname;
for ($i=0;$i<count($emails);$i++) {
$str.= '&data[]={"email":"'.$emails[$i] . '","name":"unknown'. $i .'"}';
}
return file_get_contents($url . $str);
}
The scripts with a some touchs works very fine, i add the urlencode, the json_decode and simulated name for the email.
$url = 'https://sendgrid.com/api/newsletter/lists/email/add.json?api_user='.$username.'&api_key='.$password;
$str= '&list=' . $listname;
foreach ($data as $email) {
$attributes = explode("#", $email);
$str.= '&data[]=';
$str.= urlencode('{"email":"'. $email . '","name":"'. ucfirst($attributes[0]) .'"}');
}
$results = file_get_contents($url . $str);
$results = json_decode($results, TRUE);
return (isset($results['inserted'])) ? $results['inserted'] : 0;

Array returning empty - Facebook API

When i'm trying to receive all the data from a specific facebook page (that i have access, and garantee the access from my app) it return empty array.
But i use the same access_token in th graphic API explorer, i can see everything.
Any ideas why?!
Here's my code:
<?php
include (APPPATH.'libraries/facebook/facebook.php');
class Fbpages_users extends Facebook {
public function Fbpages_users($pages) {
$ci =& get_instance();
$ci->config->load('facebook', TRUE);
$config = $ci->config->item('facebook');
$facebook = new Facebook(array(
'appId' => '***********',
'secret' => '**********',
));
parent::__construct($config);
for ($x=0; $x<count($pages); $x++) {
try {
$pageFeed = $this->api('/'.$pages[$x]['page_id'].'/feed?access_token='.$pages[$x]['access_token']);
$this->pagefeed = $pageFeed;
echo "<pre>";print_r($pageFeed); echo "</pre>";
for ($i=0;$i<count($pageFeed['data']);$i++) {
for ($z=0;$z<count($pageFeed['data'][$i]['likes']['data']);$z++) {
$query_fb_user_likes = $ci->db->query("
SELECT user_id,id_fb_pages,type FROM fb_users
where user_id like " . $pageFeed['data'][$i]['likes']['data'][$z]['id']
. " AND id_fb_pages like " . $pages[$x]['id_fb_pages']
. " AND type like 1
");
$verifica_query_likes = $query_fb_user_likes->result_array();
if ( (empty($verifica_query_likes)) AND ($pages[$x]['page_id'] != $pageFeed['data'][$i]['likes']['data'][$z]['id']) )
{
$likes = array(
'id_fb_pages' => $pages[$x]['id_fb_pages'],
'user_id' => $pageFeed['data'][$i]['likes']['data'][$z]['id'],
'type' => '1'
);
$ci->db->insert('fb_users', $likes);
}
}
for ($s=0;$s<count($pageFeed['data'][$i]['comments']['data']);$s++) {
$query_fb_user_comments = $ci->db->query("
SELECT user_id,id_fb_pages,type FROM fb_users
where user_id like " . $pageFeed['data'][$i]['comments']['data'][$s]['from']['id']
. " AND id_fb_pages like " . $pages[$x]['id_fb_pages']
. " AND type like 2
");
$verifica_query_comments = $query_fb_user_comments->result_array();
if ( (empty($verifica_query_comments)) AND ($pages[$x]['page_id'] != $pageFeed['data'][$i]['comments']['data'][$s]['from']['id']) )
{
$comments = array(
'id_fb_pages' => $pages[$x]['id_fb_pages'],
'user_id' => $pageFeed['data'][$i]['comments']['data'][$s]['from']['id'],
'type' => '2'
);
$ci->db->insert('fb_users', $comments);
}
}
}
$checked_pages_getusers = array(
'page_id' => $pages[$x]['page_id'],
'date_checked' => date ("Y-m-d H:i:s")
);
$ci->db->insert('checked_pages_getusers', $checked_pages_getusers);
} catch (FacebookApiException $e) {
error_log($e);
$error = array(
'logtype' => $pages[$x]['page_id'] . " - pages-users",
'date' => date ("Y-m-d H:i:s"),
'error' => "'" . $e . "'"
);
$ci->db->insert('error_log', $error);
}
}
//redirect('main/login');
}
}
?>

Categories