<?php
ini_set('max_execution_time', 1600);
/* Register and create app in
* https://apps.twitter.com/
* Documentation:
* https://dev.twitter.com/rest/reference/get/search/tweets
* Example:
* twitter_api_get.php?count=10&page=10&lang=id&q=quote%20-RT
*/
// Replace with your token and consumer key from apps.twitter.com
$token = "<your token>";
$token_secret = "<your token_secret>";
$consumer_key = "<your consumer_key>";
$consumer_secret = "<your consumer_secret>";
$host = 'api.twitter.com';
$method = 'GET';
//$path = '/1.1/statuses/user_timeline.json'; // api call path
$path = '/1.1/search/tweets.json'; // api call path search
$max_id="";
$since_id=0;$since_id_new=0;
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$count = $_GET['count'];
$page = $_GET['page'];
$dtquery = $_GET['q'];
$lang = $_GET['lang'];
$awal = microtime(true);$bar=1;
echo "<!-- Progress bar holder -->
<div id='progress' style='width:100%;'></div><br>";
$total = $page;
for($i=0;$i<$page;$i++){
echo '<hr>Page '.$i.' ----------'.$max_id.'<hr>';
if($max_id != ""){
$query = array( // query parameters
//'screen_name' => 'Hangs_',
'q' => $dtquery,
'count' => $count,
'lang' => $lang,
//'since_id' => $max_id-$count,
'max_id' => $max_id
//'result_type' => 'mixed'
//'until' => '2016-09-17'
);
}else{
$query = array( // query parameters
'q' => $dtquery,
'count' => $count,
'lang' => $lang
);
}
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("%25","%",str_replace("&","&",$url)); //Patch by @Frewuill
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
//print it out echo $url;
//echo '<pre>',print_r($twitter_data),'</pre>';
$n=$i*$count;
if(count($twitter_data->statuses)>0){
foreach($twitter_data->statuses as $items){
echo ++$n.". ".$items->created_at." __ ".$items->user->screen_name."<br />";
echo $items->id_str."<br>";
echo $items->text."<br/>";
echo "<br/>";
$max_id = $items->id_str;
}
}
$since_id = $twitter_data->search_metadata->since_id_str;
//$max_id = $twitter_data->search_metadata->max_id_str;
//$max_id = substr($max_id,0,-4).((int)substr($max_id,-4)-$count);
//echo '<pre>',print_r($twitter_data->search_metadata),'</pre>';
//======= Calculate the percentation
$percent = (intval($bar/$total * 100)>=100?100:(intval($bar/$total * 100)-1))."%";
// Javascript for updating the progress bar and information
echo '<script language="javascript">
document.getElementById("progress").innerHTML="<div class=\"progress\"><div id=\"progressval\" style=\"padding-top:5px;padding-bottom:5px;background:#3498db;color:#fff;font-weight:bold;text-align:center;width:'.$percent.'\">'.$percent.' Complete</div></div>";
</script>';
// This is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
// Send output to browser immediately
flush();
// Sleep one second so we can see the delay
//sleep(1);
$bar++;
}
// Tell user that the process is completed
$akhir = microtime(true);
$lama = $akhir - $awal;
echo '<script language="javascript">document.getElementById("progressval").innerHTML="Process Complete. Execution time: '.(round($lama,2)).' Second";</script>';
?>
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
Manual Javascript load another page
<div id="load"></div>
<script>
<script>
// ========= get method
var client = new XMLHttpRequest();
client.open('GET', 'http://<yourweb>/contentpage.php');
client.onreadystatechange = function() {
document.getElementById('load').innerHTML=(client.responseText);
}
client.send();
In another host page set <?php header("Access-Control-Allow-Origin: *");?>
var client = new XMLHttpRequest();
client.open('GET', 'http://<yourweb>/contentpage.php');
client.onreadystatechange = function() {
document.getElementById('load').innerHTML=(client.responseText);
}
client.send();
// ========= post method
var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'lorem=ipsum¶=meter';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
</script>In another host page set <?php header("Access-Control-Allow-Origin: *");?>
KNOWLEDGE DISCOVERY IN DATABASE USING WEKA WITH PHP
WEKA is software can Classify, Cluster, and Associate data. In this implementation is used Weka Weka 3-6-13 Jar executable version that can be in control using the CLI (Command Line), the PHP Command Line can be run using a command shell_exec (). I prefer to use executable .jar version 3-6-13 because file size is smaller. WEKA can be download from http://www.cs.waikato.ac.nz/ml/weka/downloading.html.
Source code GoogleDrive
Source code GoogleDrive
Monitoring network tool ping with php
Using exec() function PHP ping IP Address
Monitoring network tool ping with php
How to use:
Type IP Address on the input text, e.g.
192.168.1.1
192.168.1.1-192.168.1.50
192.168.1.0/24
Github
Monitoring network tool ping with php
How to use:
Type IP Address on the input text, e.g.
192.168.1.1
192.168.1.1-192.168.1.50
192.168.1.0/24
Github
Open Existing PDF With PHP MPDF and set Protection Password
<?php
include("MPDF57/mpdf.php");
$pdf=new mPDF();
$pdf->SetImportUse();
$pagecount = $pdf->SetSourceFile('filename.pdf');
for ($i=1; $i<=$pagecount; $i++) {
$import_page = $pdf->ImportPage($i);
$pdf->UseTemplate($import_page);
if ($i < $pagecount){
$pdf->AddPage();
}
}
$pdf->SetProtection(array('copy','print'), '', 'password');
$pdf->Output("filename.pdf","I");
?>
Tutorial HTMLtoPDF
include("MPDF57/mpdf.php");
$pdf=new mPDF();
$pdf->SetImportUse();
$pagecount = $pdf->SetSourceFile('filename.pdf');
for ($i=1; $i<=$pagecount; $i++) {
$import_page = $pdf->ImportPage($i);
$pdf->UseTemplate($import_page);
if ($i < $pagecount){
$pdf->AddPage();
}
}
$pdf->SetProtection(array('copy','print'), '', 'password');
$pdf->Output("filename.pdf","I");
?>
Tutorial HTMLtoPDF
Create Your Own QR Code With Logo Centered With PHP
I just want to know how to create QR Code, so I search to Google.com, first time I find online QR Code generate by Google API, Source code here(Github). I think always online is not good, so I search again then I find "phpqrcode", PHP QR Code is open source (LGPL) library for generating QR Code, 2-dimensional barcode. This is the web page.
http://phpqrcode.sourceforge.net/
The web page tell Some of library features includes:
- Supports QR Code versions (size) 1-40
- Numeric, Alphanumeric, 8-bit and Kanji encoding. (Kanji encoding was not fully tested, if you are japan-encoding enabled you can contribute by verifing it :) )
- Implemented purely in PHP, no external dependencies except GD2
- Exports to PNG, JPEG images, also exports as bit-table
- TCPDF 2-D barcode API integration
- Easy to configure
- Data cache for calculation speed-up
- Provided merge tool helps deploy library as a one big dependency-less file, simple to "include and do not wory"
- Debug data dump, error logging, time benchmarking
- API documentation
- Detailed examples
- 100% Open Source, LGPL Licensed
then write code
QRcode::png('some othertext 1234'); //creates code image and outputs it directly into browser
To adding image in the center of QR Code image I using php function imagecopyresampled
// === Adding image to qrcode
$QR = imagecreatefrompng($imgname);
if($logo !== FALSE){
$logopng = imagecreatefrompng($logo);
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logopng);
$logo_height = imagesy($logopng);
list($newwidth, $newheight) = getimagesize($logo);
$out = imagecreatetruecolor($QR_width, $QR_width);
imagecopyresampled($out, $QR, 0, 0, 0, 0, $QR_width, $QR_height, $QR_width, $QR_height);
imagecopyresampled($out, $logopng, $QR_width/2.65, $QR_height/2.65, 0, 0, $QR_width/4, $QR_height/4, $newwidth, $newheight);
}
imagepng($out,$imgname);
imagedestroy($out);
Then, to chage color of qrcode image with php, use php function imagecolorat
// === Change image color
$im = imagecreatefrompng($imgname);
$r = 44;$g = 62;$b = 80;
for($x=0;$x<imagesx($im);++$x){
for($y=0;$y<imagesy($im);++$y){
$index = imagecolorat($im, $x, $y);
$c = imagecolorsforindex($im, $index);
if(($c['red'] < 100) && ($c['green'] < 100) && ($c['blue'] < 100)) { // dark colors
// here we use the new color, but the original alpha channel
$colorB = imagecolorallocatealpha($im, 0x12, 0x2E, 0x31, $c['alpha']);
imagesetpixel($im, $x, $y, $colorB);
}
}
}
imagepng($im,$imgname);
imagedestroy($im);
I adding the function to convert png image to base64, qrcode image is saved as png file, just 3 line to convert png image to base64 code.
// === Convert Image to base64
$type = pathinfo($imgname, PATHINFO_EXTENSION);
$data = file_get_contents($imgname);
$imgbase64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
There all done, to showing image use tag <img/>
// === Show image
echo "<img src='$imgbase64' style='position:relative;display:block;width:240px;height:240px;margin:160px auto;'>";
Complete Project here(Github)
Report PHP CSV
csv_download.php
<?php
for($i=1;$i<4;$i++){
$out.="A,B,C,D,E,F\r\n";
}
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv".date("Y-m-d").".csv");
header("Content-disposition: filename=csv".date("Y-m-d").".csv");
print $out;
?>
csv_save_to_folder_server.php
<?php
$data_array = array (
array ('1','2'),
array ('2','2'),
array ('3','6'),
array ('4','2'),
array ('6','5')
);
$csv = "col1,col2 \n";//Column headers
foreach ($data_array as $record){
$csv.= $record[0].','.$record[1]."\n"; //Append data to csv
}
//membuat file csv di folder server
for($i=1;$i<4;$i++){
$csv_handler = fopen ("csv/csvfile".$i.".csv",'w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);
}
echo 'Data saved to csvfile.csv';
?>
<?php
for($i=1;$i<4;$i++){
$out.="A,B,C,D,E,F\r\n";
}
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv".date("Y-m-d").".csv");
header("Content-disposition: filename=csv".date("Y-m-d").".csv");
print $out;
?>
csv_save_to_folder_server.php
<?php
$data_array = array (
array ('1','2'),
array ('2','2'),
array ('3','6'),
array ('4','2'),
array ('6','5')
);
$csv = "col1,col2 \n";//Column headers
foreach ($data_array as $record){
$csv.= $record[0].','.$record[1]."\n"; //Append data to csv
}
//membuat file csv di folder server
for($i=1;$i<4;$i++){
$csv_handler = fopen ("csv/csvfile".$i.".csv",'w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);
}
echo 'Data saved to csvfile.csv';
?>
php.ini disable_function
disable_functions= symlink,shell_exec,proc_close,popen,system,dl,passthru,escapeshellarg,escapeshellcmd,exec,ini_alter,parse_ini_file,pcntl_exec,proc_terminate,show_source,proc_get_status,proc_nice,proc_open,pclose,pfsockopen,leak,apache_child_terminate,posix_kill,posix_mkfifo,posix_setsid,posix_setuid,posix_setpgid,define_syslog_variables,syslog,openlog,closelog,ocinumcols,listen,chgrp,apache_note,apache_setenv,debugger_on,debugger_off,ftp_exec,dll,ftp,myshellexec,socket_bind,fpassthru,posix_getpwuid,phpinfo,base64_decode,shell,python_eval,safe_mode,diskfreespace,posix_setegid,posix_seteuid,posix_setgid,posix_times,posix_uname,source,fpaththru,virtual,posix_ctermid,posix_getcwd,posix_getegid,posix_geteuid,posix_getgid,posix_getgrgid,posix_getgrnam,posix_getgroups,posix_getlogin,posix_getpgrp,posix_getpid,posix,_getppid,posix_getrlimit,posix_getsid,graphem
Compress Image While Upload
Sharing source code compress image JPG/JPEG/PNG/GIF
the simple code
Download full source (dropbox)
the simple code
$tmp_name = $_FILES["file"]["tmp_name"]; $dir = "images"; $dest = $dir."/".$_FILES["file"]["name"]; $quality=95;//percentage quality compress image //check image type if ($_FILES["file"]["type"] == 'image/jpeg'){ $image = imagecreatefromjpeg($tmp_name); }elseif ($_FILES["file"]["type"] == 'image/gif'){ $image = imagecreatefromgif($tmp_name); }elseif ($_FILES["file"]["type"] == 'image/png'){ $image = imagecreatefrompng($tmp_name); } //compress and save file to jpg imagejpeg($image, $dest, $quality); imagecreatefromjpeg($dest);
Download full source (dropbox)
HTML to PDF with PHP
Membuat report website berfomat PDF, kebanyakan dari kita mungkin sudah banyak yang tau, menggunakan FPDF. Disini saya sekedar sharing report web PHP dengan output PDF menggunakan MPDF57 dimana report di ambil dari halaman HTML.
Awal dulu membuat report PDF menggunakan FPDF saya sangat kesusaha karena rumit dan merepotkannya mengatur halaman menggunakan perintah $pdf->Cell(), mungkin bagi yang sudah jago dan familiar dengan FPDF membuat report sangat lancar. Browsing-browsing cari cara membuat PDF yang mudah akhirnya kepikiran "Gimana caranya membuat HTML ke PDF menggunakan PHP", nemu namanya html2pdf, utak-atik, setting-setting berjam-jam dan hasilnya masih kurang cocok menurut saya, untuk kombinasi HTML dengan CSS kurang bagus. Balik lagi browsing cari lewat ke search engine, nemu yang namanya MPDF, coba utak-atik wah ternyata cocok ini. Hasil ubahnya HTML+CSS ke PDF menurut saya sudah sempurna, title pagenya sesuai dengan halaman HTML yang di PDF-kan.
Contoh script PHP yang membuat PDF:
Silahkan download MPDF57(Dropbox)
Halaman resmi
Awal dulu membuat report PDF menggunakan FPDF saya sangat kesusaha karena rumit dan merepotkannya mengatur halaman menggunakan perintah $pdf->Cell(), mungkin bagi yang sudah jago dan familiar dengan FPDF membuat report sangat lancar. Browsing-browsing cari cara membuat PDF yang mudah akhirnya kepikiran "Gimana caranya membuat HTML ke PDF menggunakan PHP", nemu namanya html2pdf, utak-atik, setting-setting berjam-jam dan hasilnya masih kurang cocok menurut saya, untuk kombinasi HTML dengan CSS kurang bagus. Balik lagi browsing cari lewat ke search engine, nemu yang namanya MPDF, coba utak-atik wah ternyata cocok ini. Hasil ubahnya HTML+CSS ke PDF menurut saya sudah sempurna, title pagenya sesuai dengan halaman HTML yang di PDF-kan.
Contoh script PHP yang membuat PDF:
Silahkan download MPDF57(Dropbox)
Halaman resmi
Select LIMIT di MSSQL dengan PHP
Kita tau untuk menampilkan data dari baris ke berapa sampai baris ke berapa pada mysql menggunakan perintah limit. seperti:
namun kasusnya berbeda jika menggunakan database MSSQL/SQL Server, pada database MSSQL/SQL Server tidak ada sintak LIMIT, maka untuk mengatasinya
menggunakan perintah.
- SELECT TOP 3 * FROM maksudnya tampilkan 3 baris dari atas (sebanyak 3)
- SELECT TOP 20 * FROM Customers maksudnya tampilkan sampai baris terakhir baris ke 20
Silahkan di coba di w3schools
Semoga bermanfaat
SELECT * FROM Customers LIMIT 5,10;
namun kasusnya berbeda jika menggunakan database MSSQL/SQL Server, pada database MSSQL/SQL Server tidak ada sintak LIMIT, maka untuk mengatasinya
menggunakan perintah.
SELECT * FROM (SELECT TOP 3 * FROM (SELECT TOP 20 * FROM Customers ORDER BY CustomerID) AS a ORDER BY CustomerID DESC ) AS b WHERE CustomerID BETWEEN 1 AND 20 ORDER BY b.CustomerID;
- SELECT TOP 3 * FROM maksudnya tampilkan 3 baris dari atas (sebanyak 3)
- SELECT TOP 20 * FROM Customers maksudnya tampilkan sampai baris terakhir baris ke 20
Silahkan di coba di w3schools
Semoga bermanfaat
Extract text from DOCX or ODT files using PHP
Rqeuired:
- PHP 5.2+
- php_zip.dll for Windows or --enable-zip parameter for Linux.
This technique can be used to create a web crawler and index document files based upon their content. The text data is present in word/document.xml for DOCX and in Content.xml for ODT file. In order to extract the text all we need to do is that get the contents of word/document.xml (for docx file) or content.xml (for odt file) and then display its content after filtering out XML tags present in it.
Create a new PHP file and name it as extract.php and add the following code
Source: www.botskool.com
- PHP 5.2+
- php_zip.dll for Windows or --enable-zip parameter for Linux.
This technique can be used to create a web crawler and index document files based upon their content. The text data is present in word/document.xml for DOCX and in Content.xml for ODT file. In order to extract the text all we need to do is that get the contents of word/document.xml (for docx file) or content.xml (for odt file) and then display its content after filtering out XML tags present in it.
Create a new PHP file and name it as extract.php and add the following code
open($filename)) { // If successful, search for the data file in the archive if (($index = $zip->locateName($dataFile)) !== false) { // Index found! Now read it to a string $text = $zip->getFromIndex($index); // Load XML from a string // Ignore errors and warnings $xml = DOMDocument::loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING); // Remove XML formatting tags and return the text return strip_tags($xml->saveXML()); } //Close the archive file $zip->close(); } // In case of failure return a message return "File not found"; } echo extracttext($document); ?>
Source: www.botskool.com
Showing Image from DOCX using PHP
Required:
- PHP 5.2+
- php_zip.dll for Windows or --enable-zip parameter for Linux
Basically we need a ZIP library for PHP. The reason behind this requirement is that Word document files are actually archived files with there extension changed from .zip to .docx.
Create a new PHP file and name it as extract.php and add the following code in it.
Now create another PHP file and name it as display.php and add the following code to it.
- PHP 5.2+
- php_zip.dll for Windows or --enable-zip parameter for Linux
Basically we need a ZIP library for PHP. The reason behind this requirement is that Word document files are actually archived files with there extension changed from .zip to .docx.
Create a new PHP file and name it as extract.php and add the following code in it.
open($filename)) { for ($i=0; $i<$zip->numFiles;$i++) { /*Loop via all the files to check for image files*/ $zip_element = $zip->statIndex($i); /*Check for images*/ if(preg_match("([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)",$zip_element['name'])) { /*Display images if present by using display.php*/ echo "
"; } } } } readZippedImages($document); ?>
Now create another PHP file and name it as display.php and add the following code to it.
open($_GET['filename'])) { /*Get the content of the specified index of ZIP archive*/ echo $zip->getFromIndex($_GET['index']); } $zip->close(); ?>Source: www.botskool.com
Progress Bar dengan PHP
Jika Anda memiliki script PHP berjalan lama yang mengeksekusi banyak proses, Anda mungkin perlu untuk menginformasikan pengguna tentang kemajuan proses ketika script masih berjalan dan belum selesai. Menggunakan progress bar dapat menjadi pilihan terbaik. Kita bisa menggabungkan fungsi PHP flush(), Javascript, dan CSS juga untuk membuat progress bar yang bagus.
Berikut adalah teknik pembuatan progress bar.
Kodenya.
Berikut adalah teknik pembuatan progress bar.
- Buat setidaknya satu elemen div dengan lebar tertentu dalam dokumen HTML Anda untuk menampilkan progress bar.
- Memperkirakan persentase kemajuan dalam script PHP Anda. Nomor ini akan digunakan untuk menentukan panjang progress bar.
- "Echo" Javascript untuk memperbarui isi dari elemen div di atas dengan div bahwa persentase lebar sama seperti kemajuan yang dihitung. Juga memberikan div warna latar belakang yang berbeda atau gambar latar belakang sehingga kita bisa melihatnya.
- "Flush" ke browser.
Kodenya.
Chart & Graph jqPlot
Plugin untuk membuat Chart dan Grafik (jqPlot).
Penggunaannya mudah tinggal panggil 2(dua) script .js dan 1(satu) script .css
Penggunaannya mudah tinggal panggil 2(dua) script .js dan 1(satu) script .css
Subscribe to:
Posts (Atom)