Using the PHP Mail Function with Additional Headers

February 7th, 2010

Pass a fourth parameter to the mail() function with the header information.

&ght;?php
$to = "jane@example.com";
$subject = "Hello World!";
$body = "This will be sent from email-addr@example.com";
$headers = "From: email-addr@example.com\r\nX-Mailer: php";
mail($to, $subject, $body, $headers);

Dump MySQL Database without Drop Table Syntax

February 5th, 2010

Output .sql file for MySQL but without the drop table syntax before table name use the –skip-add-drop-table flag

mysqldump -u root -p database_name --skip-add-drop-table --skip-lock-tables > database_name.sql

Generate MySQL Datetime Type Using PHP Date() Function

February 5th, 2010

If you want to insert a datetime that matches the default mysql datetime type format use this

date('Y-m-d H:i:s');

PHP Paypal IPN Script

January 29th, 2010

Simple script for posting a valid response back to Paypal service after a sale is completed using the Paypal Instant Checkout payment method.

<?php
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {
  $value = urlencode(stripslashes($value));
  $req .= "&$key=$value";
}

// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

// assign posted variables to local variables
$item_name        = $_POST['item_name'];
$item_number      = $_POST['item_number'];
$payment_status   = $_POST['payment_status'];
$payment_amount   = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id           = $_POST['txn_id'];
$receiver_email   = $_POST['receiver_email'];
$payer_email      = $_POST['payer_email'];

if (!$fp) {
// HTTP ERROR
} else {
  fputs ($fp, $header . $req);
  while (!feof($fp)) {
    $res = fgets ($fp, 1024);
    if (strcmp ($res, "VERIFIED") == 0) {
      // check the payment_status is Completed
      // check that txn_id has not been previously processed
      // check that receiver_email is your Primary PayPal email
      // check that payment_amount/payment_currency are correct
      // process payment
    } else if (strcmp ($res, "INVALID") == 0) {
      // log for manual investigation
    }
  }
fclose ($fp);
}

I grabbed this script from Paypal Docs… I never can find the info I need w/in their site so I’m posting here for reference. https://www.paypal.com/us/cgi-bin/webscr?cmd=p/pdn/ipn-codesamples-pop-outside#php

Listing Files and Directories with PHP

January 27th, 2010

Listing all files and directories using PHP 5.

<?php
$files = array(); $dir = dir(".");
while(false!==($file=$dir->read())):
  if(($file{0}!=".") && ($file{0}!="~") && (substr($file, -3)!="LCK")
    && ($file!=basename($_SERVER["PHP_SELF"]))):
      $files[$file] = stat($file); //
    endif;
endwhile;
$dir->close(); ksort($files); ?>

<table border=1 cellpadding=5>
<tr><th>Name</th><th>Size</th><th>Date</th></tr>
<?php foreach($files as $name => $stats): ?>
  <tr>
    <td><?php print $name;?></td>
    <td><?php print $stats['size']; ?></td>
    <td><?php print date("m-d-Y h:ia", $stats['mtime']); ?></td>
  </tr>
<?php endforeach; ?></table>

Highlight String in PHP

January 23rd, 2010

Function for highlighting text/strings in PHP.

$content = file_get_contents("http://php.net/");

print highlight("PHP", $content);

function highlight($match, $string){
  return str_ireplace($match, "<span style='background:yellow'>$match</span>", $string);
}

Will output something like this

Highlighted PHP.Net

Highlighted PHP.Net

***Notice all the styles are gone :( … would need to parse the document body to maintain stylesheet and other ‘php’ strings that might be in resources paths.

Absolutize Relative Links Using PHP and Preg_Replace_Callback

January 13th, 2010

I was in the market for a simple php script to replace hrefs with their absolute paths from scraped web pages. I wrote one myself. I used the preg_replace_callback function so that I could pass the parsed results as a single variable.

<?php
$domain = "http://seanbehan.com";
$pattern = "/\bhref=[\"|'](.*?)[\"|']/";
$string = file_get_contents($domain);

// prepends relative links w/ $domain skips returns the match if already absolute
function replace_href($match){
  global $domain;
  if(substr($match[1], 0, 7)!=="http://" && substr($match[1],0,8)!=="https://"){
    return "href='".$domain.$match[1]."'";
  } else {
    return "href='".$match[1]."'s";
  }
}
print preg_replace_callback($pattern, "replace_href", $string);

Hello Rack

December 15th, 2009

What is Rack?

Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.

- Rack API Docs


Create and name your file config.ru If rack isn’t installed get it with this command

gem install rack

In your config.ru file

require 'rubygems'
require 'rack'

class HelloRack
  def call(env)
    [200, {"Content-Type" => "text/html"}, "Hello Rack!"]
  end
end

Rack::Handler::Mongrel.run HelloRack.new, :P ort => 8888

Check out http://m.onkey.org/2008/11/17/ruby-on-rack-1

The survey for people who make websites

December 15th, 2009

I took the survey!


Click here to take it →

Placing an Authenticity Token in a Rails Form

December 14th, 2009
 <%= hidden_field_tag :authenticity_token, form_authenticity_token %>