mysql_fetch_object is very slow takes about 30 seconds to load with only 20 ROWS [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Simplest way to profile a PHP script
We are building this online application using MVC approach (but a bit tweeked).
The structure of the application goes like this.
class Page{
private $title;
private $css;
private $type;
private $formData;
private $obj;
public function __construct($type){
//this instance variable is designed to set form data which will appear on the pages
$this->formData = array();
$this->setup($type);
}
public function setTitle($var){
$this->title = 'Page : ';
$this->title .= $var;
}
public function getFormData() {
return $this->formData;
}
private function setFormData($tmpObjs) {
$finData = array();
foreach($tmpObjs as $value){
if($value == $this->obj && isset($_GET['new']))
$newValue = 'true';
else
$newValue = 'false';
$tmpData = array();
$tmpData = $value->getData($newValue);
$finData = array_merge($finData, $tmpData);
}
return $finData;
}
public function getTitle(){
return $this->title;
}
public function displayCSS($_SESSION){
$GlobalConfig = $_SESSION['Config'];
$CSS = array();
$CSS = $GlobalConfig->getCSS();
$SIZE = count($CSS);
foreach($CSS as $key => $value){
echo "<link href=\"".$CSS[$key]."\" type=\"text/css\" rel=\"stylesheet\" />\n";
}
}
public function displayJS($_SESSION){
$GlobalConfig = $_SESSION['Config'];
$JS = array();
$JS = $GlobalConfig->getJS();
$SIZE = count($JS);
foreach($JS as $key => $value){
echo "<script src=\"".$JS[$key]."\" type=\"text/javascript\"></script>\n";
}
}
function setPageType($type)
{
$this->type = $type;
}
// This is used when you are filtering whatever type for search function
function getPageType(){
$type = $this->type;
echo $type;
}
function setup($type){
$this->type = $type;
switch($this->type){
case "AccountExpiry":
break;
case "Home":
$CalendarExpiryItemList = new CalendarExpiryItemList();
$CalendarExpiryItemList->createList();
$_SESSION['Active_Form'] = 'homepage-record';
$this->obj = $CalendarExpiryItemList;
$objs = array($CalendarExpiryItemList);
$this->formData = $this->setFormData($objs);
$this->setTitle('Home');
break;
}
}
function generateJS(){
if(file_exists('../classes/Javascript.class.php'))
include_once '../classes/Javascript.class.php';
$JSType = str_replace(" " , "", ucwords(str_replace("-", " ", substr(end(explode("/", $_GET['page'])), 0, -4))));
$JSType = $_GET['page'];
if(substr($JSType, -1) == 's')
$JSType = substr ($JSType, 0, -1);
echo $JSType;
$new_obj_name = $JSType . "JS";
$jsObj = new $new_obj_name($this->type);
}
function getObject(){
return $this->obj;
}
//There is more code, file has been omitted for forum
}
The following is the CalendarExpiryItemList class
class CalendarExpiryItemList
{
private $List = array();
public function __construct()
{
//Nothing To Do Yet
}
public function createList($Type = "Followups")
{
switch($Type)
{
case "ALL":
$this->List = array();
$this->getAllItemsInArray();
return $this->List;
break;
case "Invoice":
$this->List = array();
$this->getInvoiceCalendarItems();
return $this->List;
break;
case "Followups":
$this->List = array();
$this->getFollowUpExpiryItems();
return $this->List;
break;
}
}
public function _compare($m, $n)
{
if (strtotime($m->getExpiryDate()) == strtotime($n->getExpiryDate()))
{
return 0;
}
$value = (strtotime($m->getExpiryDate()) < strtotime($n->getExpiryDate())) ? -1 : 1;
echo "This is the comparison value" . $value. "<br/>";
return $value;
}
public function display()
{
foreach($this->List as $CalendarItem)
{
echo "<tr>";
if($CalendarItem->getType() != "ContractorInsurance")
echo "<td>".DateFormat::toAus($CalendarItem->getExpiryDate())."</td>";
else
echo "<td>".$CalendarItem->getExpiryDate()."</td>";
echo "<td>".$CalendarItem->getType()."</td>";
echo "<td>".$CalendarItem->getDescription()."</td>";
echo "<td>".$CalendarItem->doAction()."</td>";
echo "</tr>";
}
}
public function getData()
{
$data = array();
$data['Rows'] = "";
$TempArray1 = array();
foreach($this->List as $CalendarItem)
{
$Temp = "";
$Temp .= "<tr>";
if($CalendarItem->getType() != "ContractorInsurance")
$Temp .= "<td>".DateFormat::toAus($CalendarItem->getExpiryDate())."</td>";
else
$Temp .= "<td>".$CalendarItem->getExpiryDate()."</td>";
$Temp .= "<td>".$CalendarItem->getType()."</td>";
$Temp .= "<td>".$CalendarItem->getDescription()."</td>";
$Temp .= "<td>".$CalendarItem->doAction()."</td>";
$Temp .= "</tr>";
$TempArray1[] = $Temp;
}
if(count($TempArray1) == 0)
{
$Row = "<tr><td colspan='4'>No Items overdue</td></tr>";
$TempArray1[] = $Row;
}
$data['Rows'] = $TempArray1;
return $data;
}
//---------------Private Functions----------------
private function SortArrayDate()
{
$TempArray = array();
$TempArray = $this->List;
$this->List = array();
foreach($TempArray as $CalendarItem)
{
$this->List[$CalendarItem->getExpiryDate()] = $CalendarItem;
}
ksort($this->List);
}
private function getAllItemsInArray()
{
$this->getInvoiceCalendarItems();
$this->getFollowUpExpiryItems();
$this->getProjectExpiryItems();
$this->getVehicleExpiryItems();
$this->getUserInsuranceExpiryItems();
$this->getContractorExpiryItems();
//$this->SortArrayDate();
}
private function getContractorExpiryItems()
{
$SQL = "SELECT * FROM `contractor_Details` WHERE `owner_id` =".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$InsLic = new ContractorInsLis();
$InsLic->getContractorInsLisById($row->contractor_id);
if($InsLic->CheckExpiry($InsLic->getwcic_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getwcic_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Workers Comp License expired on ".$InsLic->getwcic_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getpli_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getpli_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Public Liability Insurance expired on ".$InsLic->getpli_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getcontractor_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getcontractor_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Contractor License expired on ".$InsLic->getcontractor_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getwcic_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getcompany_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Company License expired on ".$InsLic->getcompany_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
}
}
private function getUserInsuranceExpiryItems()
{
$SQL = "SELECT * FROM `user_my_insurances_licences` WHERE `user_id`=".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$UserInsuranceLicenses = new UserMyLicenseInsurance();
if($UserInsuranceLicenses->CheckExpiry($row->DL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->DL_expiry_date,"DL #".$row->DL_number." has expired on ".$row->DL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->CL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->CL_expiry_date,"CL #".$row->CL_number." has expired on ".$row->CL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->BL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->BL_expiry_date,"BL #".$row->BL_number." has expired on ".$row->DL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->wcic_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->wcic_expiry_date,"Workers Compe #".$row->wcic_policy_number." has expired on ".$row->wcic_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->pli_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->pli_expiry_date,"Public Liability #".$row->pli_policy_number." has expired on ".$row->pli_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->cwi_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->cwi_expiry_date,"Contract Worker Insurance #".$row->cwi_policy_number." has expired on ".$row->cwi_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->hoi_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->hoi_expiry_date,"Home Owners Insurance #".$row->hoi_policy_number." has expired on ".$row->hoi_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->pii_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->pii_expiry_date,"Professional Indemnity Owners Insurance #".$row->pii_policy_number." has expired on ".$row->pii_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->tic_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->tic_expiry_date,"Tools Insurance #".$row->tic_policy_number." has expired on ".$row->tic_expiry_date);
$this->List[] = $ExpiredItem;
}
}
}
private function getVehicleExpiryItems()
{
$SQL = "SELECT * FROM `user_my_motor_vehicles` WHERE `user_id` =".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$UserMotorVehicles = new UserMotorVehicles();
if($UserMotorVehicles->CheckExpiry($row->vehicle_registration_expiry_date) == 'Expired')
{
$VehicleRegistration = new VehicleExpiryItem($row->id,$row->vehicle_registration_expiry_date,"Vehicle ".$row->vehicle_reg_no." Registration Expired on ".$row->vehicle_registration_expiry_date);
$this->List[] = $VehicleRegistration;
}
if($UserMotorVehicles->CheckExpiry($row->insurance_expiry_date) == 'Expired')
{
$VehicleInsurance = new VehicleExpiryItem($row->id,$row->insurance_expiry_date,"Vehicle ".$row->vehicle_reg_no." Insurace Expired on ".$row->insurance_expiry_date);
$this->List[] = $VehicleInsurance;
}
}
}
private function getProjectExpiryItems()
{
$SQL = "SELECT * FROM my_project WHERE user_id =".$_SESSION['user_id']." AND ((end_date < '".date('Y-m-d')."') OR (end_date = '".date('Y-m-d')."') OR end_date='0000-00-00') AND (actual_end_date = '' OR actual_end_date = ' ' OR actual_end_date = '0000-00-00')";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Project = new ProjectExpiryItem($row->project_id,$row->end_date,"Project ".$row->project_name." was due on ".$row->end_date,$row->start_date);
$this->List[] = $Project;
}
}
private function getInvoiceCalendarItems()
{
$SQL = "SELECT * FROM project_invoices WHERE (dueDate < '".date('Y-m-d')."') AND (date_paid ='0000-00-00' OR date_paid='') AND (user_id = ".$_SESSION['user_id'].") LIMIT 0, 10";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Invoice = new InvoiceExpiryItem($row->id,$row->invoice_date,"Invoice #".$row->id." is overdue.");
//testObj(array($Invoice));
$this->List[] = $Invoice;
}
}
private function getFollowUpExpiryItems()
{
$SQL = "SELECT * from followUps WHERE owner_id=".$_SESSION['user_id']." AND ((Date_Due < '".date('Y-m-d')."') OR (Date_Due = '".date('Y-m-d')."') OR (Date_Due = '0000-00-00')) AND Completed != '1'";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Form_Id = new FormId();
$Description = "Follow Up on ".$Form_Id->getFormNam($row->Form_id)." was due on ".$row->Date_Due;
$FollowUp = new FollowUpExpiryItem($row->Id,$row->Date_Due,$Description);
$this->List[] = $FollowUp;
}
}
This is the pagination Class
<?php
class Pagination {
protected $Items = array();
protected $Type = "default";
protected $Title = "List of ";
protected $Base_Url = "";
protected $Table;
//-------------------------Table Settings----------------//
protected $No_Of_Columns = NULL;
protected $No_Of_Items_Per_Page = 10; //By Default 10 items will be displayed on a page.protected
protected $Present_Page = 0;
protected $Columns = array();
protected $Rows = array();
//------------------------Table Class Attributes---------//
protected $Table_Class = "";
protected $Table_Id = "";
protected $GETVarName = "PP";
/**
*
*/
public function __construct()
{
$this->Table = false;
}
public function paginate()
{
//Check if the base url is set
if(strlen($this->Base_Url) == 0){
echo "Error: Could not paginate, No base url Found!";
}
//Set the Current page value to Present Page
if(isset($_GET))
{
if(isset($_GET[$this->GETVarName])){
$this->Present_Page = intval($_GET[$this->GETVarName]);
} else {
$this->Present_Page = 1;
}
}
//Draw the table and the values
$this->generatePaginationTable();
}
public function setData($data)
{
if(is_array($data)){
$this->Rows = $data;
return true;
} else {
return false;
}
}
public function putData($object,$functionName = "generateRow")
{
$TempData = array();
if(method_exists($object,"getObjs"))
{
$ObjectArray = $object->getObjs();
}
if(method_exists($object,$functionName))
{
foreach($ObjectArray as $Obj)
{
$TempData[] = $object->$functionName($Obj);
}
}
$this->setData($TempData);
unset($TempData);
}
public function setIsTable($val)
{
$this->IsTable = $val;
}
public function addColumnNames($Col){
if(is_array($Col)){
$this->No_Of_Columns = $Col;
} else {
return false;
}
}
/**
* #param $config (array)
* #return bool
*
* this function initializes the Pagination object with the
* initial values
*/
public function initialize($config)
{
if(is_array($config))
{
foreach($config as $key => $value)
{
if(isset($this->$key))
{
$this->$key = $value;
}
}
} else if(is_object($config)) {
return false;
} else if(is_string($config)){
return false;
}
}
//------------------------------Private Function For the Class-------------------------//
private function generatePaginationTable()
{
if($this->Table){
$this->StartTable();
$this->DisplayHeader();
}
$this->DisplayData();
$this->DisplayLinks();
if($this->Table)
echo "</table>";
}
private function DisplayLinks()
{
if($this->Table){
echo "<tr>";
echo '<td colspan="'. count($this->Rows) .'">';
$this->GenerateLinkCounting();
echo '</td>';
echo "</tr>";
} else {
if(count($this->Rows) > 0)
{
$ROW = $this->Rows[0];
$ColSpan = substr_count($ROW,"<td");
echo "<tr>";
echo '<td colspan="'. $ColSpan .'" align="right">';
$this->GenerateLinkCounting();
echo '</td>';
echo "</tr>";
}
}
}
private function GenerateLinkCounting()
{
$this->Base_Url .= $this->getOtherGetVar();
$StartCount = 1;
$EndCount = count($this->Rows) / $this->No_Of_Items_Per_Page;
for($i=0; $i < $EndCount; $i++)
{
if($i == 0)
{
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1). '" >First</a> ';
} else if($i == intval($EndCount)){
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1).'" >Last</a> ';
} else {
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1). '" >'.intval($i+1).'</a> ';
}
}
}
private function getOtherGetVar()
{
$Link = "";
if(isset($_GET))
{
foreach($_GET as $key => $val)
{
if($key != $this->GETVarName)
{
$Link .= "&".$key."=".$val;
}
}
}
$h = preg_split("/&/",$this->Base_Url);
$this->Base_Url = $h[0];
return $Link;
}
private function DisplayData()
{
$Index = 0;
$StartIndex = intval(intval($this->Present_Page-1) * $this->No_Of_Items_Per_Page);
$EndIndex = intval($StartIndex + $this->No_Of_Items_Per_Page);
foreach($this->Rows as $Row)
{
$Index++;
if($Index >= $StartIndex && $Index <= $EndIndex)
{
echo "<tr>";
if(is_array($Row))
{
foreach($Row as $key => $value){
echo "<td>".$value."</td>";
}
} else {
echo $Row;
}
echo "</tr>";
}
}
}
private function DisplayHeader()
{
if(is_array($this->Columns))
{
echo "<thead>";
echo "<tr>";
foreach($this->Columns as $Col => $value)
{
echo "<td>".$value."</td>";
}
echo "</tr>";
echo "</thead>";
}
}
private function StartTable()
{
echo "<table ";
if(strlen($this->Table_Class) > 0)
echo 'class="'.$this->Table_Class.'" ';
if(strlen($this->Table_Id) > 0)
echo 'id="'.$this->Table_Id.'" ';
echo ">";
}
}
Final Implementation of the File
<?php
$Page = new Page('Home');
$data = $Page->getFormData();
$Pagination = new Pagination();
$config = array();
$config['Table'] = false;
$config['No_Of_Items_Per_Page'] = 25;
$config['Base_Url'] = base_url() . 'BootLoader.php?page=Homepage';
$config['GETVarName'] = "ODL";
$Pagination->initialize($config);
$Pagination->setData($data['Rows']);
/**
* Want to have multiple lists
*/
$CalendarExpiryList = $Page->getObject();
$CalendarExpiryList->createList("Invoice");
$InvoiceList = new Pagination();
$config = array();
$config['Table'] = false;
$config['No_Of_Items_Per_Page'] = 25;
$config['Base_Url'] = base_url() . 'BootLoader.php?page=Homepage';
$config['GETVarName'] = "OIDL";
$InvoiceList->initialize($config);
$data2 = $CalendarExpiryList->getData();
$InvoiceList->setData($data2['Rows']);
//This is the display
include_once("Forms/homepage/home-page.html.php");
?>
The PHP Script runs fine. It takes about 0.03 to load.
But when the script reaches the CalendarExpiryItemList class. It takes about 30 seconds and my server times out.
Each table would have around 12 to 15 fields on an average and about 10 to 100 records to go through.
I am on hosting with a hosting company they have load balancers. So if my scripts takes more than 30 seconds the load balancer resets my connection and return an error saying "Server sent no data"

