PHP email validation script - php

My first post here, although i have used this site many times to find fixes for code.
I've been using a script to validate emails on my old host which works fine, the new host however (123-reg) it doesnt validate them correctly at all.
This script actually verifies the existence of an email not just the format of it.
please see the following links
t43.co.uk/emailcheck.php?email=asdasdasd#hotmail.com (works fine)
smile-database.co.uk/emailcheck.php?email=asdasdasd#hotmail.com (always says valid when i know it isnt)
my script is below.
function checkEmail( $email, $chFail = false )
{
$msgs = Array();
$msgs[] = 'Received email address: '.$email;
if( !preg_match( "/^(([^<>()[\]\\\\.,;:\s#\"]+(\.[^<>()[\]\\\\.,;:\s#\"]+)*)|(\"([^\"\\\\\r]|(\\\\[\w\W]))*\"))#((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([a-z\-0-9áàäçéèêñóòôöüæøå]+\.)+[a-z]{2,}))$/i", $email ) )
{
$msgs[] = 'Email address was not recognised as a valid email pattern<br><br>';
return $chFail ? Array( false, $msgs ) : false;
}
$msgs[] = 'Email address was recognised as a valid email pattern';
//get the mx host name
if( preg_match( "/#\[[\d.]*\]$/", $email ) )
{
$mxHost[0] = preg_replace( "/[\w\W]*#\[([\d.]+)\]$/", "$1", $email );
$msgs[] = 'Email address contained IP address '.$mxHost[0].' - no need for MX lookup';
}
else
{
//get all mx servers - if no MX records, assume domain is MX (SMTP RFC)
$domain = preg_replace( "/^[\w\W]*#([^#]*)$/i", "$1", $email );
if( !getmxrr( $domain, $mxHost, $weightings ) )
{
$mxHost[0] = $domain;
$msgs[] = 'Failed to obtain MX records, defaulting to '.$domain.' as specified by SMTP protocol';
}
else
{
array_multisort( $weightings, $mxHost );
$cnt = ''; $co = 0; foreach( $mxHost as $ch ) { $cnt .= ( $cnt ? ', ' : '' ) . $ch . ' (' . $weightings[$co] . ')'; $co++; }
$msgs[] = 'Obtained the following MX records for '.$domain.': '.$cnt;
}
}
//check each server until you are given permission to connect, then check only that one server
foreach( $mxHost as $currentHost )
{
$msgs[] = 'Checking MX server: '.$currentHost;
if( $connection = #fsockopen( $currentHost, 25 ) )
{
$msgs[] = 'Created socket ('.$connection.') to '.$currentHost;
if( preg_match( "/^2\d\d/", $cn = fgets( $connection, 1024 ) ) )
{
$msgs[] = $currentHost.' sent SMTP connection header - no futher MX servers will be checked: '.$cn;
while( preg_match( "/^2\d\d-/", $cn ) )
{
$cn = fgets( $connection, 1024 );
$msgs[] = $currentHost.' sent extra connection header: '.$cn;
}
if( !$_SERVER )
{
global $HTTP_SERVER_VARS; $_SERVER = $HTTP_SERVER_VARS;
}
//attempt to send an email from the user to themselves (not <> as some misconfigured servers reject it)
echo $_SERVER['HTTP_HOST'] . "<BR>";
$localHostIP = gethostbyname(preg_replace("/^.*#|:.*$/",'',$_SERVER['HTTP_HOST']));
echo $localHostIP . "<BR>";
$localHostName = gethostbyaddr($localHostIP);
fputs( $connection, 'HELO '.($localHostName?$localHostName:('['.$localHostIP.']'))."\r\n" );
if( $success = preg_match( "/^2\d\d/", $hl = fgets( $connection, 1024 ) ) )
{
$msgs[] = $currentHost.' sent HELO response: '.$hl;
fputs( $connection, "MAIL FROM: <$email>\r\n" );
if( $success = preg_match( "/^2\d\d/", $from = fgets( $connection, 1024 ) ) )
{
$msgs[] = $currentHost.' sent MAIL FROM response: '.$from;
fputs( $connection, "RCPT TO: <$email>\r\n" );
if( $success = preg_match( "/^2\d\d/", $to = fgets( $connection, 1024 ) ) )
{
$msgs[] = $currentHost.' sent RCPT TO response: '.$to;
}
else
{
$msgs[] = $currentHost.' rejected recipient: '.$to;
}
}
else
{
$msgs[] = $currentHost.' rejected MAIL FROM: '.$from;
}
}
else
{
$msgs[] = $currentHost.' rejected HELO: '.$hl;
}
fputs( $connection, "QUIT\r\n");
fgets( $connection, 1024 ); fclose( $connection );
//see if the transaction was permitted (i.e. does that email address exist)
$msgs[] = $success ? ('Email address was accepted by '.$currentHost) : ('Email address was rejected by '.$currentHost);
return $chFail ? Array( $success, $msgs ) : $success;
}
elseif ( preg_match( "/^550/", $cn ) )
{
$msgs[] = 'Mail domain denies connections from this host - no futher MX servers will be checked: '.$cn;
return $chFail ? Array( false, $msgs ) : false;
}
else
{
$msgs[] = $currentHost.' did not send SMTP connection header: '.$cn;
}
}
else
{
$msgs[] = 'Failed to create socket to '.$currentHost;
}
}
$msgs[] = 'Could not establish SMTP session with any MX servers';
return $chFail ? Array( false, $msgs ) : false;
}
echo "<br><br>Email Validation Check<br><br>";
$return_msgs = checkEmail( $_REQUEST['email'], true );
if ( $return_msgs[0] == 0 )
{
echo "<img src='img/Fail.png'> May be invalid<br>".$_REQUEST['email'];
}
elseif ( $return_msgs[0] == 1 )
{
echo "<img src='img/OK.png'> Valid<br>".$_REQUEST['email'];
}
else
{
echo "<img src='img/Caution.png'> Caution<br>".$_REQUEST['email'];
}

I have read one great topic about email validation.
Author propose to use this regexp: /.+#.+\..+/i and give a great description (in Russian) to a lot of "why exactly this regexp"
'somestring' # 'somestring'.'somestring'

Related

form doesn't get sent with PHPMailer()

can someone help me a bit with PhpMailer form? I'm not a php dev and i'm a bit lost, mostly because I have no idea how to debug it.
Tips how to debug such scripts are very welcome! (I don't know how to do it in localhost and I host it in a web shared host so I cannot ssh the server)
This is the script:
I have a multiple step form from Frontend which has also recaptcha, so the script include validation of different form steps and recaptcha validation.
<?php
require_once("/PHPMailer/PHPMailer.php");
use PHPMailer\PHPMailer\PHPMailer;
$t_mailer = new PHPMailer;
$t_mailer->SMTPAuth = true;
$t_mailer->Username = "myemail#gmail.com"; // gmail username
$t_mailer->Password = "****"; //gmail password
$t_mailer->SMTPSecure = 'tls';
$t_mailer->Port = 587;
$t_mailer->setFrom("myemail#gmail.com", "Name for the owner of the Account");
//$t_mailer->addAddress("myemail#gmail.com", "Name for who is being sent the email.");
$t_mailer->Subject = "Project request from ECA";
$t_mailer->Body = "This will be the message body that is sent.";
// $recipient = 'myemail#gmail.com'; // Enter the recipient's email address here.
// $subject = 'Project request from ECA'; // Enter the subject of the email here.
$success = 'Your message was sent successful. Thanks.';
$error = 'Sorry. We were unable to send your message.';
$invalid = 'Validation errors occurred. Please confirm the fields and submit it again.';
if ( ! empty( $_POST ) ) {
require_once('recaptcha.php');
if( isset( $_POST['email'] ) ) {
$from = filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL );
} else {
$from = null;
}
if( isset( $_POST['step'] ) ) {
$step = $_POST['step'];
} else {
$step = 'send';
}
if ( ! empty( $_POST['reCAPTCHA'] ) ) {
if ( ! empty( $reCAPTCHA['success'] ) ) {
$errCaptcha = '';
} else {
$errCaptcha = true;
}
} else {
$errCaptcha = '';
}
$errFields = array();
foreach( $_POST as $key => $value ) {
if ( $key != 'section' && $key != 'reCAPTCHA' ) {
if ( $key == 'email' ) {
$validation = filter_var( $_POST[$key], FILTER_VALIDATE_EMAIL );
} else {
$validation = ! empty( $_POST[$key] );
}
if ( ! $validation ) {
$errFields[$key] = true;
}
}
}
if ( empty( $errCaptcha ) && count( $errFields ) === 0 && $step === 'send' ) {
$header = "From: " . $from . " <" . $from . ">" . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$body = '<table style="padding: 35px; background-color: #f5f5f5"; font-family: Roboto, sans-serif; font-size: 1rem; text-align: left; border-radius: 4px>';
$body .= '<tr><th style="font-size: 1.5rem; font-weight: 600; color: #1E50BC">'.$subject.'</th></tr>';
$body .= '<tr></td>';
foreach( $_POST as $key => $value ) {
if ( $key != 'section' && $key != 'reCAPTCHA' ) {
$body .= '<p><b>' . str_replace( '-', ' ', ucfirst( $key ) ) . '</b>: ' . $value . '</p>';
}
}
$body .= '</td></tr>';
$body .= '</table>';
$t_mailer->Body = $body;
$t_mailer->addAddress($from, 'who send the email');
// $mail = mail( $recipient, $subject, $body, $header );
// $mail
if ( $t_mailer->send() ) {
$response = array(
'status' => 'success',
'info' => $success
);
print_r( json_encode( $response ) );
} else {
$response = array(
'status' => 'fail',
'info' => $error
);
print_r( json_encode( $response ) );
}
} else {
$response = array(
'status' => 'invalid',
'info' => $invalid,
'captcha' => $errCaptcha,
'fields' => $errFields,
'errors' => count( $errFields )
);
print_r( json_encode( $response ) );
}
exit;
}
I'm sure PhpMailer works with my host and my server because I tried a very simple script that send an email from root and it worked. (I got the email in my gmail inbox)
But This script is in another folder, not root, even tho they all have same folder/files permission (not sure if is relevant, but better specify!)
Several things not quite right here.
When you're using PHPMailer without composer, you need to load all the classes it needs yourself, so add:
require_once '/PHPMailer/SMTP.php';
require_once '/PHPMailer/Exception.php';
You are setting some SMTP config properties, but not actually telling PHPMailer to use SMTP, so add this:
$t_mailer->isSMTP();
You're sending from a gmail address, which means you must send through gmail's servers (or you will fail SPF checks), but you have not specified a server to send through, so set this:
$t_mailer->Host = 'smtp.gmail.com';
Your content is in HTML, but you're not asking PHPMailer to send it as HTML:
$t_mailer->isHTML();
You don't need any of that stuff you're doing with $header; PHPMailer does all that for you.
Rather than going any further, I'd recommend basing your code on the gmail example provided with PHPMailer, and if you run into any other issues, refer to the PHPMailer troubleshooting guide and search on here.

CakePHP- Accessing mail using IMAP

Re-visiting this problem specified in my previous question, I tried and tried, also with different accounts (I tried gmail, as well as outlook), but the problem still persists. The error I get is the following if I try to access my google account
Error: Unable to get imap_thread after 4 retries. 'Can't open mailbox {imap.gmail.com:993/ssl/imap/tls/novalidate-cert}INBOX: invalid remote specification'
if I try accessing email on my outlook account, the error is the same :
Error: Unable to get imap_thread after 4 retries. 'Can't open mailbox {outlook.office365.com:993/ssl/imap/tls/novalidate-cert}INBOX: invalid remote specification'
My setup is as follows :
public $emailTicket = array(
'datasource' => 'ImapSource',
'server' => 'outlook.office365.com',
'connect' => 'imap/tls/novalidate-cert',
'username' => 'my email here',
'password' => 'my password here',
'port' => '993', //incoming port
'ssl' => true,
'encoding' => 'UTF-8',
'error_handler' => 'php',
'auto_mark_as' => array(
'Seen',
// 'Answered',
// 'Flagged',
// 'Deleted',
// 'Draft',
),
);
I am working on a local machine, does anyone know if this might be the problem or not? Has anyone ever tried this and worked for him/her? I am open to all input!
I can't seem to find what's wrong here, I've been at this for about 2days now, so if anyone can help, I appreciate it!
Also here's the link for the plugin i'm using, by Nicolas Ramy..
You can use the following implemented code to fulfill your requirements:
public function generate_email_response_pdf()
{
$this->layout = false;
$this->autoRender = false;
$username = EMP_SMTP_MAIL_FROM;
$password = EMP_SMTP_MAIL_PASSWORD;
$imap = imap_open('{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX', $username, $password);
$emails = imap_search($imap, 'ALL');
if(!empty($emails))
{
//put the newest emails on top
rsort($emails);
foreach($emails as $email_number)
{
$flag = 0;
$mail_data = array();
$file_name = array();
$output = array();
$savefilename = null;
$filename = null;
$overview = imap_fetch_overview($imap, $email_number, 0);
//initialize the subject index with -000, considering not receving this will not be received in
//subject line of email
$output['subject'] = '-000x';
if(isset($overview[0] -> subject))
{
$output['subject'] = $overview[0] -> subject;
}
$structure = imap_fetchstructure($imap, $email_number);
if(property_exists($structure, 'parts'))
{
$flag = 1;
$flattened_parts = $this->flatten_parts($structure->parts);
foreach($flattened_parts as $part_number => $part)
{
switch($part->type)
{
case 0:
//the HTML or plain text part of the email
if((isset($part->subtype)=='HTML')&&(isset($part->disposition)=='ATTACHMENT'))
{
$part_number = 1.2;
}
else if(isset($part->subtype)=='HTML')
{
$part_number = $part_number;
}
else
{
$part_number = $part_number;
}
$message = $this->get_part($imap, $email_number, $part_number, $part->encoding);
//now do something with the message, e.g. render it
break;
case 1:
// multi-part headers, can ignore
break;
case 2:
// attached message headers, can ignore
break;
case 3: // application
case 4: // audio
case 5: // image
case 6: // video
case 7: // other
break;
}
if(isset($part->disposition))
{
$filename = $this->get_filename_from_part($part);
if($filename)
{
// it's an attachment
$attachment = $this->get_part($imap, $email_number, $part_number, $part->encoding);
$file_info = pathinfo($filename);
$savefilename = RESPONSE_ATTACHMENT_PREFIX.$file_info['filename'].'_'.$this->_getRandId(4).'.'.$file_info['extension'];
$file_name[] = $savefilename;
$attachment_file_name = $this->save_attachment($attachment, $savefilename, $directory_path);
//imap_fetchbody($imap, $email_number, 2); //This marks message as read
}
else
{
// don't know what it is
}
}
}
}
else
{
$encoding = $structure->encoding;
$message = imap_fetchbody($imap, $email_number, 1.2);
//echo $message; die;
if($message == "")
{
$message = imap_body($imap, $email_number);
if($encoding == 3)
{
$message = base64_decode($message);
}
else if($encoding == 4)
{
$message = quoted_printable_decode($message);
}
}
}
$header = imap_headerinfo($imap, $email_number);
$from_email = $header->from[0]->mailbox."#".$header->from[0]->host;
$to_email = $header->to[0]->mailbox."#".$header->to[0]->host;
$reply_to_email = $header->reply_to[0]->mailbox."#".$header->reply_to[0]->host;
$cc_email = array();
if(isset($header->cc))
{
foreach($header->cc as $ccmail)
{
$cc_email[] = $ccmail->mailbox.'#'.$ccmail->host;
}
$cc_email = implode(", ", $cc_email);
}
$output['to'] = $to_email;
$output['from'] = $from_email;
$output['reply_to'] = $reply_to_email;
$output['cc'] = $cc_email;
$formatted_date = date('D, d M Y h:i A', strtotime($overview[0] -> date));
$output['date'] = $formatted_date;
$output['message'] = $message;
$output['flag'] = $flag;
$mail_data['Attachment'] = $file_name;
$mail_data['Data'] = $output;
$this->set('response_data', $mail_data);
$mail_content = null;
if(!empty($mail_data))
{
$this->viewPath = 'Elements/default';
$mail_content = $this->render('pdf_content');
}
$header = null;
$footer = null;
$html = preg_replace(array('/[^\r\n\t\x20-\x7E\xA0-\xFF]*/'), '', $mail_content);
$pdfFile = $this->_generateWkPdf($html, $directory_path, $new_file_name, $header, $footer);
$image_type = EXT_JPG;
$response_files_array = $this->_generateImagesFromPdf($directory_path.$pdfFile, $directory_path, $new_file_name, $image_type);
}
}
imap_close($imap);
}

Send email using gmail smtp in zend? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
email zend framwork smtp
I have following configuration:
smtp.type = Zend_Mail_Transport_Smtp
smtp.smtpServer = "smtp.gmail.com"
smtp.username = "ddd#gmail.com"
smtp.password = "dddd"
smtp.email = "ddd#gmail.com"
smtp.port = "587"
smtp.ssl = "tls"
smtp.auth = "login"
I am getting following error:
5.7.0 Must issue a STARTTLS command first. 74sm813723wem.41
My COde:
public function sendEmail( $mailData, $bootstrap = null ) {
// Get SMTP server configurations
if ( $bootstrap == null ) {
$front = Zend_Controller_Front::getInstance();
$bootstrap = $front->getParam('bootstrap');
}
$smtpSettings = $bootstrap->getOption('smtp');
print_r($smtpSettings);
// Only pass username password settings if the authentication is required.
if ( $smtpSettings['auth'] == 'login' ) {
$config = array('ssl' => $smtpSettings['ssl'],
'username' => $smtpSettings['username'],
'password' => $smtpSettings['password']);
$transport = new Zend_Mail_Transport_Smtp( $smtpSettings['smtpServer'], $config );
} else {
$transport = new Zend_Mail_Transport_Smtp( $smtpSettings['smtpServer'] );
}
$mail = new Zend_Mail( 'utf-8' );
try {
if ( $mailData['user'] == true ) {
$mail->setFrom( $mailData['from'], $mailData['fromName'] );
} else {
$mail->setFrom( $smtpSettings['email'], "eCHDP" );
}
// Do we have a single reciepent or multiple receipents?
if ( !is_array($mailData['to']) ) {
$mail->addTo( $mailData['to'] , $mailData['toName'] );
} else {
// We have multiple receipents. Add all of them.
foreach ( $mailData['to'] as $id => $value ) {
$mail->addTo( $value , $mailData['toName'][$id] );
}
}
$mail->setSubject( $mailData['subject'] );
$mail->setBodyHtml( $mailData['body'] );
// If attachment found then attach
if ( $mailData['attachment'] ) {
$attach = new Zend_Mime_Part( file_get_contents( $mailData['attachment'] ) );
$attach->type = 'application/pdf';
$attach->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$attach->filename = 'Invoice.pdf';
$mail->addAttachment( $attach );
}
$mail->send( $transport );
return true;
} catch ( Exception $e ) {
echo "Error sending Email : ";
$logger = Zend_Registry::get('Logger');
$logger->err($e->getMessage());
echo $e->getMessage() . "\n\n\n";
return false;
}
}
Can someone guess that what is the error ? I can post code as well if required.
Thanks
This is from our application.ini
resources.mail.transport.type = Zend_Mail_Transport_Smtp
resources.mail.transport.host = "smtp.gmail.com"
resources.mail.transport.port = 587
resources.mail.transport.auth = "login"
resources.mail.transport.username = "email#address.com"
resources.mail.transport.password = "password"
resources.mail.transport.ssl = "tls"
And it "Just works (tm)"!
You can try with: ssl = tls or port = 587

Hacking "Contact Form 7" code to Add A "Referred By" field

I've got about 6 subdomains that have a "contact us" link and I'm sending all these links to a single form that uses "Contact Form 7". I add ?from=site-name to each of the links so that I can set a $referredFrom variable in the contact form.
The only two things I'm missing are (1) the ability to insert this referredFrom variable into the email that I get whenever someone submits the form and (2) The ability to redirect the user back to the site they came from (stored in $referredFrom)
Any ideas?
Here's a bit of code from includes/classes.php that I thought might be part of the email insert but its not doing much...
function mail() {
global $referrer;
$refferedfrom = $referrer; //HERE IS MY CUSTOM CODE
$fes = $this->form_scan_shortcode();
foreach ( $fes as $fe ) {
$name = $fe['name'];
$pipes = $fe['pipes'];
if ( empty( $name ) )
continue;
$value = $_POST[$name];
if ( WPCF7_USE_PIPE && is_a( $pipes, 'WPCF7_Pipes' ) && ! $pipes->zero() ) {
if ( is_array( $value) ) {
$new_value = array();
foreach ( $value as $v ) {
$new_value[] = $pipes->do_pipe( $v );
}
$value = $new_value;
} else {
$value = $pipes->do_pipe( $value );
}
}
$this->posted_data[$name] = $value;
$this->posted_data[$refferedfrom] = $referrer; //HERE IS MY CUSTOM CODE
}
I'm also thinking that I could insert the referredFrom code somewhere in this function as well...
function compose_and_send_mail( $mail_template ) {
$regex = '/\[\s*([a-zA-Z][0-9a-zA-Z:._-]*)\s*\]/';
$callback = array( &$this, 'mail_callback' );
$mail_subject = preg_replace_callback( $regex, $callback, $mail_template['subject'] );
$mail_sender = preg_replace_callback( $regex, $callback, $mail_template['sender'] );
$mail_body = preg_replace_callback( $regex, $callback, $mail_template['body'] );
$mail_recipient = preg_replace_callback( $regex, $callback, $mail_template['recipient'] );
$mail_headers = "From: $mail_sender\n";
if ( $mail_template['use_html'] )
$mail_headers .= "Content-Type: text/html\n";
$mail_additional_headers = preg_replace_callback( $regex, $callback,
$mail_template['additional_headers'] );
$mail_headers .= trim( $mail_additional_headers ) . "\n";
if ( $this->uploaded_files ) {
$for_this_mail = array();
foreach ( $this->uploaded_files as $name => $path ) {
if ( false === strpos( $mail_template['attachments'], "[${name}]" ) )
continue;
$for_this_mail[] = $path;
}
return #wp_mail( $mail_recipient, $mail_subject, $mail_body, $mail_headers,
$for_this_mail );
} else {
return #wp_mail( $mail_recipient, $mail_subject, $mail_body, $mail_headers );
}
}
I'd found a plugin that works fantastic for doing this, plus a little more:
http://wordpress.org/plugins/contact-form-7-leads-tracking/
Which will add all the information to the end of your email when it is sent
First of all, in order to get the from variable you'll have to insert
$referrer = $_GET['from'];
somewhere in the top script, at least before the last line you inserted.
Additionally, in the second script you have to add the value to $mail_body somehow, but since I don't know how that value is made up I can't help much with that.
Is the code for this form available online somewhere?
Insert in your functions.php or create a simple plugin...
1.
function custom_wpcf7_special_mail_tag( $output, $name ) {
if ( 'from' == $name ) {
$referredFrom = ( isset($_GET["from"]) && !empty($_GET["from"]) ) ? $_GET["from"] : '';
$output = $referredFrom;
}
return $output;
}
add_filter( 'wpcf7_special_mail_tags', 'custom_wpcf7_special_mail_tag', 10, 2 );
Use the [from] tag in your email template.
2.
function add_custom_js_cf7() {
$referredFrom = ( isset($_GET["from"]) && !empty($_GET["from"]) ) ? $_GET["from"] : '';
if ( $referredFrom ) {
?>
<script type="text/javascript">
var from = "<?php echo $referredFrom; ?>";
</script>
<?php }
}
add_action( 'wpcf7_enqueue_scripts', 'add_custom_js_cf7' );
And add this line to the "additional settings" in your form settings:
on_sent_ok: "location = from;"
http://contactform7.com/blog/2010/03/27/redirecting-to-another-url-after-submissions/
You can also use global $referredFrom; if you declared it somewhere.

comparing PERL md5() and PHP md5()

All of my application is written in PHP, bar 1 script which happens to create a md5 hash which is used later via PHP scripts. Problem being they dont match up.
PERL:
#$linkTrue = 'http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php'
md5_hex($linkTrue);
And for testing purposes i did this in PHP:
echo md5("http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php");
both return different values. Does anyone know why this is?
EDIT:
WHOLE PHP SCRIPT
<?php
echo md5("http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php");
?>
WHOLE PERL SCRIPT (sorry its long)
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
require LWP::UserAgent;
sub trim($);
use DBI;
use Net::FTP;
use Digest::MD5 qw(md5 md5_hex md5_base64);
print "Content-type: text/html\n\n";
print "<html>\n<head>\n</head><body>\n";
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;
$ua->max_redirect(0);
#my %get = ();
#for (split /\&/, $ENV{'QUERY_STRING'}) { my ($key, $val) = split /=/; $val =~ s/\+/ /g; $val =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/ge; $get{$key} = $val; }
#my %post = ();
#for (split /\&/, <STDIN>) { my ($key, $val) = split /=/; $val =~ s/\+/ /g; $val =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/ge; $post{$key} = $val; }
my %get = ('findAllPages' => 'true' );
my %post = ('ki' => '############################' );
sub trim($){
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
sub extention {
my($data) = #_;
if( substr( trim($data), -1) eq "/" ){
my #extArray = ('.html', '.php', '.htm', '.asp', '.shtml', '.aspx');
foreach(#extArray){
my $ext = $_;
my $testResponse = $ua->get('http://' . trim($data . "index" . $ext));
my $testResponseCode = $testResponse->code;
if( $testResponseCode == 200 || $testResponseCode == 301 || $testResponseCode == 302 ){
return trim($data . "index" . $ext);
last;
}
}
}else{
return $data;
}
}
if( defined( $get{findAllPages} ) && defined( $post{ki} ) ){
my ($database, $hostname, $port, $password, $user );
$database = "##########";
$hostname = "############";
$password = "##########";
$user = "#########";
my $KI = $post{ki};
# connect to the database
my $dsn = "DBI:mysql:database=$database;host=$hostname;";
my $dbh = DBI->connect($dsn, $user, $password);
my $sth = $dbh->prepare("SELECT * FROM accounts WHERE KI = '$KI' ") or die "Could not select from table" . $DBI::errstr;
$sth->execute();
if( $sth->rows != 0 ) {
my $ref = $sth->fetchrow_hashref();
my $domain = $ref->{website};
my $DB_username = $ref->{db_name};
my $DB_password = $ref->{db_pass};
my $DB_ftpuser = $ref->{ftpuser};
my $DB_ftppass = $ref->{ftppass};
my $DB_ftpserver = $ref->{ftpserver};
$sth->finish();
$dbh->disconnect();
chomp(my $url = trim($domain));
# try and find full path
sub findFullPath {
my($link, $landingPage) = #_;
# strip ./ and / from beggining of string
$link =~ s/^(?:(?:\/)|(?:\.\/))//g;
# find out whether link is backtracing to previous folder
if( $link =~ m/^\.\.\// ) { # link desination is back tracing
if( $landingPage =~ m/(?:(?:\.html)|(?:\.php)|(?:\.htm)|(?:\.asp)|(?:\.shtml)|(?:\.aspx))$/g ) {
# find destination folder from landing page
my #folders = split( "/", $landingPage );
#find size of array
my $foldersSize = scalar #folders;
delete $folders[$foldersSize - 1];
$foldersSize = scalar #folders;
my #backFolders = ( $link =~ m/\.\.\//g ); # get rid of ../
my $amountOfBackFolders = scalar #backFolders; # find how many folders back
for( my $x=0; $x < $amountOfBackFolders; $x++ ) {
my $numberToDelete = ($foldersSize - 1) - $x;
delete $folders[$numberToDelete];
}
$landingPage = join( "/", #folders );
$link =~ s/\.\.\///g;
return $landingPage . "/" . $link . "\n";
} elsif( $landingPage =~ m/(?:\/)$/g ) {
my #folders = split( "/", $landingPage );
#find size of array
my $foldersSize = scalar #folders;
delete $folders[$foldersSize - 1];
$foldersSize = scalar #folders;
my #backFolders = ( $link =~ m/\.\.\//g ); # get rid of ../
my $amountOfBackFolders = scalar #backFolders; # find how many folders back
for( my $x=0; $x < $amountOfBackFolders; $x++ ) {
my $numberToDelete = ($foldersSize) - $x;
delete $folders[$numberToDelete];
}
$landingPage = join( "/", #folders );
$link =~ s/\.\.\///g;
return $landingPage . "/" . $link . "\n";
} else {
}
}else{
if( substr( $landingPage, -1) eq "/" ){
return $landingPage . $link;
}else{
my #splitLandingPage = split( "/", $landingPage );
my $amountSplit = scalar #splitLandingPage;
my $toDelete = $amountSplit - 1;
my $lastEntry = $splitLandingPage[$toDelete];
if( $lastEntry =~ m/(?:(?:com)|(?:co\.uk)|(?:net)|(?:org)|(?:cc)|(?:tv)|(?:info)|(?:org\.uk)|(?:me\.uk)|(?:biz)|(?:name)|(?:eu)|(?:uk\.com)|(?:eu\.com)|(?:gb\.com)|(?:gb\.net)|(?:uk\.net)|(?:me)|(?:mobi))$/g ) {
return join( "/", #splitLandingPage ) . "/" . $link . "\n";
}else{
delete $splitLandingPage[$toDelete];
return join( "/", #splitLandingPage ) . "/" . $link . "\n";
}
}
}
}
# get HTTP details
my $response = $ua->get('http://' . trim($url));
my $responseCode = $response->code;
my $responseLocation = $response->header( 'Location' );
# contintue only if status code is 200 or 301
if( $responseCode != 200 && $responseCode != 301 && $responseCode != 302 ){
print "<span class=\"red\"> error: http://" . trim($url) . "Domain name invalid, please use differnet domain name: http status - " . $responseCode . "</span><br />\n";
die;
}
# change url if domain status eq 301
if( $responseCode == 301 || $responseCode == 302 ){
if($response->header( 'Location' ) =~ m/^http:\/\/www\./g ) {
$url = substr( $response->header( 'Location' ), 11 );
}elsif($response->header( 'Location' ) =~ m/^http:\/\//g ) {
$url = substr( $response->header( 'Location' ), 7 );
}else{
$url = findFullPath($response->header( 'Location' ), $url);
}
}
my #pagesArray = ($url);
my #pagesScannedArray;
my #mainPagesArray;
my #pagesNotScanned;
my $z = 0;
#print "\nGethering all valid links from " . $domain . "...\n\n";
while ( #pagesArray && $z < 100 ) {
# get the next in queue for proccessing
my $page = trim(shift #pagesArray);
if( ! grep {$_ eq trim($page)} #pagesNotScanned ) {
# check page http status
$response = $ua->get("http://" . trim($page));
$responseCode = $response->code;
if( $responseCode == 200 || $responseCode == 301 || $responseCode == 302 ){
# change page url if 301 redirect
if( $responseCode == 301 || $responseCode == 302 ){
if($response->header( 'Location' ) =~ m/^http:\/\/www\./g ) {
$page = substr( $response->header( 'Location' ), 11 );
}elsif($response->header( 'Location' ) =~ m/^http:\/\//g ) {
$page = substr( $response->header( 'Location' ), 7 );
}else{
$page = findFullPath($response->header( 'Location' ), $url);
}
}
# connect to page and get contents
if( my $pageData = get "http://" . trim($page) ) {
# get all links on page
my #pageLinksArray = ( $pageData =~ m/href=["']([^"']*)["']/g );
# foreach link on the page
foreach( #pageLinksArray ) {
my $link = trim($_);
# remove url if located on same domain
$link =~ s/(?:http:\/\/)?(?:www\.)?$url//g;
# if link is format we are looking for
if( $link =~ m/(?:(?:\.html)|(?:\.php)|(?:\.htm)|(?:\.asp)|(?:\.shtml)|(?:\.aspx)|(?:\/))$/ ) {
# if link is outbound
if( $link =~ m/^http:\/\//g ) {
if( ! grep {$_ eq trim($link)} #pagesNotScanned ) {
if( ! grep {$_ eq trim($page)} #mainPagesArray ) {
push ( #pagesNotScanned, trim($link) );
}
}
}else{
# find full path for link
my $newUrl = &findFullPath(trim($link), trim($page));
# if link has not already been claimed to be a main page
if( ! grep {$_ eq trim($newUrl)} #mainPagesArray ) {
# if link is not already in queue
if( ! grep {$_ eq trim($newUrl)} #pagesArray ) {
push ( #pagesArray, trim($newUrl) );
}
}
}
}
}
if( ! grep {$_ eq trim($page)} #mainPagesArray ) {
push ( #mainPagesArray, trim($page) );
}
}
}else{
if( ! grep {$_ eq trim($page)} #pagesNotScanned ) {
if( ! grep {$_ eq trim($page)} #mainPagesArray ) {
push ( #pagesNotScanned, trim($page) );
}
}
}
}
$z++;
}
if( scalar #mainPagesArray != 0 ) {
my ($database, $hostname, $port, $password, $user );
$database = $DB_username;
$hostname = "###########";
$password = $DB_password;
$user = $DB_username;
# connect to the database
my $dsn = "DBI:mysql:database=$database;host=$hostname;";
my $dbh = DBI->connect($dsn, $user, $password) or die " error: Couldn't connect to database: " . DBI->errstr;
print "\nTesting links' extentions from " . $domain . "...\n\n";
my $root;
my $ftp = Net::FTP->new($DB_ftpserver, Debug => 0) or die "Cannot connect to some.host.name: $#";
$ftp->login($DB_ftpuser, $DB_ftppass) or die "Cannot login ", $ftp->message;
my #list = $ftp->dir;
if( scalar #list != 0 ) {
foreach( #list ){
if( $_ =~ m/((?:www)|(?:public_html)|(?:htdocs))$/g ){
$root = $1;
last;
}
}
}
if( $root eq "" ) {
print "error: could not identify root directory.<br />\n";
die;
}
foreach( #mainPagesArray ) {
my $webpage = &extention(trim($_));
if( trim($webpage) ne trim($domain) ){
my $webpageQuote = $dbh->quote("http://www." . $webpage);
my $sth = $dbh->prepare("SELECT * FROM page_names WHERE linkTrue = $webpageQuote ") or die "Could not select from table" . $DBI::errstr;
$sth->execute();
if( $sth->rows == 0 ) {
print "http://www." . $webpage . "<br />\n";
my $linkTrue = $dbh->quote("http://www." . $webpage);
my $string = ($webpage =~ s/^$domain//g);
my $linkFromRoot = $dbh->quote($root . $webpage);
my $page_name = $dbh->quote("");
my $table_name = $dbh->quote(md5_hex(trim($linkTrue)));
my $navigation = $dbh->quote("");
my $location = $dbh->quote("");
$dbh->do("INSERT INTO page_names (linkFromRoot, linkTrue, page_name, table_name, navigation, location) VALUES ( $linkFromRoot, $linkTrue, $page_name, $table_name, $navigation, $location )") or die " error: Couldn't connect to database: " . DBI->errstr;
}
}
}
}else{
print "<span class=\"red\"> error: No pages where found. This CMS is designed for pre-existing sites. Please contact support for more information.</span><br />\n";
}
}else{
print "<span class=\"red\"> error: input key incorrerct.</span><br />\n";
}
}else{
print "<span class=\"red\"> error: This area is forbidden please locate back to www.plugnplaycms.co.uk</span><br />\n";
}
print "</body>\n</html>";
I believe its on line 274. The code might be messy but its my first script with perl, only been at it a week.
thing i got it. $dbh->quote() adds single quotes around the value.
http://www.themobilemakeover.co.uk/index.php
HEX: 58030da397e8a071bc192e67744faeb3 VALUE: ['http://www.themobilemakeover.co.uk/index.php']
http://www.themobilemakeover.co.uk/about-us-the-mobile-makeover.php
HEX: 569c081a2974da39758a3cbf3c3407d2 VALUE: ['http://www.themobilemakeover.co.uk/about-us-the-mobile-makeover.php']
http://www.themobilemakeover.co.uk/beauty-products-used.php
HEX: ac94f84cf6b27bca0c23cd6b0e0f1fc9 VALUE: ['http://www.themobilemakeover.co.uk/beauty-products-used.php']
http://www.themobilemakeover.co.uk/beauty-treatments.php
HEX: e88d7e8e16ffc0a72b56a884d4c6c06b VALUE: ['http://www.themobilemakeover.co.uk/beauty-treatments.php']
http://www.themobilemakeover.co.uk/contact.php
HEX: 8924fa24bdde1c4e072f99826d957b77 VALUE: ['http://www.themobilemakeover.co.uk/contact.php']
http://www.themobilemakeover.co.uk/pamper-parties.php
HEX: 1f2fae70048359734a9d1b3ca29cce55 VALUE: ['http://www.themobilemakeover.co.uk/pamper-parties.php']
http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking.php
HEX: 9961f75109590c3924e4018768ecd44e VALUE: ['http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking.php']
http://www.themobilemakeover.co.uk/sitemap/index.php
HEX: fbca4996156b038f4635467ee13e1615 VALUE: ['http://www.themobilemakeover.co.uk/sitemap/index.php']
http://www.themobilemakeover.co.uk/accessibility/index.php
HEX: 6f03046cbe90c490e4993c5325a44aa7 VALUE: ['http://www.themobilemakeover.co.uk/accessibility/index.php']
http://www.themobilemakeover.co.uk/terms/index.php
HEX: 5304b5e9bd933fb920a4f8749c27094b VALUE: ['http://www.themobilemakeover.co.uk/terms/index.php']
http://www.themobilemakeover.co.uk/beauty-treatments2.php
HEX: 96225fa657ef60b4969d277d01d8b577 VALUE: ['http://www.themobilemakeover.co.uk/beauty-treatments2.php']
http://www.themobilemakeover.co.uk/beauty-treatments3.php
HEX: 327c1bc37354aad202c90efe0dfa756b VALUE: ['http://www.themobilemakeover.co.uk/beauty-treatments3.php']
http://www.themobilemakeover.co.uk/wedding-and-special-occasions.php
HEX: 54c074a1881a0c958c7c2b8ff88f63d6 VALUE: ['http://www.themobilemakeover.co.uk/wedding-and-special-occasions.php']
http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php
HEX: 486c944b10ef539aa7ba4bfe607861f2 VALUE: ['http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php']
When I try it, both programs return a4cbeef10b3c6d44ca30d96370619eef
I have the feeling you're not giving us the whole picture. Show us the code leading up to this. In particular, check for newlines. Have you used chomp in the perl script?
Try for yourself. Here is the complete php script I used:
<?php
echo md5("http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php");
?>
And here is a complete perl script I used:
#!/usr/bin/perl
use Digest::Perl::MD5 'md5_hex';
$linkTrue = 'http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php';
print md5_hex($linkTrue);
edit:
Which if the two scripts is not returning that value for md5? That's the one that has a bug. Log the value that you're passing to md5, (with '[' before and ']' after to detect extra whitespace). Does that value match what you expect?
edit 2:
It looks like you found it, right? It's the single quotes. This:
print md5_hex("'http://www.themobilemakeover.co.uk/mobile-makeover-appointment-booking-signup.php'");
Notice the extra quotes. The above line gives me: 486c944b10ef539aa7ba4bfe607861f2

Categories