Category Archives: PHP

Download Images From Web Page

download images directly to your local computer, without the need for any authentication, permission, etc.

<?php
$url=’http://www.example.com/index.php’;
$urlsrc=’http://www.example.com/’;

$doc=new DOMDocument();
$html=file_get_contents($url);
@$doc->loadHTML($html);
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$images=$xml->xpath(‘//img’);

$filenum=1;

$Successful=0;

$Failed=0;

foreach ($images as $img)
{
$url_components = parse_url($img[‘src’]); // First parse the URL
$url_path = $url_components[‘path’]; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()

if($img[‘title’]!=null)
{
$imgtitle=$img[‘title’];
}
else
{
$imgtitle=pathinfo($url_path, PATHINFO_FILENAME);
}

if (strpos($img[‘src’],’http’) !== false)
{
$chkcopy=@copy($img[‘src’], ‘images_extract/data/’.$imgtitle.’.’.$ext);
if($chkcopy)
{
echo $filenum.’) ‘.$img[‘src’].'<br>’;

$Successful++;
}
else
{
echo $filenum.’) ‘.$img[‘src’].'<br>’;

$Failed++;
}
}
else
{
$chkcopy=@copy($urlsrc.$img[‘src’], ‘images_extract/data/’.$imgtitle.’.’.$ext);
if($chkcopy)
{
echo $filenum.’) ‘.$urlsrc.$img[‘src’].'<br>’;

$Successful++;
}
else
{
echo $filenum.’) ‘.$urlsrc.$img[‘src’].'<br>’;

$Failed++;
}
}

$filenum++;
}

$Total=$filenum-1;

echo ‘Total Count: ‘.$Total.'<br>’;

echo ‘Successful Count: ‘.$Successful.'<br>’;

echo ‘Failed Count: ‘.$Failed.'<br>’;

?>

MYSQL Scroll LIST IN PHP

The programming code will list 12 records at a time from a data table contained within a MySQL database. It can scroll forwards and backwards by the same number of rows by clicking the labeled buttons above the list, “Next” and “Previous”. This is a simple to use utility and it works in a clean and seamless manner.

In this patch of code, you can see how the data table row counter is advanced forward by 12 rows in the code enclosed in the ifthen data structure beginning with “if ($HTTP_POST_VARS['submit_page_forward']) “. And it will go backwards by the same number in the programming under the ifthen data structure starting with “if ($HTTP_POST_VARS['submit_page_backward']) “. The PHP session variable, “$_SESSION[start_row]“, holds the first of the next 12 data records to be displayed in the scroll list. “$_SESSION[totalrecords]” is another session variable that contains the total number of records in the data table that is used to populate the scroll list. It is used to detect the end of the scroll list used with the forward scrolling function mentioned before.

<?php

session_start();  
// include the file containing log in constants.
include 'generic_config.php';

// redirect to home page.
if ($_POST['submit_return_to']) 
{
header("Location: http://www.generic.com/index.html");  
}

// redirect to comment posting page.
if ($_POST['submit_add_feedback']) 
{
header("Location: http://www.generic.com/submit_sheet_customer_feedback.php");  
}

// scroll forward 12 rows.
if ($HTTP_POST_VARS['submit_page_forward']) 
{
$_SESSION[start_row] = $_SESSION[start_row] + 12;
if ( $_SESSION[start_row] > $_SESSION[totalrecords] ) {
$_SESSION[start_row] = $_SESSION[start_row] - 12;
}
}

// scroll backward 12 rows.
if ($HTTP_POST_VARS['submit_page_backward']) 
{
$_SESSION[start_row] = $_SESSION[start_row] - 12;
if ( $_SESSION[start_row] < 0 ) {
$_SESSION[start_row] = 0;
}
}

?>

The display of the scroll list consists of a PHP script enclosed in a HTML form. When the site visitor clicks on the “Next” or “Previous” <input> element buttons, the form will send the selection to the server. It will then be handled by the code in the previous section of this article.

At the beginning of the PHP code within the HTML form (see below), a connection is made to the website’s server and the MySQL database is set. The predefined constants for the server and database connection can be found in the configuration file specified near the beginning of this web page, include 'generic_config.php';.

