Actualizar estado de facebook desde PHP y CURL
<?PHP
/*******************************
*	Facebook Status Updater
*	Christian Flickinger
*	http://nexdot.net/blog
*	April 20, 2007
*******************************/
 
$status = 'YOUR_STATUS';
$first_name = 'YOUR_FIRST_NAME';
$login_email = 'YOUR_LOGIN_EMAIL';
$login_pass = 'YOUR_PASSWORD';
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&amp;next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_exec($ch);
 
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
$page = curl_exec($ch);
 
curl_setopt($ch, CURLOPT_POST, 1);
preg_match('/name="post_form_id" value="(.*)" \/>'.ucfirst($first_name).'/', $page, $form_id);
curl_setopt($ch, CURLOPT_POSTFIELDS,'post_form_id='.$form_id[1].'&status='.urlencode($status).'&update=Update');
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
curl_exec($ch);
?>
Tags: , , ,
Código PHP para enviar comentarios automáticamente en Wordpress

Un código Script Kiddie para spamear blogs en Wordpress automáticamente. Sin embargo solo es el preámbulo ya que poner un while(1) y tratar de saltarse akismet si que es todo un reto.

<?php 
$postfields = array(); 
$postfields["action"] = "submit"; 
$postfields["author"] = "Spammer"; 
$postfields["email"] = "spammer@spam.com"; 
$postfields["url"] = "http://www.iamaspammer.com/"; 
$postfields["comment"] = "I am a stupid spammer."; 
$postfields["comment_post_ID"] = "123"; 
$postfields["_wp_unfiltered_html_comment"] = "0d870b294b"; 
//Url of the form submission 
$url = "http://www.ablogthatdoesntexist.com/blog/suggerer_site.php?action=meta_pass&id_cat=0"; 
$useragent = "Mozilla/5.0"; 
$referer = $url;  
 
//Initialize CURL session 
$ch = curl_init($url); 
//CURL options 
curl_setopt($ch, CURLOPT_POST, 1); 
//We post $postfields data 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); 
//We define an useragent (Mozilla/5.0) 
curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
//We define a refferer ($url) 
curl_setopt($ch, CURLOPT_REFERER, $referer); 
//We get the result page in a string 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
//We exits CURL 
$result = curl_exec($ch); 
curl_close($ch); 
 
//Finally, we display the result 
echo $result; 
?>
Tags: , ,
Solución al error de Wordpress en paginación de categorias y autor

Existe un error de Wordpress donde la paginación no funciona en permalinks que lleven la siguiente estructura.

tublog.com/%category%/%postname%/
tublog.com/%author%/%postname%/
Cuando vas a la cualquier página que no sea la primera recibes error 404. Afortunadamente puedes solucionar el error puedes pegar el siguiente código en el archivo functions.php de tu theme.
 
function remove_page_from_query_string($query_string)
{
    if ($query_string['name'] == 'page' && isset($query_string['page'])) {
        unset($query_string['name']);
        // 'page' in the query_string looks like '/2', so split it out
        list($delim, $page_index) = split('/', $query_string['page']);
        $query_string['paged'] = $page_index;
    }
    return $query_string;
}
 
add_filter('request', 'remove_page_from_query_string');
Tags: , ,
Catalogo y Ejemplos de expresiones regulares

Una de las cosas mas  difíciles o que tienen una curvatura de aprendizaje diferente  son las expresiones regulares.  Pero una vez que encuentras el truco ya no es tan difícil.

Les dejo los mejores manuales de expresiones regulares y los ejemplos mas esenciales o importantes.

Expresiones regulares que siempre se ocupan:

Expresión regular para números de telefonos

$string = "(232) 555-5555";
if (preg_match('/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/', $string)) {
echo "This is a valid phone number.";
}

Una de las cosas mas difíciles o que tienen una curvatura de aprendizaje diferente son las expresiones regulares. Pero una vez que encuentras el truco ya no es tan difícil.

Les dejo los mejores manuales de expresiones regulares y los ejemplos mas esenciales o importantes.

Expresiones regulares que siempre se ocupan:

Expresión regular para números de teléfonos

$string = "(232) 555-5555";
if (preg_match('/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/', $string)) {
echo "Esto es un teléfono válido";
}

Expresión regular para códigos postales

	$string = "55324-4324";
if (preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/', $string)) {
echo "Cópdigo Postal válido";
}

Expresión regular para Username

function validate_username( $username ) {
  if(preg_match('/^[a-zA-Z0-9_]{3,16}$/', $_GET['username'])) {
    return true;
  }
  return false;
}

Expresión regular para XHTML/XML tag

function get_tag( $tag, $xml ) {
  $tag = preg_quote($tag);
  preg_match_all('{&lt;'.$tag.'[^&gt;]*&gt;(.*?).'}',
                   $xml,
                   $matches,
                   PREG_PATTERN_ORDER);
 
  return $matches[1];
}

Expresión regular para URL o dirección

$szString = "http://www.talkPHP.com";
if (preg_match('/^(http|https|ftp):\/\/([\w]*)\.([\w]*)\.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)(\.[a-z]{1,3})?\z/i', $szString))
    echo "Es una dirección URL válida";

