Posts Tagged PHP

Turn on the web server service on macOS

Apache webserver is shipped with all macOS version. The newer macOS version no longer provides user interface to control the webserver. Geeks who know Linux can turn on and off the webserver easily through the command line client. The following article on Apple community provides a step by step tutorial to do this.

Setting up a local web server on macOS 10.13 “High Sierra”

After you follow the above article to turn on your webserver. You can find the all software is up to date and ready to use. The latest PHP version is 7.1.7.

Share

Tags: , , , , ,

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