All the records in the customer_ feedbackdata table are queried by the PHP directive, $result=mysql_query("SELECT * FROM customer_feedback“) or die('Could not select table');. The total number of records in the data table is retrieved by another PHP directive, $total_records = mysql_num_rows($result);. Then that value is assigned to a session variable used by the forward scrolling function, $_SESSION[totalrecords] = $total_records;.

The contents of the “remarks” field from the data table is assigned to a PHP variable like this, $remark = mysql_result($result, $num, "remarks");. Then the variable is displayed on the scroll list like this, echo nl2br($remark);. This is done within a for loop data structure that repeats 12 times for each row to be displayed.

Also, note how the HTML is encapsulated within the PHP scripting language. The idea is to “weave” a HTML table into the fabric of PHP during the display of each of the 12 rows. This “weaving” technique is also applied to the PHP ifendif data structure that is used to enable and disable the navigation buttons located just above the row listing. I’m stuck on PHP coding!

Lastly, the queried resource is freed like this, mysql_free_result($result);. Then the server connection is closed like so, mysql_close($conn);.

<form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">

<?php

// make the sql connection then select database using constants from the 
// included configuration php file.
$conn = mysql_connect(DB_HOSTX, DB_USERX, DB_PASSWORDX) or die('Could not connect: ' . mysql_error());
$db_selected = mysql_select_db(DB_NAMEX, $conn) or die('Could not select database');   

// query the customer feedback records.
$result=mysql_query("SELECT * FROM customer_feedback") or die('Could not select table'); 
// the number of records in your result set; assign to the php session
// variable, $_SESSION[totalrecords].
$total_records = mysql_num_rows($result); 
$_SESSION[totalrecords] = $total_records;

// assign the current starting row to a row variable, '$num'.
$num = $_SESSION[start_row];

// encapsulate html with php code to display buttons for redirection
// operations as well as forward and backward scrolling.
echo "<p>";

echo "<input type=submit name=submit_return_to value='Home'>";
echo "<input type=submit name=submit_add_feedback value='Add Customer Feedback'>";

if ( $_SESSION[start_row] + 11 >= $_SESSION[totalrecords] || $_SESSION[totalrecords] < 11 ) {
echo "<input type=submit name=submit_page_forward value=Next disabled>";
} else {
echo "<input type=submit name=submit_page_forward value=Next>";
}
if ( $_SESSION[start_row] == 0 ) {
echo "<input type=submit name=submit_page_backward value=Previous disabled>";
} else {
echo "<input type=submit name=submit_page_backward value=Previous>";
}

echo "</p>";

// place displayed results in a html table.
echo "<table border='3' cellpadding='10' cellspacing='10'>";

// next, run the "for loop" to display the current 12 rows.
for ($rows = 0; $rows < 12; $rows++) {

if ($num < $total_records) {

// assign the customer feedback to a row variable from the current table record.
$remark = mysql_result($result, $num, "remarks");

echo "<tr>";    
echo "<td>";    
// display the customer service feedback remark.
echo nl2br($remark);
echo "</td>";    
echo "</tr>";    

}

// increment the row variable by one for the next table record.
$num++; 

}

echo "</table>";

// free the resource, '$result'.
mysql_free_result($result);
// close the server connection, '$conn'.
mysql_close($conn);

?>

 

Simple file uploader written in PHP

Simple file uploader written in PHP, can be used in different modules and it can be designed according to your needs.

 

<?

    $file = $_FILES['file'];
    $name = $_POST['name'];
    $path = $_POST['path'];
    $upload = $_POST['upload'];

    if(isset($upload)){

        if($file['name']){

            if($name){
                
                if(strlen($path) > 5){

                    move_uploaded_file($file['tmp_name'], $path.$name);
                    echo "<font color=green>File successfully uploaded!</font>";
                
                } else 
                    echo "<li> Please enter the path!";
            
            } else 
                echo "<li> Please put the file name!"; 

        } else 
            echo "<li> No file to upload";

        echo "<br /><hr />";
    }

?>

How to create Ajax based PHP application

JavaScript is a client side scripting language. It is executed on the client side by the web browsers that support JavaScript. JavaScript code only works in browsers that have JavaScript enabled. It supports the following programming patterns;

  • Object oriented
  • Imperative
  • Functional

JavaScript enhances the functionality of websites and web applications. It is used to perform activities like.

  • Display a message box
  • Animate text or images on a web page
  • Open a pop up window
  • Update only a single part of a webpage
  • Perform validations on the client side

The syntax for JavaScript was inspired by the C Language syntax. The code below shows a JavaScript code that displays a message box.

1
<script>alert('Hello World!');</script>

HERE,

  • “<script>…</script>” are the opening and closing tags for JavaScript code when embedded into an HTML document
  • “alert(…);” alert is the built in function that displays a message box.
  • “’Hello World!’ “ is the string parameter that is displayed on the message box.

XML is the acronym for Extensible Markup Language. It is used to encode messages in both human and machine readable formats. It’s like HTML but allows you to create your custom tags. For more details on XML, see the article on XML

AJAX is the acronym for Asynchronous JavaScript And XML. It is a technology that reduces the interactions between the server and client. It does this by updating only part of a web page rather than the whole page. The asynchronous interactions are initiated by JavaScript.

Why use AJAX?
  • It allows developing rich interactive web applications just like desktop applications.
  • Validation can be performed done as the user fills in a form without submitting it. This can be achieved using auto completion. The words that the user types in are submitted to the server for processing. The server responds with keywords that match what the user entered.
  • It can be used to populate a dropdown box depending on the value of another dropdown box
  • Data can be retrieved from the server and only a certain part of a page updated without loading the whole page. This is very useful for web page parts that load things like
    • Tweets
    • Comments
    • Users visiting the site etc.
Creating an Ajax application

We will create a simple application that allows users to search for popular PHP MVC frameworks. Our application will have a text box that users will type in the names of the framework. We will then use AJAX to search for a match then display the framework’s complete name just below the search form.

Creating the index page

Index.php

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
<html>
    <head>
        <title>PHP MVC Frameworks - Search Engine</title>
        <script type="text/javascript" src="http://cdn.guru99.com/auto_complete.js"></script>
    </head>
    <body>
        <h2>PHP MVC Frameworks - Search Engine</h2>
        <p><b>Type the first letter of the PHP MVC Framework</b></p>
        <form method="POST" action="index.php">
            <p><input type="text" size="40" id="txtHint"  onkeyup="showName(this.value)"></p>
        </form>
        <p>Matches: <span id="txtName"></span></p>
    </body>
</html>

HERE,

  • “onkeyup=”showName(this.value)”” executes the JavaScript function showName everytime a key is typed in the textbox. This feature is called auto complete
Creating the frameworks page

frameworks.php

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
<?php
$frameworks = array("CodeIgniter","Zend Framework","Cake PHP","Kohana") ;
$name = $_GET["name"];
if (strlen($name) > 0) {
    $match = "";
    for ($i = 0; $i < count($frameworks); $i++) {
        if (strtolower($name) == strtolower(substr($frameworks[$i], 0, strlen($name)))) {
            if ($match == "") {
                $match = $frameworks[$i];
            } else {
                $match = $match . " , " . $frameworks[$i];
            }
        }
    }
}
echo ($match == "") ? 'no match found' : $match;
?>

 

Creating the JS script

auto_complete.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
<script>
function showName(str){
    if (str.length == 0){ //exit function if nothing has been typed in the textbox
        document.getElementById("txtName").innerHTML=""; //clear previous results
        return;
    }
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            document.getElementById("txtName").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","frameworks.php?name="+str,true);
    xmlhttp.send();
}
</script>

HERE,

  • “if (str.length == 0)” check the length of the string. If it is 0, then the rest of the script is not executed.
  • “if (window.XMLHttpRequest)…” Internet Explorer versions 5 and 6 use ActiveXObject for AJAX implementation. Other versions and browsers such as Chrome, FireFox use XMLHttpRequest. This code will ensure that our application works in both IE 5 & 6 and other high versions of IE and browsers.
  • “xmlhttp.onreadystatechange=function…” checks if the AJAX interaction is complete and the status is 200 then updates the txtName span with the returned results.
Testing our application

Assuming you have saved the file index.php In phututs/ajax, browse to the URL  http://localhost/phptuts/ajax/index.php

ajax_index

Type the letter C in the text box You will get the following results.

ajax_results

The above example demonstrates the concept of AJAX and how it can help us create rich interaction applications.

  • AJAX is the acronym for Asynchronous JavaScript and XML
  • AJAX is a technology used to create rich interaction applications that reduce the interactions between the client and the server by updating only parts of the web page.
  • Internet Explorer version 5 and 6 use ActiveXObject to implement AJAX operations.
  • Internet explorer version 7 and above and browsers Chrome, Firefox, Opera, and Safari use XMLHttpRequest.

Traffic generator via tor (educational)

Set up several onions and just leave them open while you’re browsing through Tor. It’s best if it’s more than one in case anyone analyzing your traffic figures out what it is (they shouldn’t be able to see what address you connect to).

<?php if(empty(session_id())) {session_start();} ?><!DOCTYPE html>
<html>
<head>

<title>Traffic generator</title>
<?php
if(!isset($_SESSION[‘traffic_settings’])) {$_SESSION[‘traffic_settings’]=[
‘Minimum_refresh_rate’=>3,
‘Maximum_refresh_rate’=>300,
‘Minimum_content’=>0,
‘Maximum_content’=>100000
];}
if(count($_POST)>0) {foreach($_SESSION[‘traffic_settings’] as $k=>$v) {if(isset($_POST[$k]) && !empty($_POST[$k])) {$_SESSION[‘traffic_settings’][$k]=intval($_POST[$k]);}}}
$set=$_SESSION[‘traffic_settings’];
$refresh=rand($set[‘Minimum_refresh_rate’], $set[‘Maximum_refresh_rate’]);
?><meta http-equiv=”refresh” content=”<?php echo $refresh; ?>”>

</head>
<body>

<?php echo “Next refresh in $refresh seconds.nn”; ?><form method=”POST”><?php
foreach($set as $k=>$v) {echo “<div>$k: <input name=”$k” placeholder=”$v”></div>”;}
?><button type=”submit”>Submit</button></form>

<div style=”display:none”><?php for($t=0, $f=rand($set[‘Minimum_content’], $set[‘Maximum_content’]); $t<$f; $t++) {echo ‘0’;} ?></div>

</body>
</html>

PHP to feed a video list from a particular channel without Oauth

Youtube API for PHP to feed a video list from a particular channel without Oauth, this API only needs a Channel ID and Channel name. Youtube API is to demonstrate how to show video in our website without 0auth and API Key.

This API is created for only a website to display a video list from their channel without 0auth & API key!

Basic PHP codes are used to feed a video list.

//Enter Your Channel Name
$channel_name="xyz123";
//Enter Your ID
$channel="Uhjfhdkjhfdf454dfde";


// Google Gdata feed url is used to fetch videos from channel.
//
//->results=[2] this is used to how much videos present in feed list         
                $feedURL=urlencode('https://gdata.youtube.com/feeds/api/videos?author=
                '.$channel.'&start-index=1&max-results=2&orderby=published');
                if (@simplexml_load_file($feedURL))
                {
                    $sxml = simplexml_load_file($feedURL);//converts feedlist into XML
                    $counts = $sxml->children('http://a9.com/-/spec/opensearchrss/1.0/');
                    $total = $counts->totalResults;
                    foreach ($sxml->entry as $entry) {
                    $media = $entry->children('http://search.yahoo.com/mrss/');
                    $attrs = $media->group->player->attributes();
                    $watch = $attrs['url']; //URL of the video       
                    $yt = $media->children('http://gdata.youtube.com/schemas/2007');
                    $attrs = $yt->duration->attributes();
                    $length = $attrs['seconds'];  
                    $minute=floor($length/60);
                    $second=$length-$minute*60;        
                    $gd = $entry->children('http://schemas.google.com/g/2005');
                    if ($gd->rating) {
                          $attrs = $gd->rating->attributes();
                          $rating = $attrs['average'];
                    } else {
                          $rating = 0;
                    }
                    $attrs = $media->group->thumbnail[1]
                    ->attributes();//generate thumbnail for each video.
                    
              
...

Actually, it loads the video feed list from Google gdata URL. This simple API is to demonstrate how to show video in our website without 0auth.

PHP Useful Extensions, Utilities and Classes

  • SimplePie
    SimplePie is a PHP class that helps you work with RSS feeds. Check out the online RSS and Atom feed reader, which demonstrates a simple Web application that uses SimplePie. 
  • HTML Purifier
    HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier not only removes all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive white list, it also makes sure your documents are standards-compliant. Open source and highly customizable.
  • TCPDF
    TCPDF is an open-source PHP class for generating PDF documents.
  • htmlSQL
    htmlSQL is a unique tool. It is a PHP class for querying HTML values in an SQL-like syntax. Check out the live demonstration of how htmlSQL works.
  • The Greatest PHP Snippet File Ever (Using Quicktext for Notepad++)
    “A little something for all coders: a snippets file that I use for PHP coding. This is designed to be used with Quicktext for Notepad++, but feel free to adapt it to whatever text editor you prefer.”
  • Creole
    Creole is a database abstraction layer for PHP5. It abstracts PHP’s native database-specific API to create more portable code while also providing developers with a clean, fully object-oriented interface based loosely on the API for Java’s JDBC.
  • PHPLinq
    LINQ is a component that adds native data querying capabilities to PHP using a syntax reminiscent of SQL. It defines a set of query operators that can be used to query, project and filter data in arrays, enumerable classes, XML, relational databases and third-party data sources. [via]
  • PHPMathPublisher
    With PhpMathPublisher, you can publish mathematical documents on the Web using only a PHP script (no LaTeX programs on the server and no MathML). 
  • phpMyAdmin
    If you’re working with PHP, there’s a big chance you’re set up in a LAMP configuration. phpMyAdmin is Web-based tool for managing, building, importing, exporting and exploring MySQL databases.
  • PHPExcel
    PHPExcel is a set of useful PHP classes for working with Microsoft Excel files. PHPExcel allows you to read Excel files and write to them. This is useful for dynamically generating Excel spreadsheets for downloading.
  • Phormer
    Phormer is a PHP-based photo gallery management application that helps you to store, categorize and trim your photos online.
  • xajax PHP Class Library
    xajax is a PHP class for easily working with PHP AJAX applications. It gives you an easy-to-use API for quickly managing AJAX-related tasks. Check out the xajax Multiplier demo and the Graffiti Wall demo to see the xajax PHP class in action.
  • PHP User Class
    PHP User Class is an excellent script that helps you create a system for user authentication (i.e. registration, log in, account profile, etc.). It’s a useful utility to have around if you require user registration for your Web applications.
  • PHP-GTK
    PHP-GTK is a PHP extension for the GTK+ toolkit (a robust toolkit for developing GUIs). It is a suite of useful OOP functions and classes to help you rapidly build cross-platform, client-side GUI’s for your application.

PHP Image Manipulation and Graphs

  • PHP/SWF Charts
    PHP/SWF Charts is a powerful PHP tool that enables you to create attractive Web charts and graphs from dynamic data. You can use PHP scripts to generate and gather data from databases, then pass it to this tool to generate Flash (SWF) charts and graphs.
  • pChart – a chart-drawing PHP library
    pChart is a PHP class-oriented framework designed to create aliased charts. Most of today’s chart libraries have a cost; this one is free. Data can be retrieved from SQL queries or CSV files or can be manually provided. 
  • WideImage
    WideImage is a PHP library for dynamic image manipulation and processing for PHP 5. To be able to use the library, you should have the GD PHP extensioninstalled on your Web server.
  • MagickWand For PHP
    MagickWand For PHP is a PHP module suite for working with the ImageMagickAPI, which lets you create, compose and edit bitmap images. It’s a useful tool for quickly incorporating image-editing features in your PHP applications.

PHP Security Tools

Security Tools

  • Securimage
    Securimage is a free, open-source PHP CAPTCHA script for generating complex images and CAPTCHA codes to protect forms from spam and abuse.
  • Scavenger
    Scavenger is an open-source, real-time vulnerability management tool. It helps system administrators respond to vulnerability findings, track vulnerability findings and review accepted and false-positive answered vulnerabilities, without “nagging” them with old vulnerabilities.
  • PHP-IDS
    PHP-IDS (PHP-Intrusion Detection System) is a simple-to-use, well-structured, fast and state-of-the-art security layer for your PHP-based Web application.
  • Pixy: PHP Security Scanner
    Pixy is a Java program that performs automatic scans of PHP 4 source code, aimed to detect XSS and SQL injection vulnerabilities. Pixy takes a PHP program as input and creates a report that lists possible vulnerable points in the program, along with additional information for understanding the vulnerability.

PHP Testing and Optimization Tools

  • PHPUnit
    PHPUnit is a complete port of the popular JUnit unit testing suite to PHP 5. It’s a tool that helps you test your Web application’s stability and scalability. Writing test cases within the PHPUnit framework is easy; here’s how to do it.
  • SimpleTest
    SimpleTest is a straightforward unit-testing platform for PHP applications. To get up and running with SimpleTest quickly, read through this pragmatic tutorial that shows you how to create a new test case.
  • Selenium
    Selenium Remote Control (RC) is a test tool that allows you to write automated Web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser. It can be used in conjunction with PHPUnit to create and run automated tests within a Web browser.
  • PHP_CodeSniffer
    PHP_CodeSniffer is a PHP 5 script for detecting conformance to a predefined PHP coding standard. It’s a helpful tool for maintaining uniform coding styles for large projects and teams.
  • dBug
    dBug is ColdFusion’s cfDump for PHP. It’s a simple tool for outputting data tables that contain information about arrays, classes and objects, database resources and XML resources, making it very useful for debugging purposes.
  • PHP Profile Class
    PHP Profile Class is an excellent PHP profiling tool for your Web applications. Using this class will help you quickly and easily gain insight into which parts of your app could use some refactoring and optimization.

PHP Debugging Tools

  • Webgrind
    Webgrind is an Xdebug profiling Web front end in PHP 5. It implements a subset of the features of kcachegrind, installs in seconds and works on all platforms. For quick ‘n’ dirty optimizations, it does the job. 
  • Xdebug
    Xdebug is one of the most popular debugging PHP extensions. It provides a ton of useful data to help you quickly find bugs in your source code. Xdebug plugs right into many of the most popular PHP applications, such as PHPEclipse and phpDesigner.
  • Gubed PHP Debugger
    As the name implies, Gubed PHP Debugger is a PHP debugging tool for hunting down logic errors.
  • DBG
    DBG is a robust and popular PHP debugger for use in local and remote PHP debugging. It plugs into numerous PHP IDE’s and can easily be used with the command line.
  • PHP_Debug
    PHP_Debug is an open-source project that gives you useful information about your PHP code that can be used for debugging. It can output processing times of your PHP and SQL, check the performance of particular code blocks and get variable dumps in graphical form, which is great if you need a more visual output than the one given to you by print_r() or var_dump().
  • PHP_Dyn
    PHP_Dyn is another excellent PHP debugging tool that’s open-source. You can trace execution and get an output of the argument and return values of your functions.
  • MacGDBp
    MacGDBp is a live PHP debugger application for the Mac OS. It has all the features you’d expect from a fully featured debugger, such as the ability to step through your code and set breakpoints

CLOUDFARE BYPASSER

Hey, use it at your own risk!
YOUTUBE: https://www.youtube.com/channel/UC5DPee5R7vtFytLZAGRNg4A
PAGE: https://www.facebook.com/Middle.East.Cyber.Army
TWITTER: https://twitter.com/MiddleEastCyber
GROUP: https://www.facebook.com/groups/Middle.East.Cyber.Army/
==================================================================
<?php ${x47x4cx4fBAx4cS”}[x64x7ahrx6cx67mx77x78]=“six74x65;${x47x4cx4fBx41x4cx53}[x73gx6apx63xnlx6a]=x78;${x47x4cx4fx42Ax4cx53}[x71x76x61x7ax73x68lx61x63x6bx71x6d]=“ux72x6c;${x47x4cx4fBx41x4cx53}[x63x69wx76ex65x64x73x67x74l”]=x6dx61x74x63x68x65s”;${x47x4cOBALx53}[x62x6cjx77x67hx71x71x6ex6c]=“cox75nx74;$ciarvjpxqojr=x75x72x6c;${x47x4cOx42x41x4cx53}[x7ax71x73x6bbx74x68x68x78]=x73dox6d;${x47Lx4fx42x41Lx53}[“cx69x64tzmb”]=“sx65x72x76x65x72;${x47x4cx4fx42x41x4cx53}[x73btx63x6cx70z”]=x68ex61dx65x72x73;$ccmkdtr=“ux72x6c;${x47x4cx4fBALx53}[x78fx6cux6crk”]=“mx65;${x47x4cx4fBALS”}[x6ex71x70x71x79x69x64x65x6c]=x73x64om”;${“Gx4cx4fBx41Lx53}[“ox69x79mx63jx70nofj”]=“ix70;$ccklsifydxd=x75x72x6c;echo“#x20x43LOx55DFAREx20x42Yx50ASSEx52  Bx59x20x54x48x45 Gx52x45Ax54x45Sx54.n;echox23x20x43ODx45D x42x59 : THE x47REx41TEx53T (x20hx74tpx73://wwwx2efx61cx65x62x6fox6b.cox6d/x61x6cx6fux73hx69x31994 ).n;echo“#x20x43x4fDED Ix4ex20:x20x4diddx6ce Ex61x73t x43x79bex72 Armyx20x4cabx73.n;$vmkhoyhfc=“x”;echox23x20x50AGE:x20https://wwx77.fx61cex62oox6b.x63x6fx6d/Mx69x64dx6cx65x2ex45x61x73tx2eCx79x62x65x72.Ax72mx79.n;${x47x4cx4fx42x41Lx53}[“cx66x67x7ax6ax79ux70x73x69x76m”]=x75x72x6c;echox23x20GRx4fx55P : hx74x74ps://www.fax63ebx6fox6bx2ex63x6fm/grx6fx75ps/Mx69x64dlx65x2ex45x61x73x74.Cx79bex72x2ex41rx6dx79.n;${x47LOBx41x4cx53}[x6ahx66gx79x66x73xi”]=“urx6c;echox23 Tx57x49TTx45x52: x68tx74px73://twx69ttex72.cx6fx6d/x4dx69x64dx6cx65x45astCyx62ex72.n;${x47Lx4fx42x41Lx53}[x6cx67x77x66fx75x68x73]=x68x65x61x64x65x72s”;${x47x4cx4fx42Ax4cx53}[“bx75x63tqgx77x70xx76x6e]=x75rx6c;function is_ipv4($ip){return filter_var(${${x47x4cx4fx42x41Lx53}[x6fx69x79mcjx70x6eox66x6a]},FILTER_VALIDATE_IP,FILTER_FLAG_IPV4)?${${x47x4cx4fx42x41x4cx53}[x6fiymx63x6ax70x6eox66j”]}:“(Nx75x6cl)”;}${${“Gx4cx4fx42ALS”}[“xfx6culx72k”]}=$argv[0];${${“Gx4cx4fBx41Lx53}[“cx66x67x7ax6ax79x75x70x73ix76x6d]}=@$argv[1];if(!isset(${$ccmkdtr}))die(n[+]x20x55sax67e: phpx20{$me}x20x3curx6c>n[+] x45xample: x70hx70 {$me}x20hx74tp://x77x77x77.x77ebsitx65x2ex63omn);${x47LOx42x41Lx53}[x68x74x77x6ax63x70x6a]=x73x65x72x76x65r”;if(!preg_match(“/^(hx74tx70s?):x5c//(x77{3}|x773)x2e/i”,${$ccklsifydxd}))die(nURLx20x69x73 x69x6evax6cix64x2enx55RLx20mux73tx20x62x65x20fox72x6dattx65x64x20as:x20http(x73)://x77x77x77.”.preg_replace(“/^(x68ttx70x73?):/x5c//”,“”,${${“GLx4fx42x41Lx53}[“bux63x74x71x67wx70x78x76x6e]}).n(fx6fx72 cx6fx6dpatix62x69lityx20rx65ax73ox6ex73)n);${${x47Lx4fx42x41x4cx53}[x73bx74clx70z”]}=get_headers(${${“Gx4cOx42x41x4cS”}[x6ahfgx79x66sx78x69]},1);${${x47x4cx4fx42x41x4cx53}[x63ix64x74zx6dx62]}=${${“GLOx42ALx53}[“lx67x77x66x66x75hx73]}[x53ex72ver”];${x47x4cx4fx42x41x4cx53}[x71x71x78vx6ex72ux6f]=“urx6c;${${x47x4cOx42x41x4cS”}[x7aqx73x6bx62x74hhx”]}=array(x63px61nex6c.”,x66x74px2e,x6dx61x69l.”,x77x65bx6daix6c.”,x64ix72ex63t.”,x64ix72x65x63x74-connx65ct.”,x72ex63ox72dx2e,x73sl.”,x64x6ex73.”,“hex6cx70.”,“bx6cogx2e,“fx6fx72um.”);${${“GLx4fx42x41x4cx53}[“blx6ax77gx68x71qnx6c]}=count(${${“GLx4fx42x41x4cx53}[x6eqx70x71x79x69x64x65x6c]});if(preg_match(“/^(hx74tx70s?):x5c/x5c/(w{x33}|wx33)x2e/i”,${$ciarvjpxqojr},${${x47x4cx4fBx41x4cS”}[x63x69wx76ex65x64x73x67x74l”]})){if(${${x47x4cx4fx42Ax4cx53}[x63x69wx76x65x65x64x73gtx6c]}[2]!=“wx77x77){${${x47LOx42x41LS”}[“qx76ax7ax73x68x6cackx71x6d]}=preg_replace(“/^(x68x74tpx73?):x5c/x5c//”,“”,${${x47x4cOx42x41Lx53}[“qvax7ax73x68x6cx61x63kqm”]});}else{${x47x4cx4fx42x41Lx53}[x75x7asx76x74hux6ax72x6f]=“max74x63x68es”;$floxlvt=x75x72x6c;${${x47x4cOBx41x4cx53}[“qx76azsx68x6cx61x63x6bx71x6d]}=explode(${${x47x4cx4fBx41x4cS”}[x75x7ax73x76x74x68x75x6arx6f]}[0],${${x47LOBALS”}[x71x76ax7asx68lacx6bx71m”]});${$floxlvt}=${${“Gx4cx4fBx41Lx53}[x71vax7ax73x68x6cx61x63kx71x6d]}[1];}}if(is_array(${${x47Lx4fx42x41Lx53}[x68x74x77x6ax63px6a]}))${${“GLx4fx42x41x4cx53}[x63x69dtx7ax6db”]}=${${x47x4cOx42x41x4cx53}[x63x69x64tx7ax6db”]}[0];$tesyfrhqyv=x63x6fx75x6ex74;if(preg_match(“/x63x6cox75x64fx6carx65/x69,${${“GLx4fBAx4cS”}[x63idtzx6db”]}))echon[+] x43x6cox75dFlax72ex20dex74x65x63tx65x64:x20{$server}n;else echon[+]x20NOTx20Px52x4fTx45x43Tx45Dx20x42x59 x43Lx4fUx44x46x41Rx45 !!!,x20x50ROCx45Ex44INx47 Ax4ex59x57Ax59 !!x21.n;echo“[+] x49P: “.is_ipv4(gethostbyname(${${x47x4cx4fx42x41x4cx53}[x71x71x78x76x6erx75x6f]})).nn;${x47x4cOx42x41x4cx53}[x71x76x70dx66x72zx67]=x78;echo“[+]x20Sex61x72cx68inx67 fox72 morx65x20IP addx72esx73ex73.nn;for(${$vmkhoyhfc}=0;${${x47x4cx4fx42ALx53}[x71x76x70x64x66rx7ag”]}<${$tesyfrhqyv};${${x47x4cx4fx42ALx53}[“sx67x6ax70x63xx6elx6a]}++){$kkwryamm=“x”;$fwudonliq=x73x64x6fx6d;${x47x4cx4fx42Ax4cx53}[x72dx72x78jx68x67dx78x75x61x75]=“sx69te”;${${x47Lx4fx42ALx53}[x72x64rx78jx68gx64xx75ax75]}=${$fwudonliq}[${$kkwryamm}].${${“Gx4cOBx41x4cx53}[“qvx61x7ax73hx6cx61cx6bx71x6d]};$eotbnymob=x69x70;${$eotbnymob}=is_ipv4(gethostbyname(${${x47x4cx4fx42x41x4cx53}[x64x7ax68rx6cx67mx77x”]}));echox54x72x79ix6ex67 {$site}:x20{$ip}n;}echon[+]x20Finix73hx65x64x2en;
?>

holding image data on mysql

two things are needful fot holding image data on mysql

1/. A BLOB field so that the data is held truly 8 bit clean

2/. A way to inject it without trying to use tools designed for text.

I’ve used two methods. Both work.

(a) use the ‘load file’ command t tp transfer an image on disk to Msql.
It does however need special mysql privileges that are not always
available or safe..

2/. From PHP environment, I turn the image data into an enormous
hexadecimal number. MySQL seems able to understand that as niray data OK.

ie in PHP this is a valid way to include binary data in an UPDATE query

$query=sprintf(“update objects set thumbnail=0x%s, type=’%d’, uri=’%s’,
alt_text=’%s’, privilege_level=’%d’, filename=’%s’, size=’%d’,
content=0x%s, modified_by=’%d’, modified_on=now(), etag=md5(content)
where id=’%d'”, bin2hex($thumbnail), $mime,
$_POST[‘uri’],$_POST[‘descr’],$_POST[‘privilege_level’],$filename,
$size, bin2hex($code), $login_id,$id);

 

Suggestion box in PHP

Suggestion box in PHP

Basically you type something and the software will propose suggestions

Two parts code.

The first part it’s the HTML page 

 

<html>
<head>
<script>
function showHint(str) {
  if (str.length==0) { 
    document.getElementById(“txtHint”).innerHTML=””;
    return;
  }
  var xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open(“GET”,”gethint.php?q=”+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form> 
First name: <input type=”text” onkeyup=”showHint(this.value)”>
</form>
<p>Suggestions: <span id=”txtHint”></span></p>

</body>
</html>

 

Now the PHP code to be save as gethint.php

 

<?php
// Fill up array with names
$a[]=”Anna”;
$a[]=”Brittany”;
$a[]=”Cinderella”;
$a[]=”Diana”;
$a[]=”Eva”;
$a[]=”Fiona”;
$a[]=”Gunda”;
$a[]=”Hege”;
$a[]=”Inga”;
$a[]=”Johanna”;
$a[]=”Kitty”;
$a[]=”Linda”;
$a[]=”Nina”;
$a[]=”Ophelia”;
$a[]=”Petunia”;
$a[]=”Amanda”;
$a[]=”Raquel”;
$a[]=”Cindy”;
$a[]=”Doris”;
$a[]=”Eve”;
$a[]=”Evita”;
$a[]=”Sunniva”;
$a[]=”Tove”;
$a[]=”Unni”;
$a[]=”Violet”;
$a[]=”Liza”;
$a[]=”Elizabeth”;
$a[]=”Ellen”;
$a[]=”Wenche”;
$a[]=”Vicky”;

// get the q parameter from URL
$q=$_REQUEST[“q”]; $hint=””;

// lookup all hints from array if $q is different from “” 
if ($q !== “”) {
  $q=strtolower($q); $len=strlen($q);
  foreach($a as $name) {
    if (stristr($q, substr($name,0,$len))) {
      if ($hint===””) {
        $hint=$name;
      } else {
        $hint .= “, $name”;
      }
    }
  }
}

// Output “no suggestion” if no hint were found
// or output the correct values 
echo $hint===”” ? “no suggestion” : $hint;
?>

Image Verification for Form Submission

<?PHP
/////////////////////////////////////////////
//  send_imagever.php                      //
/////////////////////////////////////////////
session_start();
// set up some default values
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
$sessionvar = 'imageVerHash';
$imgWidth = 96;
$imgHeight = 36;
$borderThick = 1;
$numChars = 5;
// set up blank image pallet with borders
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$image = imagecreate($imgWidth, $imgHeight);
$bgColor = imagecolorallocate ($image, 255, 255, 255);
$textColor = imagecolorallocate ($image, 0, 0, 0);
// Initialize some values
// ~~~~~~~~~~~~~~~~~~~~~~
$numString = '';                // init string of numbers
$minX = $borderThick +2;        // first x position for chars
$minY = $borderThick +2;        // lowest y position for chars
srand(make_seed());             // seed the random generator
// Loop $numChars times, generate random char/font/offset
// and render to image object
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$idx = 0;
while ($idx < $numChars):
    // pick a font and calculate the character size for it
    $font = rand(3,5);          // pick a font (3,4,or5) 
    $fontWidth = imagefontwidth($font);
    $fontHeight = imagefontheight($font);      
    // pick a random digit and add it to the string
    if ($font > 4) {
        $char = rand(0,9);          // small zeroes are confusing
    }                                       // because they look like 8's
    else {                              // so avoid them
        $char = rand(1,9);         
    }
    $numString .= $char;
    $xOffset = $minX + rand(3,10);  // pick new x offset
    $minX = $xOffset + $fontWidth;  // new minX is right side of new char
    // pick a random Y offset (within available space)
    $maxY = $imgHeight - $borderThick - $fontHeight;
    $yOffset = rand($minY, $maxY);
    
    // render the character to the image
    imagechar ($image, $font, $xOffset, $yOffset, $char, $textColor);
    $idx++;
    
endwhile;
// draw border;
if ($borderThick > 0) {
    imagelinethick ($image, 1,1,$imgWidth,1,$textColor,$borderThick);
    imagelinethick ($image, 1,1,1,$imgHeight,$textColor,$borderThick);
    imagelinethick ($image, $imgWidth-$borderThick,1,$imgWidth-$borderThick,$imgHeight,$textColor,$borderThick);
    imagelinethick ($image, 1,$imgHeight-$borderThick,$imgWidth,$imgHeight-$borderThick,$textColor,$borderThick);
}
// save hash of string in session var
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$_SESSION[$sessionvar] = md5($numString);
// Send out enough headers so the image is NEVER cached by browsers
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// Send the image to the browser
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
header('Content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
return;
///////////////////////////////////////////////////////////////////////
//  This is just a fancy function to draw the borders                //
///////////////////////////////////////////////////////////////////////
function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
{
    if ($thick == 1) {
        return imageline($image, $x1, $y1, $x2, $y2, $color);
    }
    $t = $thick / 2 - 0.5;
    if ($x1 == $x2 || $y1 == $y2) {
        return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
    }
    $k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q
    $a = $t / sqrt(1 + pow($k, 2));
    $points = array(
        round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
        round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
        round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
        round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
    );
    imagefilledpolygon($image, $points, 4, $color);
    return imagepolygon($image, $points, 4, $color);
}
?>
<?PHP
/////////////////////////////////////////////
// stub_imgver.php                         //
/////////////////////////////////////////////
session_start();
if (    isset($_POST['submit']) &&
        isset($_POST['imagever']) &&
        isset($_SESSION['imageVerHash'])
    ) {
        $verstring = trim($_POST['imagever']);
        $formhash = md5($verstring);
        if ($formhash == trim($_SESSION['imageVerHash'])) {
            print "matched";
            unset($_SESSION['imageVerHash']);
        }
        else {
            unset($_SESSION['imageVerHash']);
            print "no match";
        }
}
else {
    print "
    
    <html>
        <head>
            <title>Image Verification Stub</title>
        </head>
        <body>
            <FORM ACTION="" . $_SERVER['PHP_SELF'] . "" NAME="myform"  METHOD="POST" ENCTYPE="application/x-www-form-urlencoded">
            <input type="text" name="imagever"><img src="send_imagever.php">
            <input type="submit" name="submit" value="SUBMIT">
            </form>
        </body>
    </html>
    ";
    
}
?>

php simple excel table

<?php
//
class
SimpleExcelCellsTypes {
const
None =0;
const
Numeric =1;
const
Date =2;
const
Text =3;
}
class
SimpleExcelSheets {
public
$named =null;
public
$fullfile =null;
public
$has_header =null;
public
$has_data =null;
public
$max_row =1;
}
class
SimpleExcel {
//
private
$ColumnText =array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV','BW','BX','BY','BZ','CA','CB','CC','CD','CE','CF','CG','CH','CI','CJ','CK','CL','CM','CN','CO','CP','CQ','CR','CS','CT','CU','CV','CW','CX','CY','CZ','DA','DB','DC','DD','DE','DF','DG','DH','DI','DJ','DK','DL','DM','DN','DO','DP','DQ','DR','DS','DT','DU','DV','DW','DX','DY','DZ','EA','EB','EC','ED','EE','EF','EG','EH','EI','EJ','EK','EL','EM','EN','EO','EP','EQ','ER','ES','ET','EU','EV','EW','EX','EY','EZ','FA','FB','FC','FD','FE','FF','FG','FH','FI','FJ','FK','FL','FM','FN','FO','FP','FQ','FR','FS','FT','FU','FV','FW','FX','FY','FZ','GA','GB','GC','GD','GE','GF','GG','GH','GI','GJ','GK','GL','GM','GN','GO','GP','GQ','GR','GS','GT','GU','GV','GW','GX','GY','GZ','HA','HB','HC','HD','HE','HF','HG','HH','HI','HJ','HK','HL','HM','HN','HO','HP','HQ','HR','HS','HT','HU','HV','HW','HX','HY','HZ','IA','IB','IC','ID','IE','IF','IG','IH','II','IJ','IK','IL','IM','IN','IO','IP','IQ','IR','IS','IT','IU','IV');
//
private
$Strings =array();
private
$Header =array();
//
private
$worksheets =array();
//
private
$DataFile ="";
//
private
$db =null;
//
public
$CreatedBy ="";
public
$Company ="";
//
private
$workbook ="";
private
$styles ="";
private
$sharedStrings ="";
private
$content_types ="";
private
$rels ="";
private
$app ="";
private
$core ="";
private
$xl_rels ="";
private
$theme1 ="";
private
$sheet1_rels ="";
//
private
$MaxColumn =0;
private
$MaxRow =0;
//
private
$ActiveSheet =0;
//
function
__construct() {
//
Create the SQLite database in memory at creation.
if
(is_null($this->db)) {
if ($this->db = new SQLite3(':memory:')) {
$this->db->exec('CREATE TABLE storage (sheet INT, row INT, column INT, data_type INT, original_value TEXT, date_value INT, text_index INT);');
} else {
}
}
//
$Sheet1 = new SimpleExcelSheets();
$Sheet1->named = "Sheet1";
$Sheet1->has_header = false;
$Sheet1->has_data = false;
$this->worksheets[] = $Sheet1;
//
$Sheet2 = new SimpleExcelSheets();
$Sheet2->named = "Sheet2";
$Sheet2->has_header = false;
$Sheet2->has_data = false;
$this->worksheets[] = $Sheet2;
//
$Sheet3 = new SimpleExcelSheets();
$Sheet3->named = "Sheet3";
$Sheet3->has_header = false;
$Sheet3->has_data = false;
$this->worksheets[] = $Sheet3;
//
}
//
function checkDatabase($clearData = false, $clearHeader = false) {
//
if (is_null($this->db)) {
$this->db = new SQLite3(':memory:');
$this->db->exec('CREATE TABLE storage (sheet INT, row INT, column INT, data_type INT, original_value TEXT, date_value INT, text_index INT);');
} else {
if ($clearData == true) {
$this->worksheets[$this->ActiveSheet]->has_data = false;
$this->db->exec("DELETE FROM storage WHERE sheet = {$this->ActiveSheet} AND row > 1;");
}
if ($clearHeader == true) {
$this->worksheets[$this->ActiveSheet]->has_header = false;
$this->db->exec("DELETE FROM storage WHERE sheet = {$this->ActiveSheet} AND row = 1;");
}
}
//
}
//
private function EscapeXML($text) {
return str_replace("%", "%", str_replace(">", ">", str_replace("
<", "<", str_replace("&", "&", $text))));
}
//
private function BuildFiles() {
//
// ------> /xl/workbook.xml as $workbook, simple container listing worksheets with their IDs.
;{
$this->workbook = "
<?xml version="1.0" encoding="utf-8" standalone="yes"?> ";
$this->workbook .= "
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">";
$this->workbook .= "    
<fileVersion appName="xl"lastEdited="4"lowestEdited="4"rupBuild="4506"/>";
$this->workbook .= "    
<workbookPr defaultThemeVersion="124226"/>";
$this->workbook .= "    
<bookViews>";
$this->workbook .= "        
<workbookView xWindow="240"yWindow="75"windowWidth="16140"windowHeight="10365"/>";
$this->workbook .= "    
</bookViews>";
$this->workbook .= "    
<sheets>";
foreach ($this->worksheets as $key=>$value) {
// Loop through all worksheets in the workbook.
$this->workbook .= "        
<sheet name="".$value->named."" sheetId="".(string)($key+1)."" r:id="rId".(string)($key+1)."" />";
// Use the name of the workbook and then the index (1 based) as the Sheet ID and the internal rId.
}
$this->workbook .= "    
</sheets>";
$this->workbook .= "    
<calcPr calcId="114210"/>";
$this->workbook .= "
</workbook>";
;}
// ------> /xl/styles.xml as $styles, container for all styles used in the workbook. Indexes (used as IDs) are 0 based.
;{
$this->styles = "
<?xml version="1.0" encoding="utf-8" standalone="yes"?> ";
$this->styles .= "
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">";
$this->styles .= "    
<fonts count="2">";
$this->styles .= "        
<font>";
$this->styles .= "            
<sz val="10"/>";
$this->styles .= "            
<name val="Arial"/>";
$this->styles .= "        
</font>";
$this->styles .= "        
<font>";
$this->styles .= "            
<b />";
$this->styles .= "            
<sz val="10"/>";
$this->styles .= "            
<name val="Arial"/>";
$this->styles .= "            
<family val="2"/>";
$this->styles .= "        
</font>";
$this->styles .= "    
</fonts>";
$this->styles .= "    
<fills count="3">";
$this->styles .= "        
<fill>";
$this->styles .= "            
<patternFill patternType="none"/>";
$this->styles .= "        
</fill>";
$this->styles .= "        
<fill>";
$this->styles .= "            
<patternFill patternType="gray125"/>";
$this->styles .= "        
</fill>";
$this->styles .= "        
<fill>";
$this->styles .= "            
<patternFill patternType="solid">";
$this->styles .= "                
<fgColor indexed="22"/>";
$this->styles .= "                
<bgColor indexed="64"/>";
$this->styles .= "            
</patternFill>";
$this->styles .= "        
</fill>";
$this->styles .= "    
</fills>";
$this->styles .= "    
<borders count="2">";
$this->styles .= "        
<border>";
$this->styles .= "            
<left />";
$this->styles .= "            
<right />";
$this->styles .= "            
<top />";
$this->styles .= "            
<bottom />";
$this->styles .= "            
<diagonal />";
$this->styles .= "        
</border>";
$this->styles .= "        
<border>";
$this->styles .= "            
<left style="thin">";
$this->styles .= "                
<color indexed="64"/>";
$this->styles .= "            
</left>";
$this->styles .= "            
<right style="thin">";
$this->styles .= "                
<color indexed="64"/>";
$this->styles .= "            
</right>";
$this->styles .= "            
<top style="thin">";
$this->styles .= "                
<color indexed="64"/>";
$this->styles .= "            
</top>";
$this->styles .= "            
<bottom style="thin">";
$this->styles .= "                
<color indexed="64"/>";
$this->styles .= "            
</bottom>";
$this->styles .= "            
<diagonal />";
$this->styles .= "        
</border>";
$this->styles .= "    
</borders>";
$this->styles .= "    
<cellStyleXfs count="1">";
$this->styles .= "        
<xf numFmtId="0"fontId="0"fillId="0"borderId="0"/>";
$this->styles .= "    
</cellStyleXfs>";
$this->styles .= "    
<cellXfs count="3">";
$this->styles .= "        
<xf numFmtId="0"fontId="0"fillId="0"borderId="0"xfId="0"/>";
$this->styles .= "        
<xf numFmtId="0"fontId="1"fillId="2"borderId="1"xfId="0"applyFont="1"applyFill="1"applyBorder="1"applyAlignment="1">";
$this->styles .= "            
<alignment horizontal="center"/>";
$this->styles .= "        
</xf>";
$this->styles .= "        
<xf numFmtId="14"fontId="0"fillId="0"borderId="0"xfId="0"applyNumberFormat="1"/>";
$this->styles .= "    
</cellXfs>";
$this->styles .= "    
<cellStyles count="1">";
$this->styles .= "        
<cellStyle name="Normal"xfId="0"builtinId="0"/>";
$this->styles .= "    
</cellStyles>";
$this->styles .= "    
<dxfs count="0"/>";
$this->styles .= "    
<tableStyles count="0"defaultTableStyle="TableStyleMedium9"defaultPivotStyle="PivotStyleLight16"/>";
$this->styles .= "
</styleSheet>";
;}
// ------> /xl/sharedStrings.xml as $sharedStrings
;{
$this->sharedStrings = "
<?xml version="1.0" encoding="utf-8" standalone="yes"?> ";
$this->sharedStrings .= "
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"count="".(string)count($this->Strings)."" uniqueCount="".(string)count($this->Strings)."">";
foreach ($this->Strings as $value) {
$this->sharedStrings .= "    
<si><t>".$this->EscapeXML($value)."</t></si>";
}
$this->sharedStrings .= "
</sst>";
;}
// ------> /xl/worksheets/sheet1.xml as $Sheet1
;{
foreach ($this->worksheets as $key=>$value) {
while (true) {
$value->fullfile = sys_get_temp_dir().'/'.uniqid('SimpleExcel', true).'.xml';
if (!file_exists($value->fullfile)) break;
}
if (!$f = fopen($value->fullfile, 'w')) {exit;}
if ($value->has_header == false && $value->has_data == false) {
fwrite($f, "
<?xml version="1.0" encoding="utf-8" standalone="yes"?> ");
fwrite($f, "
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">");
fwrite($f, "    
<dimension ref="A1"/>");
fwrite($f, "    
<sheetViews>");
fwrite($f, "        
<sheetView workbookViewId="0"/>");
fwrite($f, "    
</sheetViews>");
fwrite($f, "    
<sheetFormatPr defaultRowHeight="12.75"/>");
fwrite($f, "    
<sheetData />");
fwrite($f, "    
<phoneticPr fontId="0"type="noConversion"/>");
fwrite($f, "    
<pageMargins left="0.75"right="0.75"top="1"bottom="1"header="0.5"footer="0.5"/>");
fwrite($f, "    
<headerFooter alignWithMargins="0"/>");
fwrite($f, "
</worksheet>");
} else {
fwrite($f, "
<?xml version="1.0" encoding="utf-8" standalone="yes"?> ");
fwrite($f, "
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">");
fwrite($f, "    
<dimension ref="A1:".$this->ColumnText[$this->MaxColumn].(string)($value->max_row)."" />");
fwrite($f, "    
<sheetViews>");
if ($key == 0) {
fwrite($f, "        
<sheetView tabSelected="1"workbookViewId="0">");
} else {
fwrite($f, "        
<sheetView tabSelected="0"workbookViewId="0">");
}
fwrite($f, "            
<selection activeCell="A1"sqref="A1"/>");
fwrite($f, "        
</sheetView>");
fwrite($f, "    
</sheetViews>");
fwrite($f, "    
<sheetFormatPr defaultRowHeight="12.75"/>");
fwrite($f, "    
<cols>");
fwrite($f, "        
<col min="1"max="".(string)$this->MaxColumn."" width="10.140625" bestFit="1" customWidth="1" />");
fwrite($f, "    
</cols>");
fwrite($f, "    
<sheetData>");
$column = 1;
$row_index = 0;
$results = $this->db->query("SELECT s1.row, (SELECT count(s2.column) FROM storage s2 WHERE s2.sheet = s1.sheet AND s2.row = s1.row) as column_count, s1.column, s1.data_type, s1.original_value, s1.date_value, s1.text_index FROM storage s1 WHERE s1.sheet = $key ORDER BY s1.row, s1.column;");
while ($e = $results->fetchArray(SQLITE3_NUM)) {
if ($e[0] != $row_index) {
if ($e[0] > 1) {fwrite($f, "        
</row>");}
fwrite($f, "        
<row r="{$e[0]}"spans="1:".$e[1]."">");
$row_index = $e[0];
}
if ($e[0] == 1) {
fwrite($f, "            
<c r="".$this->ColumnText[$e[2]-1].(string)$e[0]."" s="1" t="s">");
fwrite($f, "                
<v>".$e[6]."</v>");
} else {
switch ($e[3]) {
case SimpleExcelCellsTypes::None:
fwrite($f, "            
<c r="".$this->ColumnText[$e[2]-1].(string)$e[0]."">");
fwrite($f, "                
<v></v>");
break;
case SimpleExcelCellsTypes::Numeric:
fwrite($f, "            
<c r="".$this->ColumnText[$e[2]-1].(string)$e[0]."">");
fwrite($f, "                
<v>".$e[4]."</v>");
break;
case SimpleExcelCellsTypes::Text:
fwrite($f, "            
<c r="".$this->ColumnText[$e[2]-1].(string)$e[0]."" t="s">");
fwrite($f, "                
<v>".$e[6]."</v>");
break;
case SimpleExcelCellsTypes::Date:
fwrite($f, "            
<c r="".$this->ColumnText[$e[2]-1].(string)$e[0]."" s="2">");
fwrite($f, "                
<v>".(string)round(25569 + ($e[5] / 86400), 0, PHP_ROUND_HALF_DOWN)."</v>");
break;
default:
fwrite($f, "            
<c r="".$this->ColumnText[$e[2]-1].(string)$e[0]."">");
fwrite($f, "                
<v>".$e[4]."</v>");
break;
}
}
fwrite($f, "            
</c>");
}
fwrite($f, "        
</row>");
fwrite($f, "    
</sheetData>");
fwrite($f, "    
<phoneticPr fontId="0"type="noConversion"/>");
fwrite($f, "    
<pageMargins left="0.75"right="0.75"top="1"bottom="1"header="0.5"footer="0.5"/>");
fwrite($f, "    
<pageSetup orientation="portrait"verticalDpi="0"r:id="rId1"/>");
fwrite($f, "    
<headerFooter alignWithMargins="0"/>");
fwrite($f, "
</worksheet>");
}
fclose($f);
}
;}
// ------> /[Content_Types].xml as $content_types
;{
$this->content_types = "
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> ";
$this->content_types .= "
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">";
$this->content_types .= "    
<Override PartName="/xl/theme/theme1.xml"ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>";
$this->content_types .= "    
<Override PartName="/xl/styles.xml"ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>";
$this->content_types .= "    
<Default Extension="rels"ContentType="application/vnd.openxmlformats-package.relationships+xml"/>";
$this->content_types .= "    
<Default Extension="xml"ContentType="application/xml"/>";
$this->content_types .= "    
<Override PartName="/xl/workbook.xml"ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>";
$this->content_types .= "    
<Override PartName="/docProps/app.xml"ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>";
//
foreach ($this->worksheets as $key=>$value) {
$this->content_types .= "    
<Override PartName="/xl/worksheets/sheet".(string)($key+1).".xml"ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>";
}
//
$this->content_types .= "    
<Override PartName="/xl/sharedStrings.xml"ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>";
$this->content_types .= "    
<Override PartName="/docProps/core.xml"ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>";
$this->content_types .= "
</Types>";
;}
// ------> /_rels/.rels as $rels
;{
$this->rels = "
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> ";
$this->rels .= "
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">";
$this->rels .= "    
<Relationship Id="rId3"Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"Target="docProps/app.xml"/>";
$this->rels .= "    
<Relationship Id="rId2"Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"Target="docProps/core.xml"/>";
$this->rels .= "    
<Relationship Id="rId1"Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"Target="xl/workbook.xml"/>";
$this->rels .= "
</Relationships>";
;}
// ------> /docProps/app.xml as $app
;{
$this->app = "
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> ";
$this->app .= "
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">";
$this->app .= "    
<Application>Microsoft Excel</Application>";
$this->app .= "    
<DocSecurity>0</DocSecurity>";
$this->app .= "    
<ScaleCrop>false</ScaleCrop>";
$this->app .= "    
<HeadingPairs>";
$this->app .= "        
<vt:vector size="2"baseType="variant">";
$this->app .= "            
<vt:variant>";
$this->app .= "                
<vt:lpstr>Worksheets</vt:lpstr>";
$this->app .= "            
</vt:variant>";
$this->app .= "            
<vt:variant>";
$this->app .= "                
<vt:i4>".(string)count($this->worksheets)."</vt:i4>";
$this->app .= "            
</vt:variant>";
$this->app .= "        
</vt:vector>";
$this->app .= "    
</HeadingPairs>";
$this->app .= "    
<TitlesOfParts>";
$this->app .= "        
<vt:vector size="".(string)count($this->worksheets)."" baseType="lpstr">";
foreach ($this->worksheets as $key=>$value) {
$this->app .= "        
<vt:lpstr>".$value->named."</vt:lpstr>";
}
$this->app .= "        
</vt:vector>";
$this->app .= "    
</TitlesOfParts>";
$this->app .= "    
<Company>{$this->Company}</Company>";
$this->app .= "    
<LinksUpToDate>false</LinksUpToDate>";
$this->app .= "    
<SharedDoc>false</SharedDoc>";
$this->app .= "    
<HyperlinksChanged>false</HyperlinksChanged>";
$this->app .= "    
<AppVersion>12.0000</AppVersion>";
$this->app .= "
</Properties>";
;}
// ------> /docProps/core.xml as $core
;{
$this->core = "
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> ";
$this->core .="
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"xmlns:dc="http://purl.org/dc/elements/1.1/"xmlns:dcterms="http://purl.org/dc/terms/"xmlns:dcmitype="http://purl.org/dc/dcmitype/"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">";
$this->core .= "    
<dc:creator>{$this->CreatedBy}</dc:creator>";
$this->core .= "    
<dcterms:created xsi:type="dcterms:W3CDTF">2012-12-06T16:50:38Z</dcterms:created>";
$this->core .= "
</cp:coreProperties>";
;}
// ------> /xl/_rels/workbook.xml.rels as $xl_rels
;{
$this->xl_rels = "
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> ";
$this->xl_rels .= "
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">";
foreach ($this->worksheets as $key=>$value) {
$this->xl_rels .= "    
<Relationship Id="rId".(string)($key+1).""Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"Target="worksheets/sheet".(string)($key+1).".xml"/>";
}
$this->xl_rels .= "    
<Relationship Id="rId".(string)(count($this->worksheets)+3)."" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>";
$this->xl_rels .= "    
<Relationship Id="rId".(string)(count($this->worksheets)+2)."" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>";
$this->xl_rels .= "    
<Relationship Id="rId".(string)(count($this->worksheets)+1)."" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/>";
$this->xl_rels .= "
</Relationships>";
;}
// ------> /xl/theme/theme1.xml as $theme1
;{
$this->theme1 = "
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> ";
$this->theme1 .= "<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">";
$this->theme1 .= "    <a:themeElements>";
$this->theme1 .= "        <a:clrScheme name="Office">";
$this->theme1 .= "            <a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>";
$this->theme1 .= "            <a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>";
$this->theme1 .= "            <a:dk2><a:srgbClr val="1F497D"/></a:dk2>";
$this->theme1 .= "            <a:lt2><a:srgbClr val="EEECE1"/></a:lt2>";
$this->theme1 .= "            <a:accent1><a:srgbClr val="4F81BD"/></a:accent1>";
$this->theme1 .= "            <a:accent2><a:srgbClr val="C0504D"/></a:accent2>";
$this->theme1 .= "            <a:accent3><a:srgbClr val="9BBB59"/></a:accent3>";
$this->theme1 .= "            <a:accent4><a:srgbClr val="8064A2"/></a:accent4>";
$this->theme1 .= "            <a:accent5><a:srgbClr val="4BACC6"/></a:accent5>";
$this->theme1 .= "            <a:accent6><a:srgbClr val="F79646"/></a:accent6>";
$this->theme1 .= "            <a:hlink><a:srgbClr val="0000FF"/></a:hlink>";
$this->theme1 .= "            <a:folHlink><a:srgbClr val="800080"/></a:folHlink>";
$this->theme1 .= "        </a:clrScheme>";
$this->theme1 .= "        <a:fontScheme name="Office">";
$this->theme1 .= "            <a:majorFont>";
$this->theme1 .= "                <a:latin typeface="Cambria"/>";
$this->theme1 .= "                <a:ea typeface=""/>";
$this->theme1 .= "                <a:cs typeface=""/>";
$this->theme1 .= "                <a:font script="Jpan" typeface="MS P????"/>";
$this->theme1 .= "                <a:font script="Hang" typeface="?? ??"/>";
$this->theme1 .= "                <a:font script="Hans" typeface="??"/>";
$this->theme1 .= "                <a:font script="Hant" typeface="????"/>";
$this->theme1 .= "                <a:font script="Arab" typeface="Times New Roman"/>";
$this->theme1 .= "                <a:font script="Hebr" typeface="Times New Roman"/>";
$this->theme1 .= "                <a:font script="Thai" typeface="Tahoma"/>";
$this->theme1 .= "                <a:font script="Ethi" typeface="Nyala"/>";
$this->theme1 .= "                <a:font script="Beng" typeface="Vrinda"/>";
$this->theme1 .= "                <a:font script="Gujr" typeface="Shruti"/>";
$this->theme1 .= "                <a:font script="Khmr" typeface="MoolBoran"/>";
$this->theme1 .= "                <a:font script="Knda" typeface="Tunga"/>";
$this->theme1 .= "                <a:font script="Guru" typeface="Raavi"/>";
$this->theme1 .= "                <a:font script="Cans" typeface="Euphemia"/>";
$this->theme1 .= "                <a:font script="Cher" typeface="Plantagenet Cherokee"/>";
$this->theme1 .= "                <a:font script="Yiii" typeface="Microsoft Yi Baiti"/>";
$this->theme1 .= "                <a:font script="Tibt" typeface="Microsoft Himalaya"/>";
$this->theme1 .= "                <a:font script="Thaa" typeface="MV Boli"/>";
$this->theme1 .= "                <a:font script="Deva" typeface="Mangal"/>";
$this->theme1 .= "                <a:font script="Telu" typeface="Gautami"/>";
$this->theme1 .= "                <a:font script="Taml" typeface="Latha"/>";
$this->theme1 .= "                <a:font script="Syrc" typeface="Estrangelo Edessa"/>";
$this->theme1 .= "                <a:font script="Orya" typeface="Kalinga"/>";
$this->theme1 .= "                <a:font script="Mlym" typeface="Kartika"/>";
$this->theme1 .= "                <a:font script="Laoo" typeface="DokChampa"/>";
$this->theme1 .= "                <a:font script="Sinh" typeface="Iskoola Pota"/>";
$this->theme1 .= "                <a:font script="Mong" typeface="Mongolian Baiti"/>";
$this->theme1 .= "                <a:font script="Viet" typeface="Times New Roman"/>";
$this->theme1 .= "                <a:font script="Uigh" typeface="Microsoft Uighur"/>";
$this->theme1 .= "            </a:majorFont>";
$this->theme1 .= "            <a:minorFont>";
$this->theme1 .= "                <a:latin typeface="Calibri"/>";
$this->theme1 .= "                <a:ea typeface=""/>";
$this->theme1 .= "                <a:cs typeface=""/>";
$this->theme1 .= "                <a:font script="Jpan" typeface="MS P????"/>";
$this->theme1 .= "                <a:font script="Hang" typeface="?? ??"/>";
$this->theme1 .= "                <a:font script="Hans" typeface="??"/>";
$this->theme1 .= "                <a:font script="Hant" typeface="????"/>";
$this->theme1 .= "                <a:font script="Arab" typeface="Arial"/>";
$this->theme1 .= "                <a:font script="Hebr" typeface="Arial"/>";
$this->theme1 .= "                <a:font script="Thai" typeface="Tahoma"/>";
$this->theme1 .= "                <a:font script="Ethi" typeface="Nyala"/>";
$this->theme1 .= "                <a:font script="Beng" typeface="Vrinda"/>";
$this->theme1 .= "                <a:font script="Gujr" typeface="Shruti"/>";
$this->theme1 .= "                <a:font script="Khmr" typeface="DaunPenh"/>";
$this->theme1 .= "                <a:font script="Knda" typeface="Tunga"/>";
$this->theme1 .= "                <a:font script="Guru" typeface="Raavi"/>";
$this->theme1 .= "                <a:font script="Cans" typeface="Euphemia"/>";
$this->theme1 .= "                <a:font script="Cher" typeface="Plantagenet Cherokee"/>";
$this->theme1 .= "                <a:font script="Yiii" typeface="Microsoft Yi Baiti"/>";
$this->theme1 .= "                <a:font script="Tibt" typeface="Microsoft Himalaya"/>";
$this->theme1 .= "                <a:font script="Thaa" typeface="MV Boli"/>";
$this->theme1 .= "                <a:font script="Deva" typeface="Mangal"/>";
$this->theme1 .= "                <a:font script="Telu" typeface="Gautami"/>";
$this->theme1 .= "                <a:font script="Taml" typeface="Latha"/>";
$this->theme1 .= "                <a:font script="Syrc" typeface="Estrangelo Edessa"/>";
$this->theme1 .= "                <a:font script="Orya" typeface="Kalinga"/>";
$this->theme1 .= "                <a:font script="Mlym" typeface="Kartika"/>";
$this->theme1 .= "                <a:font script="Laoo" typeface="DokChampa"/>";
$this->theme1 .= "                <a:font script="Sinh" typeface="Iskoola Pota"/>";
$this->theme1 .= "                <a:font script="Mong" typeface="Mongolian Baiti"/>";
$this->theme1 .= "                <a:font script="Viet" typeface="Arial"/>";
$this->theme1 .= "                <a:font script="Uigh" typeface="Microsoft Uighur"/>";
$this->theme1 .= "            </a:minorFont>";
$this->theme1 .= "        </a:fontScheme>";
$this->theme1 .= "        <a:fmtScheme name="Office">";
$this->theme1 .= "            <a:fillStyleLst>";
$this->theme1 .= "                <a:solidFill>";
$this->theme1 .= "                    <a:schemeClr val="phClr"/>";
$this->theme1 .= "                </a:solidFill>";
$this->theme1 .= "                <a:gradFill rotWithShape="1">";
$this->theme1 .= "                    <a:gsLst>";
$this->theme1 .= "                        <a:gs pos="0">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                                <a:tint val="50000"/>";
$this->theme1 .= "                                <a:satMod val="300000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                        <a:gs pos="35000">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                                <a:tint val="37000"/>";
$this->theme1 .= "                                <a:satMod val="300000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                        <a:gs pos="100000">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                                <a:tint val="15000"/>";
$this->theme1 .= "                                <a:satMod val="350000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                    </a:gsLst>";
$this->theme1 .= "                    <a:lin ang="16200000" scaled="1"/>";
$this->theme1 .= "                </a:gradFill>";
$this->theme1 .= "                <a:gradFill rotWithShape="1">";
$this->theme1 .= "                    <a:gsLst>";
$this->theme1 .= "                        <a:gs pos="0">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                                <a:shade val="51000"/>";
$this->theme1 .= "                                <a:satMod val="130000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                        <a:gs pos="80000">";
$this->theme1 .= "                        <a:schemeClr val="phClr"><a:shade val="93000"/><a:satMod val="130000"/></a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                        <a:gs pos="100000">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                                <a:shade val="94000"/>";
$this->theme1 .= "                                <a:satMod val="135000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                    </a:gsLst>";
$this->theme1 .= "                    <a:lin ang="16200000" scaled="0"/>";
$this->theme1 .= "                </a:gradFill>";
$this->theme1 .= "                </a:fillStyleLst>";
$this->theme1 .= "            <a:lnStyleLst>";
$this->theme1 .= "                <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr">";
$this->theme1 .= "                    <a:solidFill>";
$this->theme1 .= "                        <a:schemeClr val="phClr">";
$this->theme1 .= "                            <a:shade val="95000"/>";
$this->theme1 .= "                            <a:satMod val="105000"/>";
$this->theme1 .= "                        </a:schemeClr>";
$this->theme1 .= "                    </a:solidFill>";
$this->theme1 .= "                    <a:prstDash val="solid"/>";
$this->theme1 .= "                </a:ln>";
$this->theme1 .= "                <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr">";
$this->theme1 .= "                    <a:solidFill>";
$this->theme1 .= "                        <a:schemeClr val="phClr"/>";
$this->theme1 .= "                    </a:solidFill>";
$this->theme1 .= "                    <a:prstDash val="solid"/>";
$this->theme1 .= "                </a:ln>";
$this->theme1 .= "                <a:ln w="38100" cap="flat" cmpd="sng" algn="ctr">";
$this->theme1 .= "                    <a:solidFill>";
$this->theme1 .= "                        <a:schemeClr val="phClr"/>";
$this->theme1 .= "                    </a:solidFill>";
$this->theme1 .= "                    <a:prstDash val="solid"/>";
$this->theme1 .= "                </a:ln>";
$this->theme1 .= "            </a:lnStyleLst>";
$this->theme1 .= "            <a:effectStyleLst>";
$this->theme1 .= "                <a:effectStyle>";
$this->theme1 .= "                    <a:effectLst>";
$this->theme1 .= "                        <a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0">";
$this->theme1 .= "                            <a:srgbClr val="000000">";
$this->theme1 .= "                                <a:alpha val="38000"/>";
$this->theme1 .= "                            </a:srgbClr>";
$this->theme1 .= "                        </a:outerShdw>";
$this->theme1 .= "                    </a:effectLst>";
$this->theme1 .= "                </a:effectStyle>";
$this->theme1 .= "                <a:effectStyle>";
$this->theme1 .= "                    <a:effectLst>";
$this->theme1 .= "                        <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0">";
$this->theme1 .= "                            <a:srgbClr val="000000">";
$this->theme1 .= "                                <a:alpha val="35000"/>";
$this->theme1 .= "                            </a:srgbClr>";
$this->theme1 .= "                        </a:outerShdw>";
$this->theme1 .= "                    </a:effectLst>";
$this->theme1 .= "                </a:effectStyle>";
$this->theme1 .= "                <a:effectStyle>";
$this->theme1 .= "                    <a:effectLst>";
$this->theme1 .= "                        <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0">";
$this->theme1 .= "                            <a:srgbClr val="000000">";
$this->theme1 .= "                                <a:alpha val="35000"/>";
$this->theme1 .= "                            </a:srgbClr>";
$this->theme1 .= "                        </a:outerShdw>";
$this->theme1 .= "                    </a:effectLst>";
$this->theme1 .= "                    <a:scene3d>";
$this->theme1 .= "                        <a:camera prst="orthographicFront">";
$this->theme1 .= "                            <a:rot lat="0" lon="0" rev="0"/>";
$this->theme1 .= "                        </a:camera>";
$this->theme1 .= "                        <a:lightRig rig="threePt" dir="t">";
$this->theme1 .= "                            <a:rot lat="0" lon="0" rev="1200000"/>";
$this->theme1 .= "                        </a:lightRig>";
$this->theme1 .= "                    </a:scene3d>";
$this->theme1 .= "                    <a:sp3d>";
$this->theme1 .= "                        <a:bevelT w="63500" h="25400"/>";
$this->theme1 .= "                    </a:sp3d>";
$this->theme1 .= "                </a:effectStyle>";
$this->theme1 .= "            </a:effectStyleLst>";
$this->theme1 .= "            <a:bgFillStyleLst>";
$this->theme1 .= "                <a:solidFill>";
$this->theme1 .= "                <a:schemeClr val="phClr"/>";
$this->theme1 .= "                </a:solidFill>";
$this->theme1 .= "                <a:gradFill rotWithShape="1">";
$this->theme1 .= "                    <a:gsLst>";
$this->theme1 .= "                        <a:gs pos="0">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                            <a:tint val="40000"/>";
$this->theme1 .= "                            <a:satMod val="350000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                        <a:gs pos="40000">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                            <a:tint val="45000"/>";
$this->theme1 .= "                            <a:shade val="99000"/>";
$this->theme1 .= "                            <a:satMod val="350000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                        <a:gs pos="100000">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                                <a:shade val="20000"/>";
$this->theme1 .= "                                <a:satMod val="255000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                    </a:gsLst>";
$this->theme1 .= "                    <a:path path="circle">";
$this->theme1 .= "                        <a:fillToRect l="50000" t="-80000" r="50000" b="180000"/>";
$this->theme1 .= "                    </a:path>";
$this->theme1 .= "                </a:gradFill>";
$this->theme1 .= "                <a:gradFill rotWithShape="1">";
$this->theme1 .= "                    <a:gsLst>";
$this->theme1 .= "                        <a:gs pos="0">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                                <a:tint val="80000"/>";
$this->theme1 .= "                                <a:satMod val="300000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                        <a:gs pos="100000">";
$this->theme1 .= "                            <a:schemeClr val="phClr">";
$this->theme1 .= "                                <a:shade val="30000"/>";
$this->theme1 .= "                                <a:satMod val="200000"/>";
$this->theme1 .= "                            </a:schemeClr>";
$this->theme1 .= "                        </a:gs>";
$this->theme1 .= "                    </a:gsLst>";
$this->theme1 .= "                    <a:path path="circle">";
$this->theme1 .= "                        <a:fillToRect l="50000" t="50000" r="50000" b="50000"/>";
$this->theme1 .= "                    </a:path>";
$this->theme1 .= "                </a:gradFill>";
$this->theme1 .= "            </a:bgFillStyleLst>";
$this->theme1 .= "        </a:fmtScheme>";
$this->theme1 .= "    </a:themeElements>";
$this->theme1 .= "    <a:objectDefaults/>";
$this->theme1 .= "    <a:extraClrSchemeLst/>";
$this->theme1 .= "</a:theme>";
;}
//
}
//
private function IsDate($Value) {
// I lost where I stole this from and I can't seem to find the post.  Stackoverflow, I think.
$formats = array("m/d/Y", "Ymd", "Y-m-d");
foreach ($formats as $format) {
$date = DateTime::createFromFormat($format, $Value);
if ($date == false)
return false;
else
return $date->sub(new DateInterval('P1D'))->getTimestamp();
}
}
//
private function AddStringToArray($Value) {
$Result = array_key_exists($Value, $this->Strings);
if ($Result != false) {
return $Result;
} else {
return array_push($this->Strings, $Value) - 1;
// Returns the new array count so, subtract one for the index of the string.
}
}
//
public function SetHeader($Header) {
//
checkDatabase(false, true);
//
$column_index = 1;
foreach ($Header as $value) {
//
if ($value != '') {$this->worksheets[$this->ActiveSheet]->has_header = true;}
//
$Type = SimpleExcelCellsTypes::Text;
$OriginalValue = $value;
$TextIndex = $this->AddStringToArray($value);
//
$Result = $this->db->exec("INSERT INTO storage (sheet, row, column, data_type, original_value, date_value, text_index) VALUES ({$this->ActiveSheet}, 1, $column_index, $Type, '".$this->db->escapeString($OriginalValue)."', 0, $TextIndex);");
if ($Result) {
} else {
}
//
$column_index++;
//
}
//
if (($column_index-1) > $this->MaxColumn) {$this->MaxColumn = ($column_index-1);}
//
}
//
public function SetDataByArray($Data, $MaxRow) {
//
checkDatabase(true);
//
$Type = SimpleExcelCellsTypes::None;
$OriginalValue = "";
$DateValue = 0;
$TextIndex = 0;
//
$this->db->exec("BEGIN TRANSACTION;");
$row_index = 2;
for ($i = 0; $i < $MaxRow; ++$i) {
$row = $Data[$i];
$column_index = 1;
foreach ($row as $column) {
$OriginalValue = $column;
if ($column == '') {
$Type = SimpleExcelCellsTypes::None;
} else {
$this->worksheets[$this->ActiveSheet]->has_data = true;
if (is_numeric($column)) {
$Type = SimpleExcelCellsTypes::Numeric;
} else {
$Result = $this->IsDate($column);
if ($Result) {
// Date
$Type = SimpleExcelCellsTypes::Date;
$DateValue = $Result;
} else {
// Assumed string
$Type = SimpleExcelCellsTypes::Text;
$TextIndex = $this->AddStringToArray($column);
}
}
}
$this->db->exec("INSERT INTO storage (sheet, row, column, data_type, original_value, date_value, text_index) VALUES ({$this->ActiveSheet}, $row_index, $column_index, $Type, '".$this->db->escapeString($OriginalValue)."', $DateValue, $TextIndex);");
$column_index++;
}
$row_index++;
if (count($row) > $this->MaxColumn) {$this->MaxColumn = count($row);}
}
$this->db->exec("COMMIT TRANSACTION;");
//
$this->worksheets[$this->ActiveSheet]->max_row = $row_index - 1;
// Store maximum row count.
}
//
public function setActiveSheet($Index) {
//
if ($Index < 0 || $Index > (count($this->worksheets) - 1)) {return false;}
//
$this->ActiveSheet = $Index;
//
return true;
//
}
//
public function addSheet($Named) {
$Sheet = new SimpleExcelSheets();
$Sheet->named = $Named;
$Sheet->has_header = false;
$Sheet->has_data = false;
$this->worksheets[] = $Sheet;
$this->ActiveSheet = count($this->worksheets)-1;
}
//
public function write($FullPath) {
//
$this->BuildFiles();
//
$zip = new ZipArchive;
$res = $zip->open($FullPath, ZipArchive::CREATE);
if ($res == TRUE) {
//
$zip->addFromString('[Content_Types].xml', $this->content_types);
//
$zip->addFromString('_rels/.rels', $this->rels);
//
$zip->addFromString('docProps/app.xml', $this->app);
$zip->addFromString('docProps/core.xml', $this->core);
//
$zip->addFromString('xl/_rels/workbook.xml.rels', $this->xl_rels);
//
$zip->addFromString('xl/theme/theme1.xml', $this->theme1);
//
$zip->addFromString('xl/workbook.xml', $this->workbook);
$zip->addFromString('xl/styles.xml', $this->styles);
$zip->addFromString('xl/sharedStrings.xml', $this->sharedStrings);
//
$zip->addEmptyDir('xl/printerSettings');
//
foreach ($this->worksheets as $key=>$value) {
$zip->addFile($value->fullfile, "xl/worksheets/sheet".(string)($key+1).".xml");
}
//
$zip->close();
//
foreach ($this->worksheets as $key=>$value) {
unlink($value->fullfile);
}
//
}
//
}
//
function __destruct() {
// Deconstruct - clean up.
if (!is_null($this->db)) {
$this->db->close();
}
}
}
// ************************************************************
// Begin Example
// ************************************************************
$excel = new SimpleExcel();
// Create the class.
$excel->Company = "Seijin Solutions LLC";
$excel->CreatedBy = "Sam Shults";
// Set a couple properties.
$excel->SetHeader(array('Header A','Header B','Header C','Header D'));
// Create the header in the spreadsheet.
$mysqli = new mysqli("localhost", "some_user", "hahaha_right", "some_db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$Data = array();
// Create the array to store the data.
$mysqli->real_query("SELECT header_a, header_b, header_c, header_d FROM fake_table;");
if ($res = $mysqli->use_result()) {
while ($row = mysqli_fetch_array($res, MYSQLI_NUM)) {
$Data[] = $row;
// Store the row in the array.
}
$res->free();
}
$mysqli->close();
;}
//
$excel->SetDataByArray($Data, count($Data) - 1);
// Store the array of data in the spreadsheet, passing the row count.
$excel->write('./test.xlsx');
// Write the Excel file.
?>

Create Random Password

<?php
/**
 * The letter l (lowercase L) and the number 1
 * have been removed, as they can be mistaken
 * for each other.
 * Tito code :eyeswideshut25@hotmail.com
 */
function createRandomPassword() {
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;
    while ($i <= 7) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}
// Usage
//$password = createRandomPassword();
//echo "Your random password is: $password";
?>

PHP SQL Injection

SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build an SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

Example #1 Splitting the result set into pages … and making superusers (PostgreSQL)

<?php$offset

$argv[0]; // beware, no input validation!
$query  "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result pg_query($conn$query);
 

?>

Normal users click on the ‘next’, ‘prev’ links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()‘d form of the following to the URL

0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

Note:

It is common technique to force the SQL parser to ignore the rest of the query written by the developer with which is the comment sign in SQL.

A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

Example #2 Listing out articles … and some passwords (any database server)

<?php$query

"SELECT id, name, inserted, size FROM products
WHERE size = '
$size'";
$result odbc_exec($conn$query);
 

?>

The static part of the query can be combined with another SELECT statement which reveals all passwords:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

If this query (playing with the and ) were assigned to one of the variables used in $query, the query beast awakened.

SQL UPDATE’s are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.

Example #3 From resetting a password … to gaining more privileges (any database server)

<?php
$query 
"UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>

But a malicious user sumbits the value ‘ or uid like’%admin% to $uid to change the admin’s password, or simply sets $pwd to hehehe’, trusted=100, admin=’yes to gain more privileges. Then, the query will be twisted:

<?php 

// $uid: ' or uid like '%admin%
$query "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";
 

// $pwd: hehehe', trusted=100, admin='yes
$query "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;"
;
 

?>

A frightening example how operating system level commands can be accessed on some database hosts.

Example #4 Attacking the database hosts operating system (MSSQL Server)

<?php$query

"SELECT * FROM products WHERE id LIKE '%$prod%'";
$result mssql_query($query);
 

?>

If attacker submits the value a%’ exec master..xp_cmdshell ‘net user test testpass /ADD’ — to $prod, then the $query will be:

<?php$query

"SELECT * FROM products
WHERE id LIKE '%a%'
exec master..xp_cmdshell 'net user test testpass /ADD' --%'"
;
$result mssql_query($query);
 

?>

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.

Note:

Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.

You want to send an attachment along with your mail message.

Technique

Use a boundary to separate the body of your message with the attachment:

<?php
$boundary = "b" . md5(uniqid(time()));
$mime =  "Content-type: multipart/mixed; ";
$mime .= "boundary = $boundaryrnrn";
$mime .= "This is a MIME encoded message.rnrn";
// First the regular message
$mime_message .= "--$boundaryrn";
$mime .= "Content-type: text/plainrn";
$mime .= "Content-Transfer-Encoding: base64";
$mime .= "rnrn" . chunk_split(base64_encode($message)) . "rn";
// Now the attachment
$filename = "data.txt";
$attach = chunk_split(base64_encode(implode("", file($filename))));
$mime .= "--$boundaryrn";
$mime .= "Content-type: text/plainrn";
$mime .= "Content-Transfer-Encoding: base64";
$mime .= "rnrn$attachment_datarn";

mail($to,
    $subject,
    "",
    $mime);
?>

Comments

When sending messages with more than one part, you need a boundary—a unique separator that separates the different parts of the message. Unfortunately, you cannot work with this boundary in the body of a message. Therefore, as in the preceding example, you must specify an empty body and then write out the entire message according to RFC 821.

The message is encoded using base 64 encoding. This isn’t really necessary for text files, but if you want to send binary files, it is vital. The chunk_split() breaks up the blobs into 76 character lines terminated by "rn" in accordance with the RFC 2045 guidelines.

You want to send an e-mail from your PHP script

 
Technique
Use PHP’s built-in mail() function:

<?php
/* submitted data is $email, $name,$subject, $message and $to */
mail($to,
$subject,
$message,
“From: $emailrnReply-to: $emailrn”);
?>

Comments
The mail() function takes three required arguments: the e-mail address to which you want to send the e-mail, the subject of the e-mail, and the body of the message. The fourth argument is optional, but it enables you to give any extra headers, which should be separated by the standard <CRLF> (“rn”).

The preceding script sends an e-mail based on the user’s input. A form that might trigger this script would be something like the following (assuming the script in the solution is named mailer.php):

<form action=”mailer.php” method=”POST”>
To: <input type=”text” name=”to”><br>
From: <input type=”text” name=”email”><br>
Subject: <input type=”text” name=”subject”><br>
Message Body: <br>
<textarea rows=”10″ cols=”40″ name=”message”></textarea><br>
<input type=”submit” value=”Send your message”>
</form>

 

example of connecting to a database and fetching a row by using the function-oriented API

<?php
include_once(“DB/mysql.php”);

$dbh = db_connect(array($host,$user,$pass));
if (!$dbh){
die(“Cannot connect to database”);
}
db_select_db(array(“sampleDB”));
$sth = db_query(“SELECT * FROM sampleTable”, $dbh);
if (!$sth) {
die(“Cannot execute query”);
}
while ($row = db_fetch_row(array($sth))) {
echo $row[“firstname”];
echo $row[“lastname”];
}
db_free_result(array($sth));
db_close(array($dbh));
?>