Expresión regular para Email

$string = "first.last@domain.co.uk";
if (preg_match(
'/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/',
$string)) {
echo "Este es un email válido."

Expresión regular para Número de Tarjeta de Crédito

 	function luhn (cc) {
   var sum = 0;
   var i;
 
   for (i = cc.length - 2; i &gt;= 0; i -= 2) {
      sum += Array (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) [parseInt (cc.charAt (i), 10)];
   }
   for (i = cc.length - 1; i &gt;= 0; i -= 2) {
      sum += parseInt (cc.charAt (i), 10);
   }
   return (sum % 10) == 0;
}

Fuente:smashingmagazine.com

Tags: , ,
Ejecutar PHP en Google App Engine

Google App Engine te permite ocupar el procesamiento de los Servers de google para tus aplicaciones. Pero solo esta limitado a pocos lenguajes como Java sin embargo puedes usar Quercus, una implementación Java de PHP.

En el siguiente post puedes encontrar la explicación: Run PHP on the Google App Engine

Via: sentidoweb.com

Tags: , ,
Clase PHP para importar contactos MSN, GMAIL, WINDOWS LIVE..

Muchas redes sociales hoy permiten invitar a tus amigos mediante el acceso a tu cuenta para enviarles invitaciones a todos tus contactos.

Lamentablemente también existen muchos otros sitios que solo se dedican a dar un supuesto servicio como “QUIEN TE BLOQUEO DEL MSN”, para obtener un beneficio propio. También es culpa de la idiota de la gente, no entiendo para que quieres saber quien te bloqueo.

include('openinviter.php');
$inviter = new OpenInviter();
$inviter->startPlugin('gmail');
$inviter->login("username", "password");

$contacts = $inviter->getMyContacts();
foreach ($contacts as $email => $name) {
    echo $name . "  - " . $email . "";
}
$inviter->stopPlugin(true);
$inviter->logout();

El uso es muy sencillo. No pidas más.

Openinviter

Tags: , , ,
Clase PHP para pagos de Paypal

Si necesitas crear aplicaciones con pagos mediante Paypal y no te quieres romper la cabeza viendo su documentación o creando botones o herramientas que son muy tardadas. Ve la siguiente clase muy fácil de utilizar.

 
// Include the paypal library
include_once ('Paypal.php');
 
// Create an instance of the paypal library
$myPaypal = new Paypal();
 
// Specify your paypal email
$myPaypal->addField('business', 'YOUR_PAYPAL_EMAIL');
 
// Specify the currency
$myPaypal->addField('currency_code', 'USD');
 
// Specify the url where paypal will send the user on success/failure
$myPaypal->addField('return', 'http://YOUR_HOST/payment/paypal_success.php');
$myPaypal->addField('cancel_return', 'http://YOUR_HOST/payment/paypal_failure.php');
 
// Specify the url where paypal will send the IPN
$myPaypal->addField('notify_url', 'http://YOUR_HOST/payment/paypal_ipn.php');
 
// Specify the product information
$myPaypal->addField('item_name', 'T-Shirt');
$myPaypal->addField('amount', '9.99');
$myPaypal->addField('item_number', '001');
 
// Specify any custom value
$myPaypal->addField('custom', 'muri-khao');
 
// Enable test mode if needed
$myPaypal->enableTestMode();
 
// Let's start the train!
$myPaypal->submitPayment();

Libreria PHP PAYMENT LIBRARY | Via sentidoweb.com

Tags: , , ,
Errores de PHP

Y tu estas cometiendo estos errores de PHP?

Tags: ,
Full Height con JQUERY

Tuve un problema, en una aplicación que estoy desarrollando, donde necesitaba que una capa tuviera la altura restante de la pantalla. Jquery me hizo la vida fácil, dado que mi aplicación es enteramente JS, puedo darme el lujo de usar este truco.

var top_header=200px;
$(window).resize(function() {
		$("#content").css('height', $(window).height()-top_header);
		});

Este codígo redimensiona la altura de un div con la altura de la pantalla restándole unos px, que podrían ser un header o alguna otra cosa.

Aunque creo que en algunos navegadores no se invoca el evento de resize una vez que se carga la página. Por lo que lo ideal seria ponerlo en el .ready().

Para quien le sirva.

Tags: ,
PHP: Includes como funciones

Podemos usar un archivo.

return array( 
  'hostname' => 'localhost', 
  'database' => 'test', 
  'username' => 'test', 
  'password' => 'test', 
);

Y al incluirlo a otro podemos hacer que regrese el valor.

$config = include 'config.php';

Yo tampoco sabía –> Devolver Includes como funciones

Tags: ,
Petición POST en PHP

A raíz de un post anterior sobre http testing, alguien me pregunto como hacer una petición POST en php.

Existen dos formas, una es usando CURL.


$ch = curl_init('http://dominio.com/pagina.php');
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "parametro1=valor1&parametro2=valor2");
curl_exec ($ch);
curl_close ($ch);
?>

Y la más bonita es con sockets.

Tags: ,