Posts Tagged 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: , ,

A useful PHP function – get page url

Here is a function I got from the internet. It is a useful PHP function. I put here for my reference in the future.
function getPageURL()
{
	$isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
	$port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
	$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
	$url = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
	return $url;
}
Share

Tags: ,

Error_reporting in PHP

I have rich experience in programming PHP and PERL. In Perl, I always add the following two lines to my scripts:

use strict;  user warning;

However, I could not find similar things in PHP. When I am working with a complicated PHP web application project, I encountered a lot of times that wrote a variable name in one way and use call it in a wrong spelling. That makes me really frustrating. Sometimes, took me a long time to figure out what was wrong. Then I started to search the internet and tried to find a solution to reduce the frustrating moments.  End up I found post with the following question:

I’m getting the following error PHP Notice: Undefined index: HTTP_REFERER in C:\Inetpub\cgi-bin\search5.php on line 168 on first call..
i’m just trying to get the value of this $_SERVER[‘HTTP_REFERER’]

Aany solution for this?

I got two useful information from the follow-up posts

1) Check the variable is set or not: isset() function. For example, isset($arr[‘a’]);

2) Switch on the PHP error reporting mechanism. There are two ways to do this. In php.ini file,  uncomment the following line:

error_reporting E_ALL

Or on the top of each PHP file, include the following code:

error_reporting(E_ALL);

There is also a display_errors directive which allows you to display errors, warnings and notices in your browser or have them written to the server’s error log only.

By using the above method, I can get rid of all unnecessary warnings and errors I made in the PHP applications.

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: , ,