Archive for category PHP

PHP CURL and AJAX

From http://stackoverflow.com/questions/19212293/mimicking-an-ajax-call-with-curl-php

I’m scraping a site using curl (via PHP) and some information I want is a list of products which is by default only showing the first few ones. The rest is passed to the user when they click a button to get the full list of products, which triggers an ajax call to return that list.

Here is in a nutshell the JS they use:

headers['__RequestVerificationToken'] = token;
$.ajax({
type: "post",
url: "/ajax/getProductList",
dataType: 'html',
data: JSON.stringify({ historyPageIndex: 1, displayPeriod: 0, productsType: All }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
    $(target).html("");
    $(target).html(result);
},
beforeSend: function (XMLHttpRequest) {
    if (headers['__RequestVerificationToken']) {
        XMLHttpRequest.setRequestHeader("__RequestVerificationToken", headers['__RequestVerificationToken']);
    }
}
});

To set the request verification token as a header, more closely mimic an AJAX request, and set the content-type to JSON, use CURLOPT_HEADER.
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Requested-With: XMLHttpRequest", "Content-Type: application/json; charset=utf-8", "__RequestVerificationToken: $token"));
PHP code
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieLocation);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieLocation);
curl_setopt($ch, CURLOPT_URL, 'https://www.domain.com/Applications/ViewProducts');
curl_setopt($ch, CURLOPT_REFERER, 'https://www.domain.com/');
$webpage = curl_exec($ch);
$productsType = trim(find_by_pattren($webpage, '<input id="productsType" name="productsType" type="hidden" value="(.*?)"'));
$token = trim(find_by_pattren($webpage, '<input name="__RequestVerificationToken" type="hidden" value="(.*?)"'));

$postVariables = json_encode(array('productsType' => $productsType,
'historyPageIndex' => 1,
'displayPeriod' => 0));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Requested-With: XMLHttpRequest", "Content-Type: application/json; charset=utf-8", "__RequestVerificationToken: $token"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postVariables);
curl_setopt($ch, CURLOPT_URL, 'https://www.domain.com/ajax/getProductList');
curl_setopt($ch, CURLOPT_REFERER, 'https://www.domain.com/Applications/ViewProducts');
$webpage = curl_exec($ch);


                            
                        
Share

Tags: , ,

Language Detection With N-Grams in PHP

When searching for an good PHP example for this. It happened this article was found. Language Detection With N-Grams

Share

Enable the managesieve of Dovecot and use it in Roundcubemail

I was searching plugins to filter mails in the RoundCubeMail webmail application. In default, the managesieve plugin for RoundCubeMail is already installed. To enable it in the RoundCubeMail application, I just simply modify the main.inc.php in the config of the roundcubemail installation folder.

$rcmail_config['plugins'] = array('managesieve');

After this modification, I was able to see the filter tab in the person setting page. However, there was a error message whenever I clicked this tab. The error message is Unable to connect to managesieve server. I googled for a couple of hours and tried to find a workable solution. None of the posts and articles I read solved my problem. I tried to install pysieved in the Ubuntu server. After the server was installed I still got the same error. As a matter of fact, all information points to Dovecot configuration. How can I properly config the Dovecot and make it work. I started my adventure by myself.

After several tries, I found a workable solution. To enable sieve plugin in dovecot, we need edit /etc/dovecot/dovecot.conf as the following:

protocols = imap imaps managesieve

protocol managesieve {
   listen = localhost:2000
}

protocol lda {
...
mail_plugins = sieve
}

protocol managesieve {
  login_executable = /usr/lib/dovecot/managesieve-login
  mail_executable = /usr/lib/dovecot/managesieve
  managesieve_logout_format = bytes=%i/%o
}

plugin {
...
sieve=~/.dovecot.sieve
sieve_dir=~/sieve
}

Save the changes and restart the dovecot daemon.

 
/etc/init.d/dovecot stop
/etc/init.d/dovecot start

Test in the RoundcubeMail webmail interface and create a filter. And then send an email to myself. The test filter is moving any mail sending to me to a spefic folder. Hooray, it works like a charm.

Share

Tags: , ,

A PHP example to generate WordPress-like category list

In one of my post I described a way to use SQL stored procedure to extract data in a particular order and then generate a list. you can find the post from the following link.

http://www.sunfinedata.com/database/mysql-database/a-sql-stored-procedure-to-combine-multiple-select-sets-into-one/

In following PHP code is used to use the data returned from the SQL stored procedure and generate a checkbox list with the parent list item hang out and child list item indented. User can use the checkbox to select multiple items.


protected function getCheckboxList($result, $select_id, $select_name, $id_array=array())
{
if (! $result) { return ""; }
// the result points to an array of an array
$recordlist = "<ul class=\"category\">";
$openul = 0;
foreach($result as $key => $value)
{
$pair = array();
foreach($value as $key1 => $value1)
{
$pair[] = $value1;
}
if ($pair[2] == 0)
{
if ($openul >0)
{
$recordlist .= "</ul>";
$openul = 0;
}
}
$recordlist .= "<li><label class=\"selectid\">";
$recordlist .= "<input type=\"checkbox\" value=\"".$pair[0]."\"";
if (($id_array[$pair[0]]))
{
$recordlist .= " selected=\"selected\" />";
}
$recordlist .= ">".$pair[1]."</lable></il>";
if ($pair[2] == 0)
{
$recordlist .= "<ul class=\"sublist\">";
$openul = 1;
}
}
if ($openul >0) { $recordlist .= "</ul>"; }
$recordlist .= "</ul>";
return $recordlist;
}

In order to show the list in the expected order, the following CSS code is used.


/*************************
category list
**************************/
#category_panel
{
height: 300px;
overflow: auto;
font-size: 88%;
/*padding: .5em .9em;*/
border: 1px solid #D8D8D8;
}

#category_panel ul.category
{
list-style-type: none;
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
}

#category_panel .category ul /*CSS for Simple Tree Menu*/
{
text-align: left;
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 12px;
}

#category_panel .category li /*Style for LI elements in general (excludes an LI that contains sub lists)*/
{
list-style: none;
margin: 0;
padding: 0;
line-height: 12px;
/* padding: 0px 0px 0px 18px;
margin: 0px 0px 2px 3px;
*/}

#category_panel .category li.sublist /* Style for LI that contains sub lists (other ULs). */
{
cursor: pointer;
margin-left: 0px;
}

#category_panel .category li.sublist ul /*Style for ULs that are children of LIs (submenu) */
{
display: none; /*Hide them by default. Don't delete. */
}

#category_panel .category li.sublist ul li /*Style for LIs of ULs that are children of LIs (submenu) */
{
cursor: default;
}

You are free to adapt these code in your web applications. Let me know if you have improved code and comments.

Share

Tags: , , ,

A generic PHP function to generate navigation bar for web applications

When you write a page with a long list in a web application, you may always want to break the list to pages to show only part of the list. And further, allow user use a navigation bar with page numbers to jump to different pages. This post provide a generic PHP function. You can adapt it and use it in your web application. There are two input variables: npages = total number of pages, page = the current page you want to display. Within the function, the only thing you should change is the $_config array. It hold some information for constructing the page hyperlink. $_config[‘scirptname’] includes php file name that display the given page and $_config[‘cmd’] includes the command code in the php file. Other than that, you do not need change anything to use the function. To see live demo, please visit bookmark.sunfinedata.com.


// generate the page navigating string
function getNavStr( npages, page)
{
// get necessary values for the variables
$href = $_config['scriptname']."?cmd=".$_config['cmd']."&page={page}";

if ($npages <= 1) { return ""; }

$first = 0;
$last = 0;
// calculate first and last pages
if ($page <= 5)
{
$first = 1;
$last = $npages < 10 ? $npages : 10;
}
elseif ($page >= $npages - 5)
{
$first = $npages - 10 > 1 ? $npages - 10 : 1;
$last = $npages;
}
else
{
$last = $npages < $page + 5 ? $npages : $page + 5;
$first = $page - 5 > 1 ? $page - 5 : 1;
}

$navStr = "";
// create the page link prefix to the first page
if ($first > 1)
{
$url = preg_replace("/{page}/", "1", $href);
$navStr .= "<a href=\"$url\"><span class=\"boxedtext\">1</span></a>...";
}
// create the page links from the first to the last
for ($i=$first; $i<=$last; $i++)
{
if ($i == $page)
{
$navStr .= "<span class=\"outstanding\">$i</span>";
}
else
{
$url = preg_replace("/{page}/", "$i", $href);
$navStr .= "<a href=\"$url\"><span class=\"boxedtext\">$i</span></a>";
}
if ($i != $last)
{
$navStr .= " ";
}
}
// create the page link affix to the last page
if ($last < $npages)
{
$url = preg_replace("/{page}/", "$npages", $href);
$navStr .= "...<a href=\"$url\"><span class=\"boxedtext\">$npages</span></a>";
}

$this->_navStr = $navStr;
// return the navigation string
return $navStr;
}

Share

Tags: , ,