Email forwarding in PHP - php

My following code is tested by my friends. They said its working fine. But I am unable to use it. Can anybody find where the error is.
`
<?php
try
{
// Change to your mail server
$host = "pop.gmail.com";
// Connecting to POP3 email server.
$connection = imap_open("{" . $host . ":995/pop3/notls}", 'someusername#gmail.com', 'somepassword');
// Total number of messages in Inbox
$count = imap_num_msg($connection);
echo $count . " messages found<br />";
// Read Messages in Loop, Forward it to Actual User email and than delete it from current email account.
for ($i = 1; $i <= $count; $i++) {
$headers = imap_headerinfo($connection, $i);
$subject = $headers->subject;
$from = $headers->from[0]->mailbox . '#' . $headers->from[0]->host;
if ($headers->cc[0]->mailbox)
$cc = $headers->cc[0]->mailbox . '#' . $headers->cc[0]->host;
$subject = $headers->subject;
$structure = imap_fetchstructure($connection, $i);
$type = $this->get_mime_type($structure);
// GET HTML BODY
$body = $this->get_part($connection, $i, "");
//$raw_body = imap_body($connection, $i);
$attachments = array();
if (isset($structure->parts) && count($structure->parts)) {
for ($e = 0; $e < count($structure->parts); $e++) {
$attachments[$e] = array('is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '');
if ($structure->parts[$e]->ifdparameters) {
foreach ($structure->parts[$e]->dparameters as $object) {
if (strtolower($object->attribute) == 'filename') {
$attachments[$e]['is_attachment'] = true;
$attachments[$e]['filename'] = $object->value;
} //if (strtolower($object->attribute) == 'filename')
} //foreach ($structure->parts[$e]->dparameters as $object)
} //if ($structure->parts[$e]->ifdparameters)
if ($structure->parts[$e]->ifparameters) {
foreach ($structure->parts[$e]->parameters as $object) {
if (strtolower($object->attribute) == 'name') {
$attachments[$e]['is_attachment'] = true;
$attachments[$e]['name'] = $object->value;
} //if (strtolower($object->attribute) == 'name')
} //foreach ($structure->parts[$e]->parameters as $object)
} //if ($structure->parts[$e]->ifparameters)
if ($attachments[$e]['is_attachment']) {
$attachments[$e]['attachment'] = #imap_fetchbody($connection, $i, $e + 1);
if ($structure->parts[$e]->encoding == 3) {
// 3 = BASE64
$attachments[$e]['attachment'] = base64_decode($attachments[$e]['attachment']);
} //if ($structure->parts[$e]->encoding == 3)
elseif ($structure->parts[$e]->encoding == 4) {
// 4 = QUOTED-PRINTABLE
$attachments[$e]['attachment'] = quoted_printable_decode($attachments[$e]['attachment']);
} //elseif ($structure->parts[$e]->encoding == 4)
} //if ($attachments[$e]['is_attachment'])
if ($attachments[$e]['is_attachment']) {
$filename = $attachments[$e]['filename'];
$filename = $attachments[$e]['name'];
$filecontent = $attachments[$e]['attachment'];
} //if ($attachments[$e]['is_attachment'])
} //for ($e = 0; $e < count($structure->parts); $e++)
} //if (isset($structure->parts) && count($structure->parts))
/**** ****/
/*echo "<pre>";
echo "From: " . $headers->Unseen . "<br />";
echo "From: " . $from . "<br />";
echo "Cc: " . $cc . "<br />";
echo "Subject: " . $subject . "<br />";
echo "Content Type: " . $type . "<br />";
echo "Body: " . $body . "<br />";*/
$mail = new Zend_Mail();
$mail->settype(Zend_Mime::MULTIPART_MIXED);
for ($k = 0; $k < count($attachments); $k++) {
$filename = $attachments[$k]['name'];
$filecontent = $attachments[$k]['attachment'];
if ($filename && $filecontent) {
$file = $mail->createAttachment($filecontent);
$file->filename = $filename;
} //if ($filename && $filecontent)
} //for ($k = 0; $k < count($attachments); $k++)
$mail->setFrom($from);
$mail->addTo('testmail#softmail.me');
if ($cc)
$mail->addCc($cc);
$mail->setSubject($subject);
$mail->setBodyHtml($body);
$mail->send();
// Mark the email messages once read
//imap_delete($mbox, 1);
} //for ($i = 1; $i <= $count; $i++)
// Delete all marked message from current email account.
imap_expunge($mbox);
echo 'If you see this, the number is 1 or below';
}
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>

Please check if you have enabled
extension=php_openssl.dll;
ext in you php.ini. I had faced this problem once and enabling the above extension worked for me.

Related

Check if file content end on Linebreak without characters

I have this script:
$dl = array('st' => false, 'smg' => '');
$fileR = file($PhatToFile);
$fileR = array_reverse($fileR);
$c = count($fileR) + 1;
foreach ($fileR as $line) {
if (!strlen(rtrim($line))) {
$dl['smg'] .= 'Incorrect space found file: <b> ' . $file . '</b> Line: <b>' . $c . '</b><br>';
$dl['st'] = true;
$c = $c - 1;
} else {
break;
}
}
if($dl['st'] == true){
echo $dl['smg'];
}
I use it to determine if file End with Space o Line Break, but not work with this:
<?php
echo "hello world";
?> (Line break)
(no find this... line 5 have line break and file end in 6)
Check I have enumerate each line.
please try this, I have replaced your if statement.
foreach ($fileR as $line) {
if (!trim(preg_replace('/\s+/', '', $line))) {
$dl['smg'] .= 'Incorrect space found file: <b> ' . $file . '</b> Line: <b>' . $c . '</b><br>';
$dl['st'] = true;
$c = $c - 1;
} else {
break;
}
}
i solve this with, is capable detecting:
white space or line break at start of file.
white space or line break at end of file.
$dl = array('st' => false, 'smg' => '');
$smg1 = $smg3 = '';
$smg2 = [];
$fileR = file($file);
$c = 1;
foreach ($fileR as $line) {
if (!strlen(trim($line))) {
$smg1 .= 'Incorrect space/Linebreak found file: <b> ' . $file . '</b> Line: <b>' . $c . '</b><br>';
$dl['st'] = true;
$c++;
} else {
break;
}
}
$fileR = array_reverse($fileR);
$rc = count($fileR);
foreach ($fileR as $line) {
if (!strlen(trim($line))) {
$smg2[] = 'Incorrect space/Linebreak found file: <b> ' . $file . '</b> Line: <b>' . $rc . '</b><br>';
$dl['st'] = true;
$rc--;
} else {
break;
}
}
$fileR = array_reverse($fileR);
if ((substr($fileR[$rc - 1], -1) == "\n") AND strlen(trim($fileR[$rc - 1])) > 0) {
$smg3 .= 'Incorrect Linebreak found file: <b> ' . $file . '</b> Line: <b>' . $rc . '</b><br>';
$dl['st'] = true;
}
$smg2 = array_reverse($smg2);
echo $dl['smg'] = $smg1 . $smg3 . implode('', $smg2);

Notice: Undefined index: REDIRECT_URL in /home/webccans/public_html/index.php

I am getting this error:
Notice: Undefined index: REDIRECT_URL in /home/webccans/public_html/index.php
I have Tried taking out the redirect and it still works. I need help try to define the index "REDIRECT_URL" I would appreciate and pointers or advice.
The page is display, and the site works fine but this error is on the home page
This is the Code on my index page
<?
include('application.php');
$header = false;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (($request = trim($_SERVER['REDIRECT_URL'])) == '') {
// Deal with direct requests
$Page = (isset($_GET['Page'])) ? $_GET['Page'] : 1;
$Page = $CMS->getPageContent($Page);
} else {
// Deal with "friendly" URL 404 pages
$pages = explode('/', $request);
array_shift($pages);
$page = array_pop($pages);
if (($pos = strpos($page, '.')) === false) {
$ext = '';
} else {
$ext = substr($page, strpos($page, '.'));
if ($pos = strpos($ext, '?')) $ext = substr($ext, 0, $pos);
}
if ($page == '') {
// have a CMS page or the home page
} else if ($ext == '.htm' || $ext == '.html' || $ext == '.php') {
$PageURL = substr($page, 0, strlen($ext) * -1);
if ($PageURL != "index") {
// Possible have a CMS page
array_push($pages, $PageURL);
}
} else if ($ext == '') {
// have a CMS page
array_push($pages, $page);
} else {
$CMS->show404Page();
$header = true;
}
if (($numPages = count($pages)) > 0) {
// Get PageID
$select = 'SELECT ';
$from = ' FROM site_content AS page0 LEFT JOIN site_content AS
page ON (page0.ParentID = page.PageID) ';
$where = ' WHERE (page0.ParentID = 0 OR page.Display = 0) ';
for ($idx = 0; $idx < $numPages; ++$idx) {
$where .= ' AND ';
if ($idx > 0) {
$select .= ', ';
$from .= ' JOIN site_content AS page' . $idx . ' ON (page'
. ($idx - 1) . '.PageID = page' . $idx . '.ParentID)';
}
$select .= 'page' . $idx . '.PageID ';
$where .= 'page' . $idx . '.PageURL = "' . $DB-
>escape(strtolower($pages[$idx])) . '"';
#$select1 = 'page' . $idx . '.PageID ';
}
$qid = $DB->query($select . $from . $where);
if ($row = $DB->fetchRow($qid)) {
$PageID = $row[$numPages - 1];
$OpenedPages = $row;
#print_r ($row);
}
else {
$CMS->show404Page();
$header = true;
}
} else {
$PageID = 1;
}
$Page = $CMS->getPageContent($PageID);
#echo '<script language="javascript">' . 'alert("' . $PageID . '")'
.
'</script>';
#echo '<script language="javascript">' . 'alert("' . $ParentId . '")'
. '</script>';
}
$TopPage = $CMS->getTopParent($Page->PageID);
if (!$header) header('HTTP/1.1 200 OK');
?>

How to use templates or dynamic content for php email sending

PHPMailer is a good option to send email, and mail() function too, but the thing is that generating dynamic content for the email body, and subject are not the best.
for example I've created a php file with the body templates or a class with the same, but are so difficult to maintain.
What do you recomend for organizing that code?
Is there a Way to create email templates? (like twig).
How do you organize folders and files?
Is there any doc recommendation for that?
thanks for your help
It's no different than what you're already doing in PHP to generate dynamic HTML. Except that instead of sending the generated HTML output via your web server to a client UA, you're sending it to an email UA via an MTA.
20 years ago someone thought to invent a good templating engine to generate dynamic content (it was called PHP). It turns out it's still incredibly useful today.
Let's say you have a template file that looks like this for your email.
<table>
<?php foreach($rows as $row) { ?>
<tr>
<?php foreach($row as $column) { ?>
<td><?=$column?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
Let's say have some templating system that renders these templates with perhaps something like this.
class Template {
protected $templateFile = "";
protected $templateVars = [];
public function __construct($templateFile, Array $templateVars= []) {
$this->templateVars = $templateVars;
$this->templateFile = $templateFile;
}
public function __toString() {
export($this->templateVars, EXTR_SKIP);
ob_start();
include $this->templateFile;
return ob_get_clean();
}
}
Now, you could expand upon this very simple abstraction of templating a bit further to include things like your email subject line, sender email address, etc...
class SendEmail {
public function __construct($to, $subject, $template, Array $data) {
$template = new Template($file, $data); // create the email template
$this->emailBody = (string) $template; // generate the content
$this->to = $to;
$this->subject = $subject;
}
public function send() {
// Send email using PHP mailer or whatever here
}
}
$tempalteContent = mysqli_query($conn, "select * from newsletter_template where name like '%$template%'");
if (mysqli_num_rows($tempalteContent) > 0) {
$validate = 0;
$messageFinal = '';
$message = '';
$row = mysqli_fetch_array($tempalteContent);
$template_id = $row['id'];
$productInc = $row['productsInc'];
$blogInc = $row['blogInc'];
$templateMsg = htmlspecialchars_decode($row['description']);
$divData = '';
$blogData = '';
if ($blogInc == 1 && $productInc == 1) {
/* * Product Query* */
$productQuery = mysqli_query($conn, "select * from newsletter_products where newsletter_tempalte_id = $template_id");
if (mysqli_num_rows($productQuery) > 0) {
$width = '';
$website = "http://demo.com/";
if (mysqli_num_rows($productQuery) > 2) {
$width = '100%';
} else if (mysqli_num_rows($productQuery) > 1) {
$width = '100%';
}
for ($i = 0; $i <= mysqli_num_rows($productQuery); $i++) {
$row[$i] = mysqli_fetch_array($productQuery);
$product_id[$i] = $row[$i]['product_id'];
$productDetails[$i] = mysqli_query($conn, "select * from products where product_id = $product_id[$i]");
if (mysqli_num_rows($productDetails[$i]) > 0) {
$rowproduct[$i] = mysqli_fetch_array($productDetails[$i]);
$productName[$i] = $rowproduct[$i]['product_name'];
$productImg[$i] = $website . $rowproduct[$i]['product_img'];
$productDesp[$i] = htmlspecialchars_decode($rowproduct[$i]['product_desp']);
$divData .= "<div style='width:" . $width . ";float:left;padding:7px;text-align:justify'><span style='width:100%;padding-bottom:5px;float:left'><img src='" . $productImg[$i] . "' width='30%' height='30%' style='max-width:100px;max-height:100px'></span><b style='vertical-align:bottom'>" . $productName[$i] . "</b><span style='font-size:12px;'>" . $productDesp[$i] . "</span></div>";
}
$validate++;
}
}
/* * Blog Query* */
$blogQuery = mysqli_query($conn, "select * from newsletter_blogs where newsletter_template_id = $template_id");
if (mysqli_num_rows($blogQuery) > 0) {
$width = '';
$website = "http://demo.com/";
if (mysqli_num_rows($blogQuery) > 2) {
$width = '100%';
} else if (mysqli_num_rows($blogQuery) > 1) {
$width = '100%';
}
for ($i = 0; $i <= mysqli_num_rows($blogQuery); $i++) {
$row[$i] = mysqli_fetch_array($blogQuery);
$blog_id[$i] = $row[$i]['blog_id'];
$blogDetails[$i] = mysqli_query($conn, "select * from blog where id = $blog_id[$i]");
if (mysqli_num_rows($blogDetails[$i]) > 0) {
$rowblog[$i] = mysqli_fetch_array($blogDetails[$i]);
$blogName[$i] = $rowblog[$i]['title'];
$blogImg[$i] = $website . $rowblog[$i]['img'];
$blogDesp[$i] = htmlspecialchars_decode($rowblog[$i]['desp']);
$blogData .= "<div style='width:100%;float:left;padding:7px;text-align:justify'><span style='width:100%;padding-bottom:5px;float:left'><img src='" . $blogImg[$i] . "' width='30%' height='30%' style='max-width:100px;max-height:100px'></span><b style='vertical-align:bottom'>" . $blogName[$i] . "</b><span style='font-size:12px;'>" . $blogDesp[$i] . "</span></div>";
}
$validate++;
}
}
$message = $templateMsg . $divData . $blogData;
} else if ($productInc == 1 && $blogInc == 0) {
$productQuery = mysqli_query($conn, "select * from newsletter_products where newsletter_tempalte_id = $template_id");
if (mysqli_num_rows($productQuery) > 0) {
$width = '';
$website = "http://demo.com/";
if (mysqli_num_rows($productQuery) > 2) {
$width = '100%';
} else if (mysqli_num_rows($productQuery) > 1) {
$width = '100%';
}
for ($i = 0; $i <= mysqli_num_rows($productQuery); $i++) {
$row[$i] = mysqli_fetch_array($productQuery);
$product_id[$i] = $row[$i]['product_id'];
$productDetails[$i] = mysqli_query($conn, "select * from products where product_id = $product_id[$i]");
if (mysqli_num_rows($productDetails[$i]) > 0) {
$rowproduct[$i] = mysqli_fetch_array($productDetails[$i]);
$productName[$i] = $rowproduct[$i]['product_name'];
$productImg[$i] = $website . $rowproduct[$i]['product_img'];
$productDesp[$i] = htmlspecialchars_decode($rowproduct[$i]['product_desp']);
$divData .= "<div style='width:" . $width . ";float:left;padding:7px;text-align:justify'><span style='width:100%;padding-bottom:5px;float:left'><img src='" . $productImg[$i] . "' width='30%' height='30%' style='max-width:100px;max-height:100px'></span><b style='vertical-align:bottom'>" . $productName[$i] . "</b><span style='font-size:12px;'>" . $productDesp[$i] . "</span></div>";
}
$validate++;
}
}
$message = $templateMsg . $divData;
} else if ($blogInc == 1 && $productInc == 0) {
$blogQuery = mysqli_query($conn, "select * from newsletter_blogs where newsletter_tempalte_id = $template_id");
if (mysqli_num_rows($blogQuery) > 0) {
$width = '';
$website = "http://demo.com/";
if (mysqli_num_rows($blogQuery) > 2) {
$width = '100%';
} else if (mysqli_num_rows($blogQuery) > 1) {
$width = '100%';
}
for ($i = 0; $i <= mysqli_num_rows($blogQuery); $i++) {
$row[$i] = mysqli_fetch_array($blogQuery);
$blog_id[$i] = $row[$i]['blog_id'];
$blogDetails[$i] = mysqli_query($conn, "select * from blog where id = $blog_id[$i]");
if (mysqli_num_rows($blogDetails[$i]) > 0) {
$rowblog[$i] = mysqli_fetch_array($blogDetails[$i]);
$blogName[$i] = $rowblog[$i]['title'];
$blogImg[$i] = $website . $rowblog[$i]['img'];
$blogDesp[$i] = htmlspecialchars_decode($rowblog[$i]['desp']);
$blogData .= "<div style='width:100%;float:left;padding:7px;text-align:justify'><span style='width:100%;padding-bottom:5px;float:left'><img src='" . $blogImg[$i] . "' width='30%' height='30%' style='max-width:100px;max-height:100px'></span><b style='vertical-align:bottom'>" . $blogName[$i] . "</b><span style='font-size:12px;'>" . $blogDesp[$i] . "</span></div>";
}
$validate++;
}
}
$message = $templateMsg . $blogData;
} else {
$message = $templateMsg;
}
$messageFinal = '<div style="width:100%">' . $message . '</div>';
echo $validate;
} else {
echo "Fail";
exit();
}
$subscribers = explode(',', $_POST['subscribers']);
for ($i = 0; $i < count($subscribers); $i++) {
$to = $subscribers[$i];
$subject = $template;
$from = 'demo#demo.com';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Create email headers
$headers .= 'From: Demo' . "\r\n" .
'Reply-To: Your Email Id' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Compose a simple HTML email message
$message = '<!DOCTYPE html><html><body>';
$message .= $messageFinal . $footer;
$message .= '</body></html>';
// Sending email
if (mail($to, $subject, $message, $headers)) {
$validate++;
} else {
$validate = 0;
}
}

How to add more elements to specific key in array?

I am trying to convert xml node into array, i have 3 separated nodes inside parent match node, so i need to convert all them into array.
When i try this code
foreach($lineup->away->player as $player){
$awaysquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
and call this matcharr by:
print_r($matcharr);
There is just last element for each index/array, i want to get all players from lineup tag.
So print_r prints this:
Array ( [goal] => 2456166 [name] => Luís Leal [number] => 9 [playerid]
=> 2474225 [yellow] => 2486288 [subin] => 2353344 [subout] => 0 [minute] => NA )
for each match tag, but i need to get 22 players for each match.
Here is more detailed code:
foreach($week->match as $match){
$matcharr = array();
//var_dump($match);
$fixid = 0;
if($match->attributes()->id == 0 || $match->attributes()->id == ''){
if($match->attributes()->alternate_id == 0 || $match->attributes()->id == ''){
$fixid = $match->attributes()->alternate_id_2;
}
else{
$fixid = $match->attributes()->alternate_id;
}
}
else{
$fixid = $match->attributes()->id;
}
$dbdate = date('Y-m-d',strtotime($match->attributes()->date));
$dbtime = date('H:i:s', strtotime($match->attributes()->time));
//if($dbdate == date('Y-m-d')){
echo $dbdate . ' ' . date("Y-m-d");
$datetime = date('Y-m-d H:i:s',strtotime($dbdate . $dbtime));
$fcountry = $this->filterCountries($results->attributes()->country);
$stadium = $match->attributes()->venue;
$city = $match->attributes()->venue_city;
//echo $fcountry;
//$home = $match->home->attributes()->name;
//$away = $match->away->attributes()->name;
$home = '';
$away = '';
$homeid = 0;
$awayid = 0;
$hgoals = 0;
$agoals = 0;
if($match->home){
$home = $this->getMap($fcountry,$match->home->attributes()->name);
$away = $this->getMap($fcountry,$match->away->attributes()->name);
$homeid = $this->filterTeams($fcountry,$match->home->attributes()->id);
$awayid = $this->filterTeams($fcountry,$match->away->attributes()->id);
$hgoals = $match->home->attributes()->score;
$agoals = $match->away->attributes()->score;
}
$eventname = $home . ' - ' . $away;
$halftimehomegoals = 0;
$halftimeawaygoals = 0;
if($match->halftime->attributes()->score != NULL){
$halftime = explode("-",$match->halftime->attributes()->score);
$halftimehomegoals = (int)$halftime[0];
if(array_key_exists(1,$halftime)){
$halftimeawaygoals = (int)$halftime[1];
}
}
$homescore = '';
$awayscore = '';
if($match->goals->goal != NULL){
foreach($match->goals->goal as $goal){
if($goal->attributes()->team == 'home'){
$homescore .= $goal->attributes()->minute.': '.
$goal->attributes()->player.'; ';
$matcharr['goal'] = (int)$goal->attributes()->playerid;
}
elseif($goal->attributes()->team == 'away'){
$awayscore .= $goal->attributes()->player.'; ';
$matcharr['goal'] = (int)$goal->attributes()->playerid;
}
}
}
$homesquad = '';
$awaysquad = '';
if($match->lineups != NULL){
foreach($match->lineups as $lineup){
if($lineup->home->player != NULL){
foreach($lineup->home->player as $player){
$homesquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
}
if($lineup->away->player != NULL){
foreach($lineup->away->player as $player){
$awaysquad .= $player->attributes()->name . '; ';
$matcharr['name'] = (string)$player->attributes()->name;
$matcharr['number'] = (int)$player->attributes()->number;
$matcharr['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ",$player->attributes()->booking));
if(substr_count($player->attributes()->booking,"YC") == 1){
$matcharr['yellow'] = (int)$player->attributes()->id;
}
elseif((substr_count($player->attributes()->booking,"RC")==1)
or ($yellowcount == 3)){
$matcharr['red'] = (int)$player->attributes()->id;
}
}
}
}
}
$homesub = '';
$awaysub = '';
if($match->substitutions != NULL){
foreach($match->substitutions as $subs){
if($subs->home->substitution != NULL){
foreach($subs->home->substitution as $sub){
$homesub .= $sub->attributes()->minute."' in: ".
$sub->attributes()->player_in_name . '; ' . ' out: ' .
$sub->attributes()->player_out_name . '; ';
$matcharr['subin'] = (int)$sub->attributes()->player_in_id;
$matcharr['subout'] = (int)$sub->attributes()->player_out_id;
$matcharr['minute'] = (string)$sub->attributes()->minute;
}
}
if($subs->away->substitution != NULL){
foreach($subs->away->substitution as $sub){
$awaysub .= $sub->attributes()->minute."' in: ".
$sub->attributes()->player_in_name . '; ' .
$sub->attributes()->player_out_name . '; ';
$matcharr['subin'] = (int)$sub->attributes()->player_in_id;
$matcharr['subout'] = (int)$sub->attributes()->player_out_id;
$matcharr['minute'] = (string)$sub->attributes()->minute;
}
}
}
}
echo $leaguename . ' ' . $leagueid . ' ' . $fixid . ' ' . $eventname.'<br>';
print_r($matcharr);
Add some counter variable before storing it in array like below
$element_count = 0;//Counter variable
foreach ($lineup->away->player as $player) {
$awaysquad .= $player->attributes()->name . '; ';
$matcharr[$element_count]['name'] = (string)$player->attributes()->name;
$matcharr[$element_count]['number'] = (int)$player->attributes()->number;
$matcharr[$element_count]['playerid'] = (int)$player->attributes()->id;
$yellowcount = count(explode(" ", $player->attributes()->booking));
if (substr_count($player->attributes()->booking, "YC") == 1) {
$matcharr[$element_count]['yellow'] = (int)$player->attributes()->id;
}
elseif ((substr_count($player->attributes()->booking, "RC") == 1) or ($yellowcount == 3)) {
$matcharr[$element_count]['red'] = (int)$player->attributes()->id;
}
$element_count++;
}

Faster Rackspace cloud upload

I have used to the Rackspace API to upload files to the RackSpace cloud. But this method seems to be a little on the slow side. Is there a better or faster way to upload a file to the cloud(curl, http adapters, etc)?
I am currently uploading with PHP and using the provided API.
Here is my solution how to make it fast:
I'm uploading only missing files using simple PHP script below. Thanks to it I do it in just one click and in just a few seconds.
PHP source code:
function UploadMissingFilesToRackFileCDN($file_paths_to_upload, $b_force_upload = false)
{
include_once("cloudfiles.php");
// Connect to Rackspace
$username = cloudfile_username; // username
echo "Connecting to CDN..." . date("H:i:s") . "<br>"; ob_flush();
$key = cloudfile_api_key; // api key
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
echo " Connected!" . date("H:i:s") . "<br>"; ob_flush();
// Get the container we want to use
$container_name = 'vladonai';//'test_container';
echo "Obtaining container $container_name..." . date("H:i:s") . "<br>"; ob_flush();
$container = $conn->get_container($container_name);
echo " The container is obtained." . date("H:i:s") . "<br>"; ob_flush();
if (!$b_force_upload)
{
echo "Receiving container objects list..." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names = $container->list_objects();
$existing_files_count = count($existing_object_names);
echo " Objects list obtained: $existing_files_count." . date("H:i:s") . "<br>"; ob_flush();
$existing_object_names_text .= "\r\n";
foreach ($existing_object_names as $obj_name)
{
$existing_object_names_text .= $obj_name . "\r\n";
}
}
// upload files to Rackspace
$uploaded_file_n = 0;
$skipped_file_n = 0;
$errors_count = 0;
foreach ($file_paths_to_upload as $localfile_path => $file_info)
{
$filename = basename($localfile_path);
if (!file_exists($localfile_path))
{
echo "<font color=red>Error! File $localfile_path doesn't exists!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
} else
if (is_dir($localfile_path))
{
//simply skip it
} else
if (strpos($existing_object_names_text, "\r\n" . $filename . "\r\n") !== false)
{
//file is already uploaded to CDN (at least file name is present there). Would be good to have date/size checked, but CDN api has no such feature
//echo "<font color=gray>Skipped file $localfile_path - it already exists!</font><br>"; ob_flush();
$skipped_file_n ++;
} else
{
echo "<font color=green>Uploading file $localfile_path (file #$uploaded_file_n)..." . date("H:i:s") . "</font><br>"; ob_flush();
try
{
$object = $container->create_object($filename);
$object->load_from_filename($localfile_path);
$uploaded_file_n ++;
}
catch (Exception $e)
{
echo "<font color=red>Error! Caught exception: ", $e->getMessage(), " on uploading file <strong>$localfile_path</strong>!</font>" . date("H:i:s") . "<br>"; ob_flush();
$errors_count ++;
}
}
// if ($uploaded_file_n >= 10)
// break;
}
echo "Done! $uploaded_file_n files uploaded. Disconnecting :)" . date("H:i:s") . "<br>"; ob_flush();
echo "Skipped files: $skipped_file_n<br>"; ob_flush();
if ($errors_count > 0)
echo "<font color=red>Erorrs: $errors_count</font><br>"; ob_flush();
}
function UploadChangedImagesToRackFileCDN($b_force_upload = false)
{
$exclude = array
(
'.',
'..',
'*.html',
'*.htm',
'*.php',
'*.csv',
'*.log',
'*.txt',
'*.cfg',
//'*sub/forum/files/*',
);
$files_array_images = get_dirlist("/var/www/html/vladonai.com/images/", '*', $exclude, false);
$files_array = array_merge(get_dirlist("/var/www/html/vladonai.com/js/", '*', $exclude, false), $files_array_images);
UploadMissingFilesToRackFileCDN($files_array, $b_force_upload);
}
function get_dirlist($path, $match = '*', $exclude = array( '.', '..' ), $b_short_path = true)
{
$result = array();
if (($handle = opendir($path)))
{
while (false !== ($fname = readdir($handle)))
{
$skip = false;
if (!empty($exclude))
{
if (!is_array($exclude))
{
$skip = fnmatch($exclude, $fname) || fnmatch($exclude, $path . $fname);
} else
{
foreach ($exclude as $ex)
{
if (fnmatch($ex, $fname) || fnmatch($ex, $path . $fname))
$skip = true;
}
}
}
if (!$skip && (empty($match) || fnmatch($match, $fname)))
{
$file_full_path_and_name = $path . $fname;
//echo "$file_full_path_and_name<br>";
$b_dir = is_dir($file_full_path_and_name);
$b_link = is_link($file_full_path_and_name);
$file_size = ($b_dir || $b_link) ? 0 : filesize($file_full_path_and_name);
$file_mod_time = ($b_dir || $b_link) ? 0 : filemtime($file_full_path_and_name);
$new_result_element = array();
if ($b_short_path)
$file_name = str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name);//'[' . str_replace("/var/www/html/vladonai.com/", "", $file_full_path_and_name) . ']';
else
$file_name = $file_full_path_and_name;
$result[$file_name] = array();
$result[$file_name]['size'] = $file_size;
$result[$file_name]['modtime'] = $file_mod_time;
if ($b_dir && !$b_link)
{
//recursively enumerate files in sub-directories
$result = array_merge(get_dirlist($file_full_path_and_name . "/", $match, $exclude, $b_short_path), $result);
}
}
}
closedir($handle);
}
return $result;
}

Categories