Wednesday, May 19, 2010

Apache Permanent Redirect

VirtualHost *>

Redirect permanent /


Thursday, May 13, 2010

PHP Sockets Loop


$jsonPing = "{\"c\":\"ping\",\"d\":{}}\0";

while (1) {


if($i == 1000) {

$data = "";
$data .= @fread($socket, 4096);
$data = str_replace("\x1f", " ", $data);
$data = str_replace("part", " part", $data);
$data = str_replace("join", " join", $data);
$data = str_replace("said", " said: ", $data);
$data = trim($data);

$jsonData = json_decode($data,true);

if ($jsonData['from'] == "ayt") {

if( ($jsonData['u']) && ($jsonData['t']) && (strpos($data, "said")) ) {
echo $jsonData['u']." : ".str_replace($jsonData['u'], "", $jsonData['t'])."
ob_flush(); }



Monday, May 10, 2010

Check to see which server is which (XML output)

header("Content-type: text/xml");

$getBeta = `/usr/bin/dig A +short`;
$getBeta = trim($getBeta);

$amIBeta = trim($amIBeta);

if ($getBeta == $amIBeta) {
$IAmBeta = "true";
$IAmBeta = "false"; }


Quick header file to use include or require with in PHP:

$mysql_pass = "mysqlpassword";

@mysql_select_db($mysql_db) or die("Unable to connect to database...");

foreach ($_REQUEST as $key => $value) {
$_REQUEST[$key] = mysql_real_escape_string($value);

Thursday, May 6, 2010

XInetD config

Just a quickie so I don't have to go dig it up again...

insert a new file under /etc/xinetd.d/ (under Ubuntu, anyway):

# default: on
# description: xinetd service to emulate Flash Remoting banner
service dummy
disable = no
id = dummy
socket_type = stream
protocol = tcp
user = root
server = /usr/local/bin/dumbdumbdumbdumbdumb
wait = no
port = 843

contents of /usr/local/bin/dumbdumbdumbdumbdumb:

echo "Oh, fiddlesticks..."

exit 0

Make sure /usr/local/bin/dumbdumbdumbdumbdumb is +x

Tomcat setup to only listen on localhost (for use with Apache Mod_Proxy)

server.xml changes:

< Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"

address=""/ >

Note the "address" section....

httpd.conf for mod_auth_mysql

Auth_MySQL_Info MySQL.Server username password
Auth_MySQL_General_DB DB with auth info

Getting Mod_Proxy to bounce to Tomcat (FINALLY)

This particular problem has been plaguing me for months.  How to make HTTPD proxy to a Tomcat instance.  Finally got it figured out.  BONUS:  Also configured it to authenticate via MySQL before proxying the connection.  This is using a self-signed SSL cert.

< VirtualHost >

        SSLEngine On
        SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
        SSLCertificateFile      /etc/apache2/ssl/server.crt
        SSLCertificateKeyFile   /etc/apache2/ssl/server.key

ProxyRequests Off
ProxyPreserveHost On

< Proxy * >
        Order deny,allow
        Allow from all
< /Proxy >

        ProxyPass /
        ProxyPassReverse /

< Location >
AuthName                        "Level 4 Staff Tools Login"
AuthType                        Basic
AuthUserFile                    /dev/null
AuthBasicAuthoritative          Off

Auth_MySQL                      On
Auth_MySQL_Password_Table       users
Auth_Mysql_Group_Table          staffGroups

Auth_MySQL_Username_Field       userName
Auth_MySQL_Password_Field       password
Auth_MySQL_Group_Field          groups
Auth_MySQL_Empty_Passwords      Off
Auth_MySQL_Encryption_Types     Plaintext Crypt_DES MySQL

require                         group engineering art

#        Order allow,deny
#        Allow from all
< /Location >

        ErrorLog /var/log/apache2/error.log

Wednesday, May 5, 2010

Post Vars as an Array

$result_storeList=mysql_query('SELECT * FROM stores');

while($arrayStoreName=mysql_fetch_array($result_storeList)) {
echo "".$arrayStoreName['name']."(put html checkbox here with $arrayStoreName['ID']).(other HTML here)\n";

Submit that to:

$getStore = "SELECT * from stores";
$getStoreQuery = mysql_query($getStore);
while($getStoreArray = mysql_fetch_array($getStoreQuery)) {
        $totalStoreNum = $getStoreArray['ID'];

if(htmlspecialchars($_POST[$getStoreArray['ID']])) {

$storeChoice = $getStoreArray['ID'];

$sql_Query = "INSERT INTO storeItems (storeID,itemID) VALUES ('".$storeChoice."','".$recordID."')";

mysql_query($sql_Query); }


File Uploading

// Where the file is going to be placed
$target_path = "/tmp/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['itemUpload']['name']);

if(move_uploaded_file($_FILES['itemUpload']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['itemUpload']['name']).
    " has been uploaded
} else{
    echo "There was an error uploading the file, please try again!";

$localFile = "/tmp/".basename( $_FILES['itemUpload']['name']);

$remoteFile = "/var/www/push/".basename( $_FILES['itemUpload']['name']);

$scp_connection = ssh2_connect('remotehost',22);
ssh2_auth_password($scp_connection, 'username', 'password');

ssh2_scp_send($scp_connection, $localFile, $remoteFile , 0664);

Upload a file via HTTP, then SCP it to another server.  Been using the hell out of this so I can "sanitize" what files get uploaded to the production server (and force them to push it to Dev first).

Wednesday, April 28, 2010

PHP Authentication Vars

Just a quick one for me to remember:


Get current auth info.  Going to be using this in later code.


PHP's json_decode function works well, unless, of course, you get the JSON from a socket server and forget to trim it.  This kicked my butt for a while yesterday.

Another important one to remember is var_dump (which kept showing up as NULL with json_decode before I started trimming the input).

Monday, April 19, 2010

Something to do with a PHP Directory Listing (Make it an HTML Option on another server)

$fp = fopen('http://whereever/whoever.php','r');

$content = '';

while($line = fgets($fp,4096)) {

        $content = $line;
        echo "\n".$content."\n\n"; }

Quickie PHP Directory Listing

$path = ".";

$dir_handle = @opendir($path) or die("Cannot open directory");

while ($file = readdir($dir_handle)) {

if (($file == ".") || ($file == "..") || ($file == "dropdown.php") || ($file == ".svn") || ($file == "old")) {

echo $file."\n"; }


Thursday, April 8, 2010

Quickie PHP Socket connection

$config = array(

'server' => 'serverName',
'port' => 'portNo' );

$socket = fsockopen($config['server'], $config['port'], $errno, $errstr);

if(!$socket) {

        die("Error on page: ".$errno." ".$errstr); }
//uncomment below if stream blocking is needed.
//stream_set_blocking($socket, 1);
$data .= fread($socket, 4096);

echo $data."\n";


Tuesday, April 6, 2010

Apache MySQL Auth

.htaccess File:

AuthName            "Title of Auth Popup"
AuthType            Basic
AuthUserFile            /dev/null
AuthBasicAuthoritative        Off

Auth_MySQL            On
Auth_MySQL_Password_Table    userTable
Auth_Mysql_Group_Table        userGroups

Auth_MySQL_Username_Field    userName
Auth_MySQL_Password_Field    password
Auth_MySQL_Group_Field        groups
Auth_MySQL_Empty_Passwords    Off
Auth_MySQL_Encryption_Types    Plaintext Crypt_DES MySQL

require                group groupName(s)

Just a MySQL statement I need to remember

select count(distinct userName) from userTracking where timeStamp >= '2010-03-30' AND status LIKE '%Logged into $%';

counts unique userNames from userTracking between March 30th 2010 and now and looks for "Logged into $" in the status field.

and even better:

SELECT COUNT(DISTINCT userName) FROM userTracking WHERE timeStamp >= DATE(NOW()) - INTERVAL 11 DAY + INTERVAL 10 HOUR AND timeStamp <= DATE(NOW()) - INTERVAL 0 DAY + INTERVAL 10 HOUR AND status LIKE '%Logged into $%';

between 11 days ago at 10am and today at 10am.

Delete MySQL Records Older Than *BLAH*




Thanks to:

Monday, April 5, 2010

My Reason to Despise Java

I understand it's a great language. Portable, (supposedly) easy to write. Also takes up a TON of file handlers on Linux. Quick fix below:

ADD: session required

ADD: fs.file-max = 1137875
then RUN: sysctl -p

* soft nofile 131070
* hard nofile 131070
* soft nproc 25000
* hard nproc 65000

(This is for Ubuntu, and MY settings....yours may be different).

Friday, April 2, 2010

PHP Code for XML

At my current job I'm writing a lot of PHP scripts to take the load off of our programmers and pass that load to our art dept. Much of the data gets passed as static XML files, which I'm converting to dynamic XML from MySQL via PHP, using the following code:


//The big one to make PHP spit it out as XML

header("Content-type: text/xml");



$sql_query="SELECT * FROM configTable";


Not the cleanest code, I know, but it works.


This blog is essentially a dumping ground for programming and thought snippets that I consider useful or entertaining. I want a central area that I can come to when I run into a problem I've solved before, but can't remember how I did it (easily done with 15+ years in tech). If you're reading these, I hope they help you as well.