PHP
Use to ajax for php page
AJAX Code:
ajaxpg.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | var http_request=false; function send_request(url){ http_request=false; if(window.XMLHttpRequest){ http_request=new XMLHttpRequest(); if(http_request.overrideMimeType){ http_request.overrideMimeType("text/xml"); } } else if(window.ActiveXObject){ try{ http_request=new ActiveXObject("Msxml2.XMLHttp"); }catch(e){ try{ http_request=new ActiveXobject("Microsoft.XMLHttp"); }catch(e){} } } if(!http_request){ window.alert("XMLHttp object creation failed"); return false; } http_request.onreadystatechange=processrequest; http_request.open("GET",url,true); http_request.send(null); } function processrequest(){ if(http_request.readyState==4){//Object state if(http_request.status==200){//return Successful document.getElementById(reobj).innerHTML=http_request.responseText; } else{ //Exception Errors alert("Exception Errors!"); } } } function dopage(obj,url){ document.getElementById(obj).innerHTML="Loading..."; send_request(url); reobj=obj; } |
index.php:
I am a content div on the display, when the flip action arises, the use of AJAX to update DIV to achieve the effect of this is the contents page shows the page code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | < ?php header("Content-type: text/html;charset=utf-8"); ?> <html> <head> <script language="javascript" src="ajaxpg.js"></script> </head> <body> <div id="result"> < ?php $page=isset($_GET['page'])?intval($_GET['page']):1; $num=10; $db=mysql_connect("www.easemarry.com","root","root"); mysql_select_db("cr_download"); $result=mysql_query("select * from cr_userinfo"); $total=mysql_num_rows($result); $url='test.php'; $pagenum=ceil($total/$num); $page=min($pagenum,$page); $prepg=$page-1; $nextpg=($page==$pagenum ? 0 : $page+1); $offset=($page-1)*$num; $pagenav=":<B>".($total?($offset+1):0)."-<b>".min($offset+10,$total)."</b>,Total:$total"; if($pagenum< =1) return false; $pagenav.=" <a href=javascript:dopage('result','$url?page=1');> < < </a> "; if($prepg) $pagenav.=" <a href=javascript:dopage('result','$url?page=$prepg');> < </a> "; else $pagenav.=" < "; if($nextpg) $pagenav.=" <a href=javascript:dopage('result','$url?page=$nextpg');> > </a> "; else $pagenav.=" > "; $pagenav.=" <a href=javascript:dopage('result','$url?page=$pagenum');> >> </a> "; $pagenav.=" page,Total page: $pagenum"; If($page>$pagenum){ Echo "Error : Can Not Found The page ".$page; Exit; } $info=mysql_query("select * from cr_userinfo limit $offset,$num"); While($it=mysql_fetch_array($info)){ Echo $it['username']; echo ""; } echo""; echo $pagenav; ?> </div> </body> </html> |
test.php:
The key to flip when the flip is called dopage() function, and then use the callback information to update the content div. The core server-side code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | < ?php header("Content-type: text/html;charset=utf-8"); $page=isset($_GET['page'])?intval($_GET['page']):1; $num=10; $db=mysql_connect("www.easemarry.com","root","root"); mysql_select_db("cr_download"); $result=mysql_query("select * from cr_userinfo"); $total=mysql_num_rows($result); $url='test.php'; $pagenum=ceil($total/$num); $page=min($pagenum,$page); $prepg=$page-1; $nextpg=($page==$pagenum ? 0 : $page+1); $offset=($page-1)*$num; $pagenav=":<B>".($total?($offset+1):0)."-<b>".min($offset+10,$total)."</b>,Total:$total"; if($pagenum< =1) return false; $pagenav.=" <a href=javascript:dopage('result','$url?page=1');> < < </a> "; if($prepg) $pagenav.=" <a href=javascript:dopage('result','$url?page=$prepg');> < </a> "; else $pagenav.=" < "; if($nextpg) $pagenav.=" <a href=javascript:dopage('result','$url?page=$nextpg');> > </a> "; else $pagenav.=" > "; $pagenav.=" <a href=javascript:dopage('result','$url?page=$pagenum');> >> </a> "; $pagenav.=" page,Total page: $pagenum"; If($page>$pagenum){ Echo "Error : Can Not Found The page ".$page; Exit; } $info=mysql_query("select * from cr_userinfo limit $offset,$num"); While($it=mysql_fetch_array($info)){ Echo $it['username']; echo ""; } echo""; echo $pagenav; ?> |
Generate the Guid use for php class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | < ?php class System { function currentTimeMillis() { list($usec, $sec) = explode(" ",microtime()); return $sec.substr($usec, 2, 3); } } class NetAddress { var $Name = 'easemarry.com'; var $IP = '69.65.10.199'; function getLocalHost() // static { $address = new NetAddress(); $address->Name = $_ENV["COMPUTERNAME"]; $address->IP = $_SERVER["SERVER_ADDR"]; return $address; } function toString() { return strtolower($this->Name.'/'.$this->IP); } } class Random { function nextLong() { $tmp = rand(0,1)?'-':''; return $tmp.rand(1000, 9999).rand(1000, 9999).rand(1000, 9999).rand(100, 999).rand(100, 999); } } class Guid { var $valueBeforeMD5; var $valueAfterMD5; function Guid() { $this->getGuid(); } // function getGuid() { $address = NetAddress::getLocalHost(); $this->valueBeforeMD5 = $address->toString().':'.System::currentTimeMillis().':'.Random::nextLong(); $this->valueAfterMD5 = md5($this->valueBeforeMD5); } function newGuid() { $Guid = new Guid(); return $Guid; } function toString() { $raw = strtoupper($this->valueAfterMD5); return substr($raw,0,8).'_'.substr($raw,8,4).'_'.substr($raw,12,4).'_'.substr($raw,16,4).'_'.substr($raw,20).'_'.time(); } } ?> |
Google AJAX Language API php class
This class allows you to use the Google AJAX Translation API to translate arbitrary text to the many languages supported by the Google API.
Source versioning added to:
http://code.google.com/p/php-language-api/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | < ?php /** * Translating language with Google API * @author gabe@fijiwebdesign.com * @version $id$ * @license - Share-Alike 3.0 (http://creativecommons.org/licenses/by-sa/3.0/) * * Google requires attribution for their Language API, please see: http://code.google.com/apis/ajaxlanguage/documentation/#Branding * */class Google_Translate_API { /** * Translate a piece of text with the Google Translate API * @return String * @param $text String * @param $from String[optional] Original language of $text. An empty String will let google decide the language of origin * @param $to String[optional] Language to translate $text to */ function translate($text, $from = '', $to = 'en') { $url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='.rawurlencode($text).'&langpair='.rawurlencode($from.'|'.$to); $response = file_get_contents( $url, null, stream_context_create( array( 'http'=>array( 'method'=>"GET", 'header'=>"Referer: http://".$_SERVER['HTTP_HOST']."/\r\n" ) ) ) ); if (preg_match("/{\"translatedText\":\"([^\"]+)\"/i", $response, $matches)) { return self::_unescapeUTF8EscapeSeq($matches[1]); } return false; } /** * Convert UTF-8 Escape sequences in a string to UTF-8 Bytes * @return UTF-8 String * @param $str String */ function _unescapeUTF8EscapeSeq($str) { return preg_replace_callback("/\\\u([0-9a-f]{4})/i", create_function('$matches', 'return html_entity_decode(\'&#x\'.$matches[1].\';\', ENT_NOQUOTES, \'UTF-8\');'), $str); }} // example usage$text = 'Welcome to my website.';$trans_text = Google_Translate_API::translate($text, '', 'it');if ($trans_text !== false) { echo $trans_text;} ?>< ?php /** * Translating language with Google API * @author gabe@fijiwebdesign.com * @version $id$ * @license - Share-Alike 3.0 (http://creativecommons.org/licenses/by-sa/3.0/) * * Google requires attribution for their Language API, please see: http://code.google.com/apis/ajaxlanguage/documentation/#Branding * */ class Google_Translate_API { /** * Translate a piece of text with the Google Translate API * @return String * @param $text String * @param $from String[optional] Original language of $text. An empty String will let google decide the language of origin * @param $to String[optional] Language to translate $text to */ function translate($text, $from = '', $to = 'en') { $url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='.rawurlencode($text).'&langpair='.rawurlencode($from.'|'.$to); $response = file_get_contents( $url, null, stream_context_create( array( 'http'=>array( 'method'=>"GET", 'header'=>"Referer: http://".$_SERVER['HTTP_HOST']."/\r\n" ) ) ) ); if (preg_match("/{\"translatedText\":\"([^\"]+)\"/i", $response, $matches)) { return self::_unescapeUTF8EscapeSeq($matches[1]); } return false; } /** * Convert UTF-8 Escape sequences in a string to UTF-8 Bytes * @return UTF-8 String * @param $str String */ function _unescapeUTF8EscapeSeq($str) { return preg_replace_callback("/\\\u([0-9a-f]{4})/i", create_function('$matches', 'return html_entity_decode(\'&#x\'.$matches[1].\';\', ENT_NOQUOTES, \'UTF-8\');'), $str); } } // example usage $text = 'Welcome to my website.'; $trans_text = Google_Translate_API::translate($text, '', 'it'); if ($trans_text !== false) { echo $trans_text; } ?> |
Export RSS 1.0 or 2.0 feeds to an array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | < ?php /* exportrss.php * Copyright 2007 Alec Hussey <alec.hussey@gmail.com> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ class ExportRSS{ protected $data = array(); protected $channel = array(); protected $rawdata = array(); public function __construct($data, $version) { $feed = @file_get_contents($data); $this->rawdata = simplexml_load_string($feed); // Parse the XML/RSS file switch ($version) { case "1.0": { $this->channel = array( "title" => $this->rawdata->channel->title, "link" => $this->rawdata->channel->link, "description" => $this->rawdata->channel->description, "image" => $this->rawdata->channel->image, "items" => $this->rawdata->channel->items, "textinput" => $this->rowdata->channel->textinput ); foreach ($this->rawdata->item as $item) { $row = array( "title" => $item->title, "link" => $item->link, "description" => $item->description ); array_push($this->data, $row); } break; } case "2.0": { $this->channel = array( "title" => $this->rawdata->channel->title, "link" => $this->rawdata->channel->link, "description" => $this->rawdata->channel->description, "language" => $this->rawdata->channel->language, "date" => $this->rawdata->channel->pubDate, "builddate" => $this->rawdata->channel->lastBuildDate, "docs" => $this->rawdata->channel->docs, "generator" => $this->rawdata->channel->generator, "editor" => $this->rawdata->channel->managingEditor, "webmaster" => $this->rawdata->channel->webMaster, ); foreach ($this->rawdata->channel->item as $item) { $row = array( "title" => $item->title, "link" => $item->link, "description" => $item->description, "enclosure" => $this->enclosure, "date" => $item->pubDate, "guid" => $item->guid ); array_push($this->data, $row); } break; } default: { echo "ExportRSS::WARNING: invalid version was specified"; break; } } } public function get_raw_data() { return $this->rawdata; } public function get_channel_data() { return $this->channel; } public function get_data() { return $this->data; } }?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | < ?php include("exportrss.php"); // Parse XML/RSS 2.0 feed $feed = new ExportRSS("test.xml", "2.0"); $channel = $feed->get_channel_data(); echo " <h3>Channel</h3> <strong>Title:</strong> {$channel['title']} <strong>Date:</strong> {$channel['date']} <strong>Description:</strong> {$channel['description']} <strong>Editor:</strong> {$channel['editor']} <strong>Webmaster:</strong> {$channel['webmaster']} <strong>Language:</strong> {$channel['language']} <strong>Generator:</strong> {$channel['generator']} <strong>Link:</strong> {$channel['link']} "; echo " <h3>Feed Items</h3> "; foreach ($feed->get_data() as $item) { echo " <strong>Title</strong>: {$item['title']} <strong>Date Published</strong>: {$item['date']} <strong>Description</strong>: {$item['description']} <strong>Link</strong>: {$item['link']} "; } ?> |
Using sockets in PHP : Get articles from Usenet
http://www.phpbuilder.net/columns/armel20010427.php3
PHP can open sockets on remote or local hosts. Here is a hands-on example of using such a socket: getting connected to a Usenet News Server, talking to this server, and downloading some articles for a precise newsgroup.
Opening a socket in PHP
Sockets are opened using fsockopen(). This function is both available in PHP3 and PHP4. It uses the following prototype :
<?php
int fsockopen
(string hostname,
int port [,
int errno [,
string errstr [,
double timeout]]])
?>
For the Internet domain, it will open a TCP socket connection to hostname on port port. hostname may in this case be either a fully qualified domain name or an IP address. For UDP connections, you need to explicitly specify the protocol: udp://hostname. For the Unix domain, hostname will be used as the path to the socket, port must be set to 0 in this case. The optional timeout can be used to set a timeout in seconds for the connect system call.
More information about fsockopen() : http://www.php.net/manual/function.fsockopen.php
Network News Transfer Protocol
Accessing a Usenet News Server requires using a specific protocol, called NNTP and standing for Network News Transfer Protocol.
This protocol is higly detailed in RFC977 (Request For Comment number 977), which is available at : http://www.w3.org/Protocols/rfc977/rfc977.html
This document described precisely how to connect to and then dialog with the NNTP server thanks to the various commands available for the task.
Connecting
Connecting to the NNTP server requires knowing its hostname (or IP address) and the port it is listening on. You should include a timeout so that an unsuccessful attempt at connecting does not “freeze” the application.
<?php
$cfgServer = “your.news.host”;
$cfgPort = 119;
$cfgTimeOut = 10;// open a socket
if(!$cfgTimeOut)
// without timeout
$usenet_handle = fsockopen($cfgServer, $cfgPort);
else
// with timeout
$usenet_handle = fsockopen($cfgServer, $cfgPort, &$errno, &$errstr, $cfgTimeOut);if(!
$usenet_handle) {
echo “Connexion failed\n”;
exit();
}
else {
echo “Connected\n”;
$tmp = fgets($usenet_handle, 1024);
}?>
Talking to the Server
We are now connected to the server, and can talk to it through th previously opened socket. Let us say we want to get the 10 latest articles from some newsgroup. RFC977 specifies that the first step is to select the right newsgroup with the GROUP command :
GROUP ggg
The required parameter ggg is the name of the newsgroup to be selected (e.g. “net.news”). A list of valid newsgroups may be obtained from the LIST command. The successful selection response will return the article numbers of the first and last articles in the group, and an estimate of the number of articles on file in the group.
Example:
chrome:~$ telnet my.news.host 119
Trying aa.bb.cc.dd…
Connected to my.news.host.
Escape character is ‘^]’.
200 my.news.host InterNetNews NNRP server INN 2.2.2 13-Dec-1999 ready (posting ok).
GROUP alt.test
211 232 222996 223235 alt.test
quit
205
After receiving the command ” GROUP alt.test”, the News Server answered “211 232 222996 223235 alt.test”. 211 is an RFC defined code (basically saying the command was succesfully executed – check the RFC for more details). It also answered it currently has 232 articles, indexed 222996 for the oldest through 223235 for the latest. These are called article numbers. Now, let us have a count here : 222996 + 232 by no means equals to 232235. The seven missing articles were removed one way or another from the server, either cancelled by their legitimate author (yes, it is possible and easy to do !) or deleted after report of abuse for example.
Be careful though, the server might require authentication before selecting the newsgroup, depending on wether it is a public or private server. It could also let anybody retrieve articles but require authentication to publish an article.
<?php//$cfgUser = “xxxxxx”;
//$cfgPasswd = “yyyyyy”;
$cfgNewsGroup = “alt.php”;
// identification required on private server
if($cfgUser) {
fputs($usenet_handle, “AUTHINFO USER “.$cfgUser.“\n”);
$tmp = fgets($usenet_handle, 1024); fputs($usenet_handle, “AUTHINFO PASS “.$cfgPasswd.“\n”);
$tmp = fgets($usenet_handle, 1024);
// check error
if($tmp != “281 Ok\r\n”) {
echo “502 Authentication error\n”;
exit();
}
}// select newsgroup
fputs($usenet_handle, “GROUP “.$cfgNewsGroup.“\n”);
$tmp = fgets($usenet_handle, 1024);if($tmp == “480 Authentication required for command\r\n”) {
echo “$tmp\n“;
exit();
}
$info = split(” “, $tmp);
$first = $info[2];
$last = $info[3]; print “First : $first\n“;
print “Last : $last\n“;?>