As the others say you should try profile your code.
...without being able to debug the code, maybe one or more of the methods in CalendarExpiryItemList class is failing at some point either; on the query, or associated query, or returning a endless loop. You should test and debug each method individually on a your test server to see what results your getting. For a quick and dirty test, just log the output of each method to a file. Also check $_SESSION['user_id'] has a value and use ". (int) $_SESSION['user_id'] as well before sending it the db in case its empty because its not escaped.

Related

Echo specific field from rsform in directory view

my first post here after actively using the site for ages.
I am trying to set up a directory view through RSFORM on my company intranet site. Everything is done, but in directory view i would like to echo the value of one selector in the form (the selector is hidden in the form, and viewable in edit). So when you edit this selector after form submission, it will echo this value to a spesific area of the directory (adds it to class for the whole row).
But I cant figure out how to get spesific field values..
I tried this
echo $this->$field(FIELD_NAME);
The code section is like this
<?php if ($this->items) { ?>
<?php foreach ($this->items as $i => $item) { ?>
<tr class="row<?php echo $i % 2; ?> directoryRow **<?php echo $this->$field(FIELD_NAME); ?>**">
<?php if ($this->directory->enablecsv) { ?>
<td align="center" class="center directoryGrid"><?php echo JHtml::_('grid.id', $i, $item->SubmissionId); ?></td>
<?php } ?>
<?php foreach ($this->viewableFields as $field) { ?>
<td align="center" class="center directoryCol directoryCol<?php echo $this->getFilteredName($field->FieldName); ?>"><?php echo $this->getValue($item, $field); ?></td>
<?php } ?>
This is from the view.html.php file
<?php
defined('_JEXEC') or die('Restricted access');
class RSFormViewDirectory extends JViewLegacy
{
public function display( $tpl = null ) {
$this->app = JFactory::getApplication();
$this->doc = JFactory::getDocument();
$this->document = &$this->doc;
$this->params = $this->app->getParams('com_rsform');
$this->layout = $this->getLayout();
$this->directory = $this->get('Directory');
$this->tooltipClass = RSFormProHelper::getTooltipClass();
if ($this->layout == 'view') {
$this->doc->addStyleSheet(JHtml::stylesheet('com_rsform/directory.css', array(), true, true));
$this->template = $this->get('template');
$this->canEdit = RSFormProHelper::canEdit($this->params->get('formId'),$this->app->input->getInt('id',0));
$this->id = $this->app->input->getInt('id',0);
// Add custom CSS and JS
if ($this->directory->JS)
$this->doc->addCustomTag($this->directory->JS);
if ($this->directory->CSS)
$this->doc->addCustomTag($this->directory->CSS);
// Add pathway
$this->app->getPathway()->addItem(JText::_('RSFP_SUBM_DIR_VIEW'), '');
} elseif ($this->layout == 'edit') {
if (RSFormProHelper::canEdit($this->params->get('formId'),$this->app->input->getInt('id',0))) {
$this->doc->addStyleSheet(JHtml::stylesheet('com_rsform/directory.css', array(), true, true));
$this->fields = $this->get('EditFields');
} else {
$this->app->redirect(JURI::root());
}
// Add pathway
$this->app->getPathway()->addItem(JText::_('RSFP_SUBM_DIR_EDIT'), '');
} else {
$this->search = $this->get('Search');
$this->items = $this->get('Items');
$this->uploadFields = $this->get('uploadFields');
$this->multipleFields = $this->get('multipleFields');
$this->unescapedFields = array_merge($this->multipleFields, $this->uploadFields);
$this->fields = $this->get('Fields');
$this->headers = RSFormProHelper::getDirectoryStaticHeaders();
$this->hasDetailFields = $this->hasDetailFields();
$this->hasSearchFields = $this->hasSearchFields();
$this->viewableFields = $this->getViewableFields();
$this->pagination = $this->get('Pagination');
$this->filter_search = $this->get('Search');
$this->filter_order = $this->get('ListOrder');
$this->filter_order_Dir = $this->get('ListDirn');
// Add custom CSS and JS
if ($this->directory->JS)
$this->doc->addCustomTag($this->directory->JS);
if ($this->directory->CSS)
$this->doc->addCustomTag($this->directory->CSS);
}
if ($this->params->get('robots')) {
$this->document->setMetadata('robots', $this->params->get('robots'));
}
if ($this->params->get('menu-meta_description')) {
$this->document->setDescription($this->params->get('menu-meta_description'));
}
if ($this->params->get('menu-meta_keywords')) {
$this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords'));
}
$title = $this->params->get('page_title', '');
if (empty($title)) {
$title = JFactory::getConfig()->get('sitename');
}
elseif (JFactory::getConfig()->get('sitename_pagetitles', 0) == 1) {
$title = JText::sprintf('JPAGETITLE', JFactory::getConfig()->get('sitename'), $title);
}
elseif (JFactory::getConfig()->get('sitename_pagetitles', 0) == 2) {
$title = JText::sprintf('JPAGETITLE', $title, JFactory::getConfig()->get('sitename'));
}
$this->document->setTitle($title);
parent::display($tpl);
}
protected function hasDetailFields() {
foreach ($this->fields as $field) {
if ($field->indetails) {
return true;
}
}
}
protected function hasSearchFields() {
foreach ($this->fields as $field) {
if ($field->searchable) {
return true;
}
}
}
protected function getViewableFields() {
$return = array();
foreach ($this->fields as $field) {
if ($field->viewable) {
$return[] = $field;
}
}
return $return;
}
protected function getFilteredName($name) {
return ucfirst(JFilterOutput::stringURLSafe($name));
}
protected function getValue($item, $field) {
if (in_array($field->FieldName, $this->unescapedFields)) {
return $item->{$field->FieldName};
} else {
// Static header?
if ($field->componentId < 0 && isset($this->headers[$field->componentId])) {
$header = $this->headers[$field->componentId];
if ($header == 'DateSubmitted') {
$value = RSFormProHelper::getDate($item->$header);
} else {
$value = $item->$header;
}
} else {
// Dynamic header.
$value = $item->{$field->FieldName};
}
return $this->escape($value);
}
}
public function pdfLink($id) {
$app = JFactory::getApplication();
$has_suffix = JFactory::getConfig()->get('sef') && JFactory::getConfig()->get('sef_suffix');
$pdf_link = JRoute::_('index.php?option=com_rsform&view=directory&layout=view&id='.$id.'&format=pdf');
if ($has_suffix) {
$pdf_link .= strpos($pdf_link, '?') === false ? '?' : '&';
$pdf_link .= 'format=pdf';
}
return $pdf_link;
}
}

Amazon Scraper Script works on XAMPP Windows but not PHP5 Cli on Linux

I'm trying to scrape Amazon ASIN codes using the below code:
<?php
class Scraper {
const BASE_URL = "http://www.amazon.com";
private $categoryFile = "";
private $outputFile = "";
private $catArray;
private $currentPage = NULL;
private $asin = array();
private $categoriesMatched = 0;
private $categoryProducts = array();
private $pagesMatched = 0;
private $totalPagesMatched = 0;
private $productsMatched = 0;
public function __construct($categoryFile, $outputFile) {
$this->categoryFile = $categoryFile;
$this->outputFile = $outputFile;
}
public function run() {
$this->readCategories($this->categoryFile);
$this->setupASINArray($this->asin);
$x = 1;
foreach ($this->catArray as $cat) {
$this->categoryProducts["$x"] = 0;
if ($this->currentPage == NULL) {
$this->currentPage = $cat;
$this->scrapeASIN($this->currentPage, $x);
$this->pagesMatched++;
}
if ($this->getNextPageLink($this->currentPage)) {
do {
// next page found
$this->pagesMatched++;
$this->scrapeASIN($this->currentPage, $x);
} while ($this->getNextPageLink($this->currentPage));
}
echo "Category complete: $this->pagesMatched Pages" . "\n";
$this->totalPagesMatched += $this->pagesMatched;
$this->pagesMatched = 0;
$this->writeASIN($this->outputFile, $x);
$x++;
$this->currentPage = NULL;
$this->categoriesMatched++;
}
$this->returnStats();
}
private function readCategories($categoryFile) {
$catArray = file($categoryFile, FILE_IGNORE_NEW_LINES);
$this->catArray = $catArray;
}
private function setupASINArray($asinArray) {
$x = 0;
foreach ($this->catArray as $cat) {
$asinArray["$x"][0] = "$cat";
$x++;
}
$this->asin = $asinArray;
}
private function getNextPageLink($currentPage) {
$document = new DOMDocument();
$html = file_get_contents($currentPage);
#$document->loadHTML($html);
$xpath = new DOMXPath($document);
$element = $xpath->query("//a[#id='pagnNextLink']/#href");
if ($element->length != 0) {
$this->currentPage = self::BASE_URL . $element->item(0)->value;
return true;
} else {
return false;
}
}
private function scrapeASIN($currentPage, $catNo) {
$html = file_get_contents($currentPage);
$regex = '~(?:www\.)?ama?zo?n\.(?:com|ca|co\.uk|co\.jp|de|fr)/(?:exec/obidos/ASIN/|o/|gp/product/|(?:(?:[^"\'/]*)/)?dp/|)(B[A-Z0-9]{9})(?:(?:/|\?|\#)(?:[^"\'\s]*))?~isx';
preg_match_all($regex, $html, $asin);
foreach ($asin[1] as $match) {
$this->asin[$catNo-1][] = $match;
}
}
private function writeASIN($outputFile, $catNo) {
$fh = fopen($outputFile, "a+");
$this->fixDupes($catNo);
$this->productsMatched += (count($this->asin[$catNo-1]) - 1);
$this->categoryProducts["$catNo"] = (count($this->asin[$catNo-1]) - 1);
flock($fh, LOCK_EX);
$x = 0;
foreach ($this->asin[$catNo-1] as $asin) {
fwrite($fh, "$asin" . "\n");
$x++;
}
flock($fh, LOCK_UN);
fclose($fh);
$x -= 1;
echo "$x ASIN codes written to file" . "\n";
}
private function fixDupes($catNo) {
$this->asin[$catNo-1] = array_unique($this->asin[$catNo-1], SORT_STRING);
}
public function returnStats() {
echo "Categories matched: " . $this->categoriesMatched . "\n";
echo "Pages parsed: " . $this->totalPagesMatched . "\n";
echo "Products parsed: " . $this->productsMatched . "\n";
echo "Category breakdown:" . "\n";
$x = 1;
foreach ($this->categoryProducts as $catProds) {
echo "Category $x had $catProds products" . "\n";
$x++;
}
}
}
$scraper = new Scraper($argv[1], $argv[2]);
$scraper->run();
?>
But it works fine on XAMPP on Windows but not on Linux. Any ideas as to why this may be? Sometimes it scrapes 0 ASIN's to file, sometimes it only scrapes 1 page in a category of 400+ pages. But the output/functionality is totally fine in Windows/XAMPP.
Any thoughts would be greatly appreciated!
Cheers
- Bryce
So try to change this way, just to avoid the error messages:
private function readCategories($categoryFile) {
if (file_exists($categoryFile)) {
$catArray = file($categoryFile, FILE_IGNORE_NEW_LINES);
$this->catArray = $catArray;
} else {
echo "File ".$categoryFile.' not exists!';
$this->catArray = array();
}
}

PHP Simple object oriented application

I am getting undefined variable for periods and subPeriods on the last line of this program. not sure what the problem is. Could it be my instances?
This is my first proper attempt at oop in PHP so i am sure i am doing something wrong.
$global_periods = 5;
$global_subperiods = 2;
$questionslist = array("q_1_1", "q_1_2", "q_2_1", "q_2_2", "q_3_1", "q_4_1", "q_5_1");
class User {
public $userId;
public $periods = array();
public function __construct($number)
{
$this->userId = $number;
}
public function addPeriod($pno)
{
$periods[] = new Period($pno);
}
}
class Period {
public $periodNo;
public $subPeriods = array();
public function __construct($number)
{
$this->periodNo = $number;
}
public function addSubPeriod($spno)
{
$subPeriods[] = new SubPeriod($spno);
}
}
class SubPeriod {
public $SubPeriodNo;
public $answers = array();
public function __construct($number)
{
$this->SubPeriodNo = $number;
}
public function addAnswer($answer)
{
$answers[] = new Answer($answer);
}
}
class Question {
public $answer;
public function __construct($ans)
{
$this->answer = $ans;
}
public function getAnswer()
{
echo $answer;
}
}
$userlist = array();
$sql = 'SELECT user_ref FROM _survey_1_as GROUP BY user_ref ORDER BY user_ref ASC';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[] = new User($row['user_ref']);
}
for ($i = 0; $i >= count($userlist); $i++)
{
for ($x = 1; $x > $global_periods; $x++)
{
$userlist[i]->addPeriod($x);
for ($y = 1; $y > $global_subperiods; $y++)
{
$userlist[i]->$periods[x]->addSubPeriod($y);
foreach($questionslist as $aquestion)
{
$sql = 'SELECT ' . $questionNumber . ' FROM _survey_1_as WHERE user_ref = ' .
$i . ' AND answer_sub_period = ' . $y . ' AND answer_period = ' . $x .'';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[i]->$periods[x]->$subPeriods[y]->addAnswer($row[$questionNumber]);
}
}
}
}
}
$userlist[3]->$periods[2]->$subPeriods[2]->getAnswer();
Remove all the $ signs behind the $userlist, you only need to define the first variable. You can't use dollar signs like this, this way, it will try get the value of the word after the $ sign and call that, but that variable doesn't exist.

php imap - get body and make plain text

I am using the PHP imap function to get emails from a POP3 mailbox and insert the data into a MySQL database.
Here is the PHP code:
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails)
{
$output = '';
rsort($emails);
foreach($emails as $email_number)
{
$header=imap_headerinfo($inbox,$email_number);
$from = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$toaddress=$header->toaddress;
$replyto=$header->reply_to[0]->mailbox."#".$header->reply_to[0]->host;
$datetime=date("Y-m-d H:i:s",$header->udate);
$subject=$header->subject;
//remove the " from the $toaddress
$toaddress = str_replace('"','',$toaddress);
echo '<strong>To:</strong> '.$toaddress.'<br>';
echo '<strong>From:</strong> '.$from.'<br>';
echo '<strong>Subject:</strong> '.$subject.'<br>';
//get message body
$message = (imap_fetchbody($inbox,$email_number,1.1));
if($message == '')
{
$message = (imap_fetchbody($inbox,$email_number,1));
}
}
It works fine, however on some emails in the body I get = in between words, or =20 in between words. And other times the emails will just be blank even though they are not blank when sent.
This only happens when coming from certain emails.
How can I get round this and just make the email completely plain text?
This happens because the emails are normally Quoted-printable encoded. The = is a soft line break and =20 is a white space. I think, you could use quoted_printable_decode() on the message so it shows correctly. About the blank emails, I don't know, I would need more details.
Basically:
//get message body
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1.1));
$data = imap_fetchbody($this->imapStream, $Part->uid, $Part->path, FT_UID | FT_PEEK);
if ($Part->format === 'quoted-printable' && $data) {
$data = quoted_printable_decode($data);
}
This is required for mails with
Content-Transfer-Encoding: quoted-printable
But for mails with
Content-Transfer-Encoding: 8bit
simply imap_fetchbody is enough.
Above code was taken from a cake-php component created for fetching mails from mail boxes throgh IMAP.
I made an entire class some years ago, and I'm still using it when I need to get contents from emails. It will help you fetch all email bodies (sometimes you have html and plain text) in a readable format, and get all attached files, just ready to be saved somewhere or sent to a website user.
It is not really optimized so on a big mailbox you may have troubles; but the purpose of this class was to access emails in a readable format to put them on a widget of a website. I let you play with the sample below to get how it works.
ImapReader.class.php Here is the source code.
<?php
class ImapReader
{
private $host;
private $port;
private $user;
private $pass;
private $box;
private $box_list;
private $errors;
private $connected;
private $list;
private $deleted;
const FROM = 0;
const TO = 1;
const REPLY_TO = 2;
const SUBJECT = 3;
const CONTENT = 4;
const ATTACHMENT = 5;
public function __construct($host = null, $port = '143', $user = null, $pass = null)
{
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->pass = $pass;
$this->box = null;
$this->box_list = null;
$this->errors = array ();
$this->connected = false;
$this->list = null;
$this->deleted = false;
}
public function __destruct()
{
if ($this->isConnected())
{
$this->disconnect();
}
}
public function changeServer($host = null, $port = '143', $user = null, $pass = null)
{
if ($this->isConnected())
{
$this->disconnect();
}
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->pass = $pass;
$this->box_list = null;
$this->errors = array ();
$this->list = null;
return $this;
}
public function canConnect()
{
return (($this->connected == false) && (is_string($this->host)) && (!empty($this->host))
&& (is_numeric($this->port)) && ($this->port >= 1) && ($this->port <= 65535)
&& (is_string($this->user)) && (!empty($this->user)) && (is_string($this->pass)) && (!empty($this->pass)));
}
public function connect()
{
if ($this->canConnect())
{
$this->box = #imap_open("{{$this->host}:{$this->port}/imap/ssl/novalidate-cert}INBOX", $this->user,
$this->pass);
if ($this->box !== false)
{
$this->_connected();
}
else
{
$this->errors = array_merge($this->errors, imap_errors());
}
}
return $this;
}
public function boxList()
{
if (is_null($this->box_list))
{
$list = imap_getsubscribed($this->box, "{{$this->host}:{$this->port}}", "*");
$this->box_list = array ();
foreach ($list as $box)
{
$this->box_list[] = $box->name;
}
}
return $this->box_list;
}
public function fetchAllHeaders($mbox)
{
if ($this->isConnected())
{
$test = imap_reopen($this->box, "{$mbox}");
if (!$test)
{
return false;
}
$num_msgs = imap_num_msg($this->box);
$this->list = array ();
for ($id = 1; ($id <= $num_msgs); $id++)
{
$this->list[] = $this->_fetchHeader($mbox, $id);
}
return true;
}
return false;
}
public function fetchSearchHeaders($mbox, $criteria)
{
if ($this->isConnected())
{
$test = imap_reopen($this->box, "{$mbox}");
if (!$test)
{
return false;
}
$msgs = imap_search($this->box, $criteria);
if ($msgs)
{
foreach ($msgs as $id)
{
$this->list[] = $this->_fetchHeader($mbox, $id);
}
}
return true;
}
return false;
}
public function isConnected()
{
return $this->connected;
}
public function disconnect()
{
if ($this->connected)
{
if ($this->deleted)
{
imap_expunge($this->box);
$this->deleted = false;
}
imap_close($this->box);
$this->connected = false;
$this->box = null;
}
return $this;
}
/**
* Took from khigashi dot oang at gmail dot com at php.net
* with replacement of ereg family functions by preg's ones.
*
* #param string $str
* #return string
*/
private function _fix($str)
{
if (preg_match("/=\?.{0,}\?[Bb]\?/", $str))
{
$str = preg_split("/=\?.{0,}\?[Bb]\?/", $str);
while (list($key, $value) = each($str))
{
if (preg_match("/\?=/", $value))
{
$arrTemp = preg_split("/\?=/", $value);
$arrTemp[0] = base64_decode($arrTemp[0]);
$str[$key] = join("", $arrTemp);
}
}
$str = join("", $str);
}
if (preg_match("/=\?.{0,}\?Q\?/", $str))
{
$str = quoted_printable_decode($str);
$str = preg_replace("/=\?.{0,}\?[Qq]\?/", "", $str);
$str = preg_replace("/\?=/", "", $str);
}
return trim($str);
}
private function _connected()
{
$this->connected = true;
return $this;
}
public function getErrors()
{
$errors = $this->errors;
$this->errors = array ();
return $errors;
}
public function count()
{
if (is_null($this->list))
{
return 0;
}
return count($this->list);
}
public function get($nbr = null)
{
if (is_null($nbr))
{
return $this->list;
}
if ((is_array($this->list)) && (isset($this->list[$nbr])))
{
return $this->list[$nbr];
}
return null;
}
public function fetch($nbr = null)
{
return $this->_callById('_fetch', $nbr);
}
private function _fetchHeader($mbox, $id)
{
$header = imap_header($this->box, $id);
if (!is_object($header))
{
return;
}
$mail = new stdClass();
$mail->id = $id;
$mail->mbox = $mbox;
$mail->timestamp = (isset($header->udate)) ? ($header->udate) : ('');
$mail->date = date("d/m/Y H:i:s", (isset($header->udate)) ? ($header->udate) : (''));
$mail->from = $this->_fix(isset($header->fromaddress) ? ($header->fromaddress) : (''));
$mail->to = $this->_fix(isset($header->toaddress) ? ($header->toaddress) : (''));
$mail->reply_to = $this->_fix(isset($header->reply_toaddress) ? ($header->reply_toaddress) : (''));
$mail->subject = $this->_fix(isset($header->subject) ? ($header->subject) : (''));
$mail->content = array ();
$mail->attachments = array ();
$mail->deleted = false;
return $mail;
}
private function _fetch($mail)
{
$test = imap_reopen($this->box, "{$mail->mbox}");
if (!$test)
{
return $mail;
}
$structure = imap_fetchstructure($this->box, $mail->id);
if ((!isset($structure->parts)) || (!is_array($structure->parts)))
{
$body = imap_body($this->box, $mail->id);
$content = new stdClass();
$content->type = 'content';
$content->mime = $this->_fetchType($structure);
$content->charset = $this->_fetchParameter($structure->parameters, 'charset');
$content->data = $this->_decode($body, $structure->type);
$content->size = strlen($content->data);
$mail->content[] = $content;
return $mail;
}
else
{
$parts = $this->_fetchPartsStructureRoot($mail, $structure);
foreach ($parts as $part)
{
$content = new stdClass();
$content->type = null;
$content->data = null;
$content->mime = $this->_fetchType($part->data);
if ((isset($part->data->disposition))
&& ((strcmp('attachment', $part->data->disposition) == 0)
|| (strcmp('inline', $part->data->disposition) == 0)))
{
$content->type = $part->data->disposition;
$content->name = null;
if (isset($part->data->dparameters))
{
$content->name = $this->_fetchParameter($part->data->dparameters, 'filename');
}
if (is_null($content->name))
{
if (isset($part->data->parameters))
{
$content->name = $this->_fetchParameter($part->data->parameters, 'name');
}
}
$mail->attachments[] = $content;
}
else if ($part->data->type == 0)
{
$content->type = 'content';
$content->charset = null;
if (isset($part->data->parameters))
{
$content->charset = $this->_fetchParameter($part->data->parameters, 'charset');
}
$mail->content[] = $content;
}
$body = imap_fetchbody($this->box, $mail->id, $part->no);
if (isset($part->data->encoding))
{
$content->data = $this->_decode($body, $part->data->encoding);
}
else
{
$content->data = $body;
}
$content->size = strlen($content->data);
}
}
return $mail;
}
private function _fetchPartsStructureRoot($mail, $structure)
{
$parts = array ();
if ((isset($structure->parts)) && (is_array($structure->parts)) && (count($structure->parts) > 0))
{
foreach ($structure->parts as $key => $data)
{
$this->_fetchPartsStructure($mail, $data, ($key + 1), $parts);
}
}
return $parts;
}
private function _fetchPartsStructure($mail, $structure, $prefix, &$parts)
{
if ((isset($structure->parts)) && (is_array($structure->parts)) && (count($structure->parts) > 0))
{
foreach ($structure->parts as $key => $data)
{
$this->_fetchPartsStructure($mail, $data, $prefix . "." . ($key + 1), $parts);
}
}
$part = new stdClass;
$part->no = $prefix;
$part->data = $structure;
$parts[] = $part;
}
private function _fetchParameter($parameters, $key)
{
foreach ($parameters as $parameter)
{
if (strcmp($key, $parameter->attribute) == 0)
{
return $parameter->value;
}
}
return null;
}
private function _fetchType($structure)
{
$primary_mime_type = array ("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
if ((isset($structure->subtype)) && ($structure->subtype) && (isset($structure->type)))
{
return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
}
return "TEXT/PLAIN";
}
private function _decode($message, $coding)
{
switch ($coding)
{
case 2:
$message = imap_binary($message);
break;
case 3:
$message = imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
case 5:
break;
default:
break;
}
return $message;
}
private function _callById($method, $data)
{
$callback = array ($this, $method);
// data is null
if (is_null($data))
{
$result = array ();
foreach ($this->list as $mail)
{
$result[] = $this->_callById($method, $mail);
}
return $result;
}
// data is an array
if (is_array($data))
{
$result = array ();
foreach ($data as $elem)
{
$result[] = $this->_callById($method, $elem);
}
return $result;
}
// data is an object
if ((is_object($data)) && ($data instanceof stdClass) && (isset($data->id)))
{
return call_user_func($callback, $data);
}
// data is numeric
if (($this->isConnected()) && (is_array($this->list)) && (is_numeric($data)))
{
foreach ($this->list as $mail)
{
if ($mail->id == $data)
{
return call_user_func($callback, $mail);
}
}
}
return null;
}
public function delete($nbr)
{
$this->_callById('_delete', $nbr);
return;
}
private function _delete($mail)
{
if ($mail->deleted == false)
{
$test = imap_reopen($this->box, "{$mail->mbox}");
if ($test)
{
$this->deleted = true;
imap_delete($this->box, $mail->id);
$mail->deleted = true;
}
}
}
public function searchBy($pattern, $type)
{
$result = array ();
if (is_array($this->list))
{
foreach ($this->list as $mail)
{
$match = false;
switch ($type)
{
case self::FROM:
$match = $this->_match($mail->from, $pattern);
break;
case self::TO:
$match = $this->_match($mail->to, $pattern);
break;
case self::REPLY_TO:
$match = $this->_match($mail->reply_to, $pattern);
break;
case self::SUBJECT:
$match = $this->_match($mail->subject, $pattern);
break;
case self::CONTENT:
foreach ($mail->content as $content)
{
$match = $this->_match($content->data, $pattern);
if ($match)
{
break;
}
}
break;
case self::ATTACHMENT:
foreach ($mail->attachments as $attachment)
{
$match = $this->_match($attachment->name, $pattern);
if ($match)
{
break;
}
}
break;
}
if ($match)
{
$result[] = $mail;
}
}
}
return $result;
}
private function _nmatch($string, $pattern, $a, $b)
{
if ((!isset($string[$a])) && (!isset($pattern[$b])))
{
return 1;
}
if ((isset($pattern[$b])) && ($pattern[$b] == '*'))
{
if (isset($string[$a]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), $b) + $this->_nmatch($string, $pattern, $a, ($b + 1)));
}
else
{
return ($this->_nmatch($string, $pattern, $a, ($b + 1)));
}
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($pattern[$b] == '?'))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 1)));
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($pattern[$b] == '\\'))
{
if ((isset($pattern[($b + 1)])) && ($string[$a] == $pattern[($b + 1)]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 2)));
}
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($string[$a] == $pattern[$b]))
{
return ($this->_nmatch($string, $pattern, ($a + 1), ($b + 1)));
}
return 0;
}
private function _match($string, $pattern)
{
return $this->_nmatch($string, $pattern, 0, 0);
}
}
ImapReader.demo.php Here is the usage sample
<?php
require_once("ImapReader.class.php");
$box = new ImapReader('example.com', '143', 'somebody#example.com', 'xxxxxxxxxxxx');
$box
->connect()
->fetchAllHeaders()
;
echo $box->count() . " emails in mailbox\n";
for ($i = 0; ($i < $box->count()); $i++)
{
$msg = $box->get($i);
echo "Reception date : {$msg->date}\n";
echo "From : {$msg->from}\n";
echo "To : {$msg->to}\n";
echo "Reply to : {$msg->from}\n";
echo "Subject : {$msg->subject}\n";
$msg = $box->fetch($msg);
echo "Number of readable contents : " . count($msg->content) . "\n";
foreach ($msg->content as $key => $content)
{
echo "\tContent " . ($key + 1) . " :\n";
echo "\t\tContent type : {$content->mime}\n";
echo "\t\tContent charset : {$content->charset}\n";
echo "\t\tContent size : {$content->size}\n";
}
echo "Number of attachments : " . count($msg->attachments) . "\n";
foreach ($msg->attachments as $key => $attachment)
{
echo "\tAttachment " . ($key + 1) . " :\n";
echo "\t\tAttachment type : {$attachment->type}\n";
echo "\t\tContent type : {$attachment->mime}\n";
echo "\t\tFile name : {$attachment->name}\n";
echo "\t\tFile size : {$attachment->size}\n";
}
echo "\n";
}
echo "Searching '*Bob*' ...\n";
$results = $box->searchBy('*Bob*', ImapReader::FROM);
foreach ($results as $result)
{
echo "\tMatched: {$result->from} - {$result->date} - {$result->subject}\n";
}
Enjoy
Regarding the blank emails, check the encoding of the mail.
If it is a binary encoded mail then you will get blank mails when you try to insert them into a mysql text field.
Try shifting every mail to UTF-8 and then insert it
iconv(mb_detect_encoding($mail_content, mb_detect_order(), true), "UTF-8", $mail_content);
function getmsg($mbox,$mid) {
// input $mbox = IMAP stream, $mid = message id
// output all the following:
global $charset,$htmlmsg,$plainmsg,$attachments;
$htmlmsg = $plainmsg = $charset = '';
$attachments = array();
// HEADER
$h = imap_header($mbox,$mid);
// add code here to get date, from, to, cc, subject...
// BODY
$s = imap_fetchstructure($mbox,$mid);
if (!$s->parts) // simple
getpart($mbox,$mid,$s,0); // pass 0 as part-number
else { // multipart: cycle through each part
foreach ($s->parts as $partno0=>$p)
getpart($mbox,$mid,$p,$partno0+1);
}
}
function getpart($mbox,$mid,$p,$partno) {
// $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
global $htmlmsg,$plainmsg,$charset,$attachments;
// DECODE DATA
$data = ($partno)?
imap_fetchbody($mbox,$mid,$partno): // multipart
imap_body($mbox,$mid); // simple
// Any part may be encoded, even plain text messages, so check everything.
if ($p->encoding==4)
$data = quoted_printable_decode($data);
elseif ($p->encoding==3)
$data = base64_decode($data);
// PARAMETERS
// get all parameters, like charset, filenames of attachments, etc.
$params = array();
if ($p->parameters)
foreach ($p->parameters as $x)
$params[strtolower($x->attribute)] = $x->value;
if ($p->dparameters)
foreach ($p->dparameters as $x)
$params[strtolower($x->attribute)] = $x->value;
// ATTACHMENT
// Any part with a filename is an attachment,
// so an attached text file (type 0) is not mistaken as the message.
if ($params['filename'] || $params['name']) {
// filename may be given as 'Filename' or 'Name' or both
$filename = ($params['filename'])? $params['filename'] : $params['name'];
// filename may be encoded, so see imap_mime_header_decode()
$attachments[$filename] = $data; // this is a problem if two files have same name
}
// TEXT
if ($p->type==0 && $data) {
// Messages may be split in different parts because of inline attachments,
// so append parts together with blank row.
if (strtolower($p->subtype)=='plain')
$plainmsg. = trim($data) ."\n\n";
else
$htmlmsg. = $data ."<br><br>";
$charset = $params['charset']; // assume all parts are same charset
}
// EMBEDDED MESSAGE
// Many bounce notifications embed the original message as type 2,
// but AOL uses type 1 (multipart), which is not handled here.
// There are no PHP functions to parse embedded messages,
// so this just appends the raw source to the main message.
elseif ($p->type==2 && $data) {
$plainmsg. = $data."\n\n";
}
// SUBPART RECURSION
if ($p->parts) {
foreach ($p->parts as $partno0=>$p2)
getpart($mbox,$mid,$p2,$partno.'.'.($partno0+1)); // 1.2, 1.2.1, etc.
}
}
Reference (First user contributed note): http://php.net/manual/en/function.imap-fetchstructure.php
I tried all this answers, but neither one worked for me. Then I hit first user contributed note on this PHP page:
http://php.net/manual/en/function.imap-fetchstructure.php
and this works for all my cases. Quite old answer btw.

php class _Construct empty

<?
session_start();
/*
echo $_SESSION['SQLIP'];
echo "<br>";
echo $_SESSION['SQLDB'];
echo "<br>";
echo $_SESSION['SQLUSER'];
echo "<br>";
echo $_SESSION['SQLPASS'];
echo "<br>";
*/
class DB_MSSQL {
private $Host;
private $Database;
private $User;
private $Password;
public $Link_ID = 0;
public $Query_ID = 0;
public $Record = array();
public $Row = 0;
public $Errno = 0;
public $Error = "";
public $Halt_On_Error = "yes";
public $Auto_Free = 1;
public $PConnect = 0;
public function _construct(){
$this->Host = $_SESSION['SQLIP'];
$this->Database = $_SESSION['SQLDB'];
$this->User = $_SESSION['SQLUSER'];
$this->Password = $_SESSION['SQLPASS'];
}
function DB_MSSQL($query = "") {
if($query) {
$this->query($query);
}
}
function connect() {
if ( 0 == $this->Link_ID ) {
if(!$this->PConnect) {
$this->Link_ID = mssql_connect($this->Host, $this->User, $this->Password);
} else {
$this->Link_ID = mssql_pconnect($this->Host, $this->User, $this->Password);
}
if (!$this->Link_ID)
$this->connect_failed("connect ($this->Host, $this->User, \$Password) failed");
else
if (!mssql_select_db($this->Database, $this->Link_ID)) {
$this->connect_failed("cannot use database ".$this->Database);
}
}
}
function connect_failed($message) {
$this->Halt_On_Error = "yes";
$this->halt($message);
}
function free_result(){
mssql_free_result($this->Query_ID);
$this->Query_ID = 0;
}
function query($Query_String)
{
/* No empty queries, please, since PHP4 chokes on them. */
if ($Query_String == "")
/* The empty query string is passed on from the constructor,
* when calling the class without a query, e.g. in situations
* like these: '$db = new DB_Sql_Subclass;'
*/
return 0;
if (!$this->Link_ID)
$this->connect();
// printf("<br>Debug: query = %s<br>\n", $Query_String);
$this->Query_ID = mssql_query($Query_String, $this->Link_ID);
$this->Row = 0;
if (!$this->Query_ID) {
$this->Errno = 1;
$this->Error = "General Error (The MSSQL interface cannot return detailed error messages).";
$this->halt("Invalid SQL: ");
}
return $this->Query_ID;
}
function next_record() {
if ($this->Record = mssql_fetch_row($this->Query_ID)) {
// add to Record[<key>]
$count = mssql_num_fields($this->Query_ID);
for ($i=0; $i<$count; $i++){
$fieldinfo = mssql_fetch_field($this->Query_ID,$i);
$this->Record[strtolower($fieldinfo->name)] = $this->Record[$i];
}
$this->Row += 1;
$stat = 1;
} else {
if ($this->Auto_Free) {
$this->free_result();
}
$stat = 0;
}
return $stat;
}
function seek($pos) {
mssql_data_seek($this->Query_ID,$pos);
$this->Row = $pos;
}
function metadata($table) {
$count = 0;
$id = 0;
$res = array();
$this->connect();
$id = mssql_query("select * from $table", $this->Link_ID);
if (!$id) {
$this->Errno = 1;
$this->Error = "General Error (The MSSQL interface cannot return detailed error messages).";
$this->halt("Metadata query failed.");
}
$count = mssql_num_fields($id);
for ($i=0; $i<$count; $i++) {
$info = mssql_fetch_field($id, $i);
$res[$i]["table"] = $table;
$res[$i]["name"] = $info->name;
$res[$i]["len"] = $info->max_length;
$res[$i]["flags"] = $info->numeric;
}
$this->free_result();
return $res;
}
function affected_rows() {
// Not a supported function in PHP3/4. Chris Johnson, 16May2001.
// return mssql_affected_rows($this->Query_ID);
$rsRows = mssql_query("Select ##rowcount as rows", $this->Link_ID);
if ($rsRows) {
return mssql_result($rsRows, 0, "rows");
}
}
function num_rows() {
return mssql_num_rows($this->Query_ID);
}
function num_fields() {
return mssql_num_fields($this->Query_ID);
}
function nf() {
return $this->num_rows();
}
function np() {
print $this->num_rows();
}
function f($Field_Name) {
return $this->Record[strtolower($Field_Name)];
}
function p($Field_Name) {
print $this->f($Field_Name);
}
function halt($msg) {
if ("no" == $this->Halt_On_Error)
return;
$this->haltmsg($msg);
if ("report" != $this->Halt_On_Error)
die("Session halted.");
}
function haltmsg($msg) {
printf("<p>Server have a critical error!<br><br><br>We are very sorry for any inconvenience!<br><br>\n", $msg);
printf("<b>MSSQL Error</b>: %s (%s)</p>\n",
$this->Errno,
$this->Error);
}
}
$_php_major_version = substr(phpversion(), 0, 1);
if((4 > $_php_major_version) or !class_exists("DB_Sql"))
{
class DB_Sql extends DB_MSSQL
{
function DB_Sql($query = "")
{
$this->DB_MSSQL($query);
}
}
}
unset($_php_major_version);
?>
I have a question, why on DB_MSSQL my $Host,$Datebase,$User,$Password are empty?
If i test $_SESSIONS Between DB_MSSQL are OK.
Class don't have errors but this variables are empty... and i don't know why..
Can anybody help me?
Thank you verry much!
You have missed one underscore, you should have write :
public function __construct()
It should work like this.

Categories