digital-ether 399 Nearly a Posting Virtuoso Team Colleague

That is true with any hashing function and that is what makes crc32 so good. It stores a large amount of data in minimum space with minimum recourses still with the concept. If however you are after uniqueness then all of the hash functions are no good and the following code will need to be used.
....
So truly a custom hash function is the ONLY way to prevent collisions and to have better security.

CRC32b is not designed to be a secure hash: http://en.wikipedia.org/wiki/Cyclic_redundancy_check

There is nothing wrong with SHA256, Whirlpool etc. are designed to be secure thus they should be used to hash passwords.

It would be very hard to develop a secure hashing algorithm. You'd have to be contributing a lot to security in order to develop a hashing algorithm that is better then the current ones.

As far as collisions go, it is impossible not to have but in practice they do not occur for a sufficiently large hash like those generated with whirlpool.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Sorry for resurrecting an old thread. But it was referenced recently and I thought I'd add to it.

crc32b should not be used with passwords as it is an insecure hash function.
http://en.wikipedia.org/wiki/Cyclic_redundancy_check

It also generates hashes that are only 8 hexadecimal (base 16) digits long. Thus you have less then 16^8 possible hashes. (or less then 10 digits decimal)

A simple brute force such as:

$hash = hash('crc32b', hash('whirlpool', 'some password ^#d@C~'));
while($hash != hash('crc32b', $n)) { $n++; }
echo $n;

will produce a collision for any crc32b hash within an hour on an average PC. Using crc32b basically makes the original hashing function (whirlpool in this example) useless.

Whirlpool produces a 128 digit hexadecimal. Thus you should keep the whole hash in order to preserve its effectiveness against attacks. Rehashing a whirlpool hash with another hash that produces a shorter hash probably isn't a good idea. If you're doing it to save space, there are better alternatives.
http://www.bucabay.com/php/base-conversion-in-php-radix-255/

You should also always salt passwords before hashing to make rainbow tables (and other precomputation attacks) unfeasible.
http://en.wikipedia.org/wiki/Rainbow_table

A rainbow table, is just a list of possible passwords, and their corresponding hashes. So it can be thought of as a simple database table with one column for the password, and the other for its hash. However, generating all the possible passwords for longer passwords, and more characters, requires a lot of space. So rainbow tables use a time-space …

Atli commented: Excellent post. Using crc32b seemd a bit odd. Now we know :) +3
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

okay, that was odd. I've been using Safari to test it thus far. And I just went to test it the first time today and it seems to be running fine in Safari now; however, just for kicks I tested it in Firefox, and the problem was still there.

So I would say it's not browser specific.

As far as refreshing goes, after being redirected to the home page 99% of the time it's going to show you still offline, even though you just logged in, one (1) refresh and it will show you online. After that, it can vary. Typically, every three to five refreshes your logged in status will change.

It may be that you're seeing cached pages? Try doing a full refresh, I believe its Ctr+Shift+R with Firefox. See if you get the same problem.
Using Wireshark, or creating the HTTP requests manually would probably be best.

To do the HTTP request manually, you could use curl. You can get the windows version (or with cygwin) from http://curl.haxx.se/download.html

Then either write a shell script or do the commands manually:

Login:

curl -b cookies.txt -c cookies.txt -d "username=user&password=pass" -i www.example.com/login.php

That would do a POST to www.example.com/login.php passing username=user&password=password as parameters.
Cookies will be saved to cookies.txt

Then you can try requesting a page over and over and examining the returned HTML:

curl -b cookies.txt -c cookies.txt -i www.example.com/index.php

That will request www.example.com/index.php, sending it the …

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

What browser are you testing in? Try another browser to make sure it isn't specific to that browser.

How often does it happen? Every 10 refreshes? 100?

If you have firefox, and firebug, try looking at each HTTP request, and see if there is a difference between the http request/response when the user is logged in, and appears logged out.

Firebug: http://getfirebug.com/

You can also use wireshark: http://sourceforge.net/projects/wireshark/

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You can get the file modification time in PHP:

http://www.php.net/filemtime

$mtime = filemtime('/path/to/file');

To get the files in the directory, you can use glob()
http://us.php.net/manual/en/function.glob.php

Or with PHP5, use RecursiveDirectoryIterator class.

eg:

$dir_iterator = new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
// could use CHILD_FIRST if you so wish

foreach ($iterator as $file) {
    echo $file->getMTime()."\n";
}

see: http://us.php.net/manual/en/function.glob.php#92710

When you use the RecursiveDirectoryIterator class, each file becomes an instance of: SplFileInfo class.

So you can access the file using the methods defined for SplFileInfo.
http://us3.php.net/manual/en/class.splfileinfo.php

It's all in the date command.

Just execute this from shell:

$ date +%Y-%m-%d

Or in your bash script:
FormattedDate=$(date +%Y-%m-%d)
echo $FormattedDate

of course.. the way to your holy grail is

$ man date

The date command also accepts a file path using the -r option, taking its last modification time as the input date.

eg:

FilePath=/path/to/file
FormattedDate=$(date -r $FilePath +%Y-%m-%d)
echo $FormattedDate

You could also parse the date out of the ls -l with sed, awk, grep etc. and pass that to: date -d

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Something that might interest you is that before you could do XMLHttpRequest, the basis of AJAX, you could create Iframes programmatically with client side scripting.

Back then it was called iframe remoting, and it worked well and achieved all that you can do now with current AJAX and more, such as sending files. It was also cross domain and had detailed load progress indication. So in a way, current AJAX was a step backwards functionality wise. (It is just easier to make it work cross browser)

The new specifications from W3C, WebSockets, will really go beyond any of this however, especially since it allows low level TCP instead of just HTTP.
http://dev.w3.org/html5/websockets/

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Made a small test and it's working beautifully, thanks again :)

One rookie question: why is it necessary to use an iframe to do this upload? Couldn't it be done in a simple div? Well I know it can't, I tried, but why?

Or where could I find information that would clarify this point to me?

The Form has to be submitted by the browser, instead of programmatically via JavaScript, in order to send the file contents.

The Iframe does not belong to the same document. So the browser can submit the form within the Iframe without reloading the parent document. It only reloads the Iframe.

If it were a DIV, the browser would reload the parent.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Did you already ask your hosting support about the issue. It looks like they have not set up the PHP configuration (PHP.ini file) properly.

The setup they have, has them send email through an SMTP server. From the error, it looks like the SMTP is hosted on Yahoo. However, that SMTP is not accepting connections.

An SMTP server (Simple Mail Transfer Protocol), is just like a web server. But instead of receiving and sending HTML pages, it receives and sends email.

The SMTP server (also called the Mail Transfer Agent, MTA) is responsible for receiving emails, as well as sending emails.

So in this case, PHP is set up to send emails through the SMTP server. However, that particular SMTP server address is not working.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi frnds....


First of all sry for all 4 arraising same(email) thread more times...
I have a problem with email sendhing...

one my old client ...his project is shifted from one server to another server(control panel)...now, the contact page(email) is not working properly...here i m getting the below error....plz tell me wat i have to do....


error:

Failed to connect to mail.aaaaaaaa.com:25 [SMTP: Failed to connect socket: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (code: -1, response: )]

where can i write smtp settings for this attachment mail code...

How are you sending mail? Please post the relevant PHP code.

You're SMTP host is not accepting any connections.
ie: mail.aaaaaaaa.com

When you switched providers, you should also have a new SMTP server address. To get the address, you can open up the shell (command line).

On windows: nslookup -type=mx example.com On linux: dig example.com mx

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

OK. Now i can see them all as ubuntu with this one.

ubuntu@ubuntu:~$ sudo chmod 777 /var/www/toy

Before i mark this as solved i just want to make sure that this command doesn't expose security issues!!!
What do you think digital?

Sorry i am new in linux but geting there slowly.

If you're on a shared system it is not a good idea to have world writable directories or files.

Best is to use the least privileges that does the job.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I just tried varbinary like before and again varbinary didn't work however I tried blob which I have never heard of before and it worked! Also the bz library works but won't decompress. So using the method you have described how can I decompress the result?

Which bz library? Do you mean zlib? Is this in mysql or PHP?

You can just decompress the result in the SQL query:

SELECT uncompress(test) as test FROM `table` WHERE `compressed` = compress('test')

This should give you the column test in decompressed form.

Note:

I wouldn't use:

SELECT * FROM `table` WHERE UNCOMPRESS(`column`)="abcd"

The reason is that you'll run uncompress() on each row in the database table.
You will also be unable to use any index made on that column.

If you use:

`column`= COMPRESS("abcd")

Then you only have to compress the input "abcd" once. You will also be able to use indexes made on the `column` column since you're comparing directly.

cwarn23 commented: Excellent Code +6
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

BTW: in the parent, you'll have defined the function: uploadDone()

eg:

function uploadDone(status) {

if (status) alert('upload complete');
else alert('upload error');

}
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Yes, unfortunatley you can't use XMLHttpRequest to upload a file fro the users computer.

The reason is that JavaScript does not have access to the file contents. It only has access to the file name, once the user has selected a file to upload. This is a security feature.

The actual upload of files, is completely done by the browser, and is not in the control of client side scripting.

Unfortunately PHP (without special extensions) cannot control the upload of the file into the sever either. This is why creating and upload progress monitor in PHP is difficult under default settings.

Taking that into account. Your choices in uploading files from browser to PHP without refreshing the page are:

1) Use an Iframe to upload the file
2) Use a client side plugin, such as Flash or Java

The first is probably the simplest, and more cross browser compatible.

So following that example I could upload the file, and I'd have all the information from the form, in the PHP, and I could synchronize the upload and the insert, but then I can't figure out how to send the OK from the PHP to a Javascript (i guess) to update the html and display the message in the web site. And anyway, is this the right approach to do what I need?

You'll need a way for the IFRAME to send a message to the parent page. From the Iframe you can …

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I have tried running the following mysql queries through the phpmyadmin command console (mysql_query() code) but I seem to be unable to retrieve the value. Here is my code.

INSERT INTO `table` SET `column`=COMPRESS("abcd")
SELECT * FROM `table` WHERE UNCOMPRESS(`column`)="abcd"

Also tried

INSERT INTO `table` SET `column`=COMPRESS("abcd")
SELECT * FROM `table` WHERE `column`=COMPRESS("abcd")

Please advice on how I should use the select query.

I tried this and it worked:

SELECT * FROM `table` WHERE `compressed` = compress('test')

The only thing I can assume is the column containing the compressed data has to be a blob or varbinary type.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi digital,

sudo chown www-data /var/www/toy/

solved the problem. I can backup with php. However, i also want to be able to see the backup files stored in that folder. Now i cannot see because ubuntu has no permission.

Thanks in advance

You cannot see the files when you do `ls` as ubuntu? What if you do it as root?

sudo ls /var/www/toy/
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi digital,

I have done the tests. I give you the result i got. It may be useful info for you to direct me what to do.

Thanks

<?php
$result = file_put_contents('/var/www/toy/test.txt', 'hi');
var_dump($result);
?>

gives this error

Warning: file_put_contents(/var/www/toy/test.txt) [function.file-put-contents]: failed to open stream: Permission denied in /var/www/in.php on line 2
bool(false)

You can see here that PHP cannot write to that folder.

ls -l /var/www/toy/

prints info given below

-rw-r--r-- 1 ubuntu ubuntu   731 2009-09-16 15:56 index.php
-rw-r--r-- 1 ubuntu ubuntu   731 2009-09-16 15:56 index.php~
-rw-r--r-- 1 ubuntu ubuntu 20576 2009-09-11 11:23 toy-11-09-2009_11:10:46.sql

The files in the folder are owned by ubuntu and group ubuntu.

-rw-r--r-- means user can read and write, group can read, world (anyone else) can read.

ie:
the groups are: user, group and world.
the access flags are: (r)ead, (w)rite, e(x)ecute

User Group World
- rw- r-- r--

var_dump(posix_getpwuid(posix_geteuid()));

prints info given below

array(7) {
  ["name"]=>
  string(8) "www-data"
  ["passwd"]=>
  string(1) "x"
  ["uid"]=>
  int(33)
  ["gid"]=>
  int(33)
  ["gecos"]=>
  string(8) "www-data"
  ["dir"]=>
  string(8) "/var/www"
  ["shell"]=>
  string(7) "/bin/sh"
}

The PHP process belongs to the user "www-data".

The user "www-data" cannot write to the folder /var/www/toy/, since only the user "ubuntu" has write privileges to it.

You'll need to give www-data privileges to write to /var/www/toy/. The simplest way is it log in as "root" or "ubuntu", and chown /var/www/toy/ to the user www-data.

eg:

sudo chown www-data /var/www/toy/

Then you should be able to have PHP write to it.

Note:

The …

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I have this info in 'User Settings'

Name-------Login name--------Home directory
veledrom ubuntu /home/ubuntu (this is active-bold and black coloured)
root root /root (this looks inactive-grey coloured)

This is what i did before.
ubuntu@ubuntu:~$ sudo chown -hR root /var/www/toy

I realise that i use root to login to mysql but in the terminal it shown ubuntu. Is ubuntu still root?

What can i do now? I bet it is something to do with users and permitions as you said, digital

Did you try and see if PHP can write to /var/www/toy/?

The permissions on the file can be viewed with the "ls" command.

eg:

ls -l /var/www/toy/

You probably want to chown the /var/www/toy/ to the PHP user.

You can get the user PHP runs as, using:

<?php
var_dump(posix_getpwuid(posix_geteuid()));
?>

To test it temporarily, chmod the directory to 777 and see if you get the SQL dump.

chmod 777 /var/www/toy

You can change it back to a safer setting when you're done testing.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi digital,

I don't know how to check if PHP has R+W privilages !!!
No password for MySQL. I didn't set it.

Thanks

A simple check is to have PHP write a file to where ever you want to check.

eg:

$result = file_put_contents('/var/www/toy/test.txt', 'hi');
var_dump($result);
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Still doesn't work. Also no error for echo exec($createBackup); .

I changed the path to /usr/bin/mysqldump -u root -h localhost toy > /var/www/toy/toy-11-09-2009_10:03:41.sql but, still doesn't work in the script.
As i said before, it works fine in Ubuntu terminal. I also, tar it in the terminal without any problem with same path.

Thanks

Does PHP have write privileges to: /var/www/toy/

Does your root account on mysql have no password? Just wondering...

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I see there is $_SERVER and $_SERVER;
Which is the best?
Also In google there are alot of $_SERVER but I cannot find it anywhere in PHP manual and doesnt work on my WAMP

Each has it's differences.

I don't think there is a HTML_ROOT, just a DOCUMENT_ROOT index in $_SERVER.

The SEVER_NAME is user defined. Your web server first checks the server name registered in DNS, then if that is not found, it will check the server configuration.
If you are distributing code, using the server name can lead to incorrect results since the server name does not reflect the host name, or the domain name in any way. Being the same is just as the host name is just the de facto configuration.

The HTTP_HOST is taken from the HTTP headers. It is the value of the "Host" http request header. This header was added later to HTTP specifications, but almost every HTTP request on the public web will have a HTTP_HOST. In fact, most site won't work without it since it is necessary to virtual host configurations.
You also cannot fully trust the HTTP_HOST value. The reason is that your server can be set up to listen on IPs and ignore the host parameter. The HTTP_HOST is essential, an you cannot gauge from PHP if it is a valid setting, unless you reflect the virtual host configuration in your PHP script, which is impossible if you're on shared hosting.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Do you really need IDs? Usually if you are going to group some elements together for some reason, use the "class" attribute instead of IDs.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

i have hard coded the header, http://www.yahoo.com .
i even commented all the code out and only left the header and the exit statement, even then it is not redirecting.

i have placed the error tags before the header code, but i am not too sure whether i should place it there, any ways i am getting the headers already sent error,

The problem is that you cannot send any HTTP headers after you have ouput content.

All the output from PHP is sent directly to the the server, which then sends it to the client via HTTP.

In the HTTP Response, you have HTTP Headers, terminated by an empty line, then the HTTP Body. Once you output something from PHP, it goes into the HTTP Body, and thus you cannot send any more HTTP Headers.

You can use the output buffering functions built into PHP.

ob_start();

That should go right at the start of teh PHP script. That will make PHP buffer all output, sot hat you can send http headers at any time, given the buffer has not been released.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Try hardcoding a URL in its place, to make sure you aren't making a mistake.

Turn on error reporting and display all errors.

error_reporting(E_ALL);
ini_set('display_errors', 1);
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Note that:

while ($xml_album->item($i)->getAttribute('ID') != $albid)
  {
	$i += 1;
   }

can will trigger an error if $albid doesn't have a corresponding value in the XML doc.

a better alternative is:

while ($xml_album->item($i) && $xml_album->item($i)->getAttribute('ID') != $albid)
  {
	$i += 1;
   }

PHP does lazy evaluation. Meaning if the first evaluation is false:

$xml_album->item($i)

Then it doesn't go on to evaluate

&& $xml_album->item($i)->getAttribute('ID') != $albid

That way you break the loop before an error is triggered. Note that if there was not error triggered, you'd actually go into an infinite loop.

Also good to check if you actually found a corresponding node, otherwise you'd run into more errors:

if ($album = $xml_album->item($i)) {
// do stuff

} else {
// error stuff
}
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

So it doesn't matter which language represents the XML document as DOM, it will have the same structure and methods defined by the DOM Specs.

Use var_dump() and get_class_methods() to find out what methods are available on an object.

For example, on your $album object.

It really helps to use teh functions that give you program state, like:

var_dump(), print_r() get_class_methods(), Reflection etc.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Yes, is is possible with wordpress. You can create custom pages with the funcitonality you want, through an extension.

I suppose you could yes, you would need to play a little with the configuration. When I say a little I mean you would have to literally rewrite allot of how wordpress work.

Also I have had my shared hosting accout hacked via a loop hole in WordPress, so I wouldn't advise you to use WordPress at all.

Josh, I wouldn't write wordpress off because it got hacked in shared hosting.

Shared hosting is usually more of the problem then the software installed on it.

Almost every account on shared hosting can be hacked, even if you use strict security measures.

ie: PHP usually runs as the same user on a single machine on shared hosting. So it can write to any file that it created, even on a different accounts.

If PHP can write to it, then anyone on the machine can write to it. It is the same for any running process on a shared host.

So when you're on a shared host, no matter how well you secure your site, if a single other site on that machine is vulnerable, your site is.

mr.khurrams commented: Thanks, too Good +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

i figured it out i use 3 serialize they a similar to a normal array and im using a ajax command that jquery includes in its library and the command is as so

$.ajax({
     url: "example .php",
     type: "POST",
     data: myArray1 + myArray2 + myArray3,
});

i took forever to find how to do this but jquery has it in API Reference under ajax

If you're sending complex data types in a query, eg: Arrays or Objects it is good to use JSON.

http://www.json.org/js.html

For example, if you use the default JavaScript JSON functions from http://www.json.org/json2.js it would be:

var str = JSON.stringify(YouObject);

I'm sure JQuery has a function for this.

You can then pass that string as a regular POST or GET parameter in your AJAX call.

PHP can parse JSON natively in PHP5, or you could use the JSON Pear lib for PHP4.

Note: JSON has become a standard for "Web2.0" (Ajaxy stuff) so every major web language either parses JSON natively, or has libraries to do it.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You can also use

unset($array);
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

what do you mean by the "raw email"?

Here is an example of a raw email. (actual address/ip/hosts are replaced with xxxxx)

Delivered-To: xxxxx@xxxx.com
Received: by xxxxxxxx with SMTP id xxxxx;
        Fri, 27 Mar 2009 01:11:xxx-0700 (PDT)
Received: by xxxxxxx with SMTP id xxxx.xxx.xxxx3;
        Fri, 27 Mar 2009 01:11:38 -0700 (PDT)
Return-Path: <xxx@xxx.xxxxxxxx.com>
Received: from xxxx.xxxxx.com (host2.xxxx.com [xxxxx])
        by mx.xxxx.com with ESMTP id xxxxxx.xxxxxx;
        Fri, 27 Mar 2009 01:11:38 -0700 (PDT)
Received-SPF: pass (xxxx.com: best guess record for domain of xxx@xxx.xxx.com designates xxxx as permitted sender) client-ip=xxxxx;
Authentication-Results: mx.xxxx.com; spf=pass (xxx.com: best guess record for domain of xxx@xxx.xxx.com designates xxxxxx as permitted sender) smtp.mail=xxx@xxx.xxxx.com
Received: from xxx by xxx.xxxx.com with local (Exim 4.69)
	(envelope-from <xxx@xxx.xxxx.com>)
	id 1Ln77j-0002a5-1M
	for info@xxxxxx.com; Fri, 27 Mar 2009 04:08:43 -0400
To: info@xxxxxxx.com
Subject: buy fioricet
X-PHP-Script: www.xxxxx.com/index.php for xxxxxx
Date: Fri, 27 Mar 2009 04:09:06 -0400
From: HsvsRsvsesv <xxxx@xxxx.net>
Message-ID: <xxxxx@www.xxxxx.com>
X-Priority: 3
X-Mailer: PHPMailer [version 1.73]
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset="iso-8859-1"
X-AntiAbuse: This header was added to track abuse, please include it with any abuse report
X-AntiAbuse: Primary Hostname - xxxxxx
X-AntiAbuse: Original Domain - xxxxx
X-AntiAbuse: Originator/Caller UID/GID - [xxxx] / [xxxx]
X-AntiAbuse: Sender Address Domain - xxxxx
X-Source: /usr/bin/php
X-Source-Args: /usr/bin/php 
X-Source-Dir: xxxxxx.com:/public_html

This is an enquiry e-mail via http://www.xxxxxxx.com from:
HsvsRsvsesv <sdfxvf3@xxxx.net>

buy fioricet

This is what your are receiving in your PHP script, and parsing.

This is a mime email with text only. Usually you'd have multiple parts: text, html, embedded media, attachments etc.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I think after making the changes you sent me, it is starting to work:
This is what i get in my email body:

1. Why is the "to" not showing though?
2. Can i also post which email sent it and which email address received the email?
3. also, can i change the "reply-to" email address so that when someone replies to the email, they reply to the correct one?

thanks so much!

The email addresses derived from the MIME headers are in the format:

Full Name <email@example.com>

It may be that you received an email address such as:

<email@example.com>

When you print this out, you won't see it since the browser will interpret it as an HTML tag.

Try using htmlentities() or viewing the HTML source.

2. Can i also post which email sent it and which email address received the email?

Off course. The address that sent the email would be the "from" header. The receiver would be "delivered-to" header.

eg:

$from = $Parser->getHeader('from');
$delivered_to = $Parser->getHeader('delivered-to');

The "to" header, can contain multiple addresses. The mail server sends the email to each address in the "to" header. Each of these addresses is then added to the "delivered-to" header.

I'm purely guessing here based on the 3 emails I'm looking at - which I copied from gmail. You'd have to look at the SMTP specs to make sure.

3. also, can i change the "reply-to" email address so that when someone …

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Could you post the raw email.

As I mentioned, I only tested the 'MimeMailParser' class on 2 or 3 emails. It may not be parsing correctly.

Give the raw email I can try debugging.

Actually, try:

$MailParser = new MimeMailParser();

$text = file_get_contents('php://stdin');
$MailParser->setText($text);

// retrieve useful info
$to = $MailParser->getHeader('to');
$from = $MailParser->getHeader('from');
$subject = $MailParser->getHeader('subject');

// the text email message
$text = $MailParser->getMessageBody('text');


// the html email message, if it exists
$html = $MailParser->getMessageBody('html');


$sendmail .= 'to = '.$to.'<br/><br/>';
$sendmail .= 'subject = '.$subject.'<br/><br/>';
$sendmail .= 'from = '.$from.'<br/><br/>';
$sendmail .= 'text = '.$text.'<br/><br/>';
$sendmail .= 'html = '.$html.'<br/><br/>';
mymailer('admin@milano4you.com','forwarding non-reply email ', $sendmail);
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi Digital-Ether,

I nearly forgot about this post, did you get my last reply?
Let me know...
Cheers

Could you post the raw email.

As I mentioned, I only tested the 'MimeMailParser' class on 2 or 3 emails. It may not be parsing correctly.

Give the raw email I can try debugging.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I think it would be more readable to use an XML parser, such as the SimpleXML parser build into PHP5.

And to use a modular approach. After a each page is parsed, to send the results to each vulnerability test, such as XSS, SQL injection, Shell injection etc.

regular expressions are a bit hard to follow.. don't you think?

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi, I've just written a script based on the previous post and the function that checks each webpage for php security flaws is as follows:

function generate($genurl) {
    $data=file_get_contents($genurl);
    $urlvars=explode('?',$genurl);
    $newurl=$urlvars[0].'?';
    $error1='None';
    //error1
    if (isset($urlvars[1])) {
        $urlvar=explode('&',$urlvars[1]);
        unset($varb);
        foreach ($urlvar AS $var) {
            $newurl.=preg_replace('/([^=]+)=(.*)/',"$1=; echo \"<script>aaabbbcccdddeeabcefffggg</script>\";",$var).'&';
            $varb=1;
            }
        unset($var);
        if ($varb==1) {
            $newurl=substr_replace($newurl,'',-1);
            if (url_exists($newurl)) {
                $secondarydata=file_get_contents($newurl);
                if (preg_match('/\<script\>aaabbbcccdddeeabcefffggg\<\/script\>/is',$secondarydata)) {
                    $error1='Page open to url injections by injecting code into the page via url.<br>The test url was: '.$newurl;
                    }
                unset($secondarydata);
                }
            }
        unset($varb);
        }
    unset($newurl);
    //error2
    preg_match_all('/\<form[^\>]+([^m][^e][^t][^h][^o][^d][^\=]([^\']|[^\"]|[^])([^p][^o][^s][^t]))(.*)\<\/form\>/i',$data,$forms);
    $error2='None';
    foreach($forms[0] AS $form) {
        preg_match_all('/(input|textarea)[^\>]+name\=(\"|\'|)/i',$form,$field);
        $fields=preg_replace('/(input|textarea)[^\>]+name\=(\"|\'|)(.*)/i',"$2",$field);
        unset($field);
        $newurls=explode('?',$genurl);
        $newurl=$newurls[0];
        unset($newurls);
        $newurl.='?';
        foreach ($fields AS $field) {
            $newurl.=$field.'='.urlencode('<script>aaabbbcccdddeeabcefffggg</script>').'&';
            $varb==1;
            }
        unset($field);
        if ($varb==1) {
            $newurl=substr_replace($newurl,'',-1);
            if (url_exists($newurl)) {
                $secondarydata=file_get_contents($newurl);
                if (preg_match('/\<script\>aaabbbcccdddeeabcefffggg\<\/script\>/is',$secondarydata)) {
                    if ($error2=='None') { $error2='Forms may inject code into your page.<br>The page was: '.$genurl; }
                    }
                unset($secondarydata);
                }
            }
        }
    unset($newurl);
    unset($form);
    unset($forms);
    unset($varb);
    //error3
    $error3='None';
    preg_match_all('/\<form(.*)(user|password)(.*)\<\/form\>/i',$data,$forms);
    foreach ($forms[0] AS $form) {
        if (preg_match('/\<form([^\>]+)method\=(\"|\'|)post/i',$form)) {
            preg_match_all('/(input|textarea)[^\>]+name\=(\"|\'|)/i',$form,$field);
            $fields=preg_replace('/(input|textarea)[^\>]+name\=(\"|\'|)(.*)/i',"$2",$field);
            unset($field);
            $newurls=explode('?',$genurl);
            $newurl=$newurls[0];
            unset($newurls);
            $newurl.='?';
            foreach ($fields AS $field) {
                $newurl.=$field.'='.urlencode('\' OR \'1\'=\'1\'').'&';
                $varb==1;
                }
            unset($field);
            if ($varb==1) {
                $newurl=substr_replace($newurl,'',-1);
                if (url_exists($newurl)) {
                    $secondarydata=file_get_contents($newurl);
                    //change if statement to if access granted
                    if (!preg_match('/(Log|Sign)([ _])?in/i',$result) && !preg_match('/(Log|Sign)([ _])?out/i',$data) && $result!==$data && !preg_match('/Register/i',$result)) {
                        if ($error3=='None') { $error2='SQL injections are possible on this page.<br>The page was: '.$genurl; }
                        }
                    unset($secondarydata);
                    }
                }
            } else {
            preg_match_all('/(input|textarea)[^\>]+name\=(\"|\'|)/i',$form,$field);
            $fields=preg_replace('/(input|textarea)[^\>]+name\=(\"|\'|)(.*)/i',"$2",$field);
            unset($field);
            $postvars='';
            foreach ($fields AS $field) {
                $postvars.=$field.'=\' OR \'1\'=\'1\'&';
                $varb==1;
                }
            unset($field);
            if ($varb==1) {
                $postvars=substr_replace($postvars,'',-1);
                $ch = curl_init();
                // set the target url
                curl_setopt($ch, CURLOPT_URL,$genurl);
                // howmany parameter to post …
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi, I'm making a site security tester which is basically a bot that scans a selected website for any php security holes such as sql injections then reports them to the user. I have managed to write the bot and all but the last piece left is the function that actually tests each individual page for security holes. The function that starts testing each individual page is as follows:

generate($url) {
$data=file_get_contents($url);
//now to do some tests on the page
}

As you can see, this function will be used on each and every valid url inside the website to perform tests on. But my question is, how do I test for php security holes and what security holes are possible?
I read something about if ;ls -la is placed in the url and not filtered it can display the contents of a web directory. But what would file_get_contents return if that is the case?

This is also an open source project so just let me know if you want the full code.

;ls -la is a linux shell command. The first part, ; is a command delimiter.

So if that were passed to the linux shell, it would first delimit any previous command, and then call the command ls -la

The -la option basically lists all files in the directory including hidden files (those preceded with .) and shows full information about them.

So ;ls -la would be an exploit against any php code that executes …

darkagn commented: very informative post +4
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Looks like STDIN does not support fseek.

You'll have to use:

$text = file_get_contents('php://stdin');
$MailParser->setText($text);

or

$text = stream_get_contents(STDIN);
$MailParser->setText($text);

etc.

This will make the whole email load into the variable $text. This however means if you have large attachments, they will be loaded into PHP's memory allocation. The max is 8mb usually so if it goes over that the script will die.

Did you try one of these suggestions?

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

hi,
ok so my host installed mailparse for me. i see it in my phpinfo.
i do get an email, but i also get mail delivery error:


this points to function "getPartBodyFromFile" and the line is "fseek($this->stream, $start, SEEK_SET);"

what shall i do?

Looks like STDIN does not support fseek.

You'll have to use:

$text = file_get_contents('php://stdin');
$MailParser->setText($text);

or

$text = stream_get_contents(STDIN);
$MailParser->setText($text);

etc.

This will make the whole email load into the variable $text. This however means if you have large attachments, they will be loaded into PHP's memory allocation. The max is 8mb usually so if it goes over that the script will die.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

IF you don't see a reference to the extension in phpinfo() then it is not installed.

The error also indicates that it isn't installed.

You actually need shell access to install PHP extensions. So you could ask your host to install it for you.

Or you could use one of the other libraries.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

If you have a specific library of choice, I can help you out with it.

Here I've written a PHP5 class for parsing mime mail messages using the PHP MailParse Extension.

<?php

/**
 * Fast Mime Mail parser Class using PHP's MailParse Extension
 * @author gabe@fijiwebdesign.com
 * @url http://www.fijiwebdesign.com/
 * @license http://creativecommons.org/licenses/by-sa/3.0/us/
 */
class MimeMailParser {
	
	/**
	 * PHP MimeParser Resource ID
	 */
	public $resource;
	
	/**
	 * A file pointer to email
	 */
	public $stream;
	
	/**
	 * A text of an email
	 */
	public $data;
	
	/**
	 * Free the held resouces
	 * @return void
	 */
	public function __destruct() {
		if (is_resource($this->stream)) {
			fclose($this->stream);
		}
		if (is_resource($this->resource)) {
			mailparse_msg_free($this->resource);
		}
	}
	
	/**
	 * Set the file path we use to get the email text
	 * @return Object MimeMailParser Instance
	 * @param $mail_path Object
	 */
	public function setPath($path) {
		// should parse message incrementally from file
		$this->resource = mailparse_msg_parse_file($path);
		$this->stream = fopen($path, 'r');
		$this->parse();
		return $this;
	}
	
	/**
	 * Set the Stream resource we use to get the email text
	 * @return Object MimeMailParser Instance
	 * @param $stream Resource
	 */
	public function setStream($stream) {
		$this->resource = mailparse_msg_create();
		$this->stream = $stream;
		// parses the message incrementally low memory usage but slower
		while(!feof($this->stream)) {
			mailparse_msg_parse($this->resource, fread($this->stream, 2082));
		}
		$this->parse();
		return $this;
	}
	
	/**
	 * Set the email text
	 * @return Object MimeMailParser Instance 
	 * @param $data String
	 */
	public function setText($data) {
		$this->resource = mailparse_msg_create();
		// does not parse incrementally, fast memory hog might explode
		mailparse_msg_parse($this->resource, $data);
		$this->data = …
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

hi again, i didnt quite understand how to use these.
could you explain please.

You have to choose one of those libraries, depending on what your PHP build supports and which you understand better.

If you are able to install extensions for PHP or have the "MailParse" extension, then you can use PHP's build in Mime-Mail parser.

http://www.php.net/manual/en/ref.mailparse.php

This would be by far the fastest and most efficient of the choices.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi,

I have a email piping code show below.
It works fine, except that when i print the $message, it also shows me some headers.
How do i strip the headers from the message itself?

email_piping.php file

#!/usr/bin/php -q
<?php
//header('Content-Type: text/html; charset=utf-8');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");  // always modified 
header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1 
header("Cache-Control: post-check=0, pre-check=0", false); 
header("Pragma: no-cache");                          // HTTP/1.0  
date_default_timezone_set('America/New_York');
ob_start();
require_once ('includes/config.inc.php');						  
require_once ('includes/functions.inc.php');
require_once ('includes/mysql_connect.php');
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
    $email .= fread($fd, 1024);
}
fclose($fd);

// handle email
$lines = explode("\n", $email);

// empty vars
$from = "";
$subject = "";
$headers = "";
$message = "";
$sendmail = "";
$splittingheaders = true;

//we have processed the headers and can start adding the lines to $message. 
for ($i=0; $i < count($lines); $i++) {
    if ($splittingheaders) {
        // this is a header
        $headers .= $lines[$i]."\n";

        // look out for special headers
        if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
            $subject = $matches[1];
        }
        if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
            $from = $matches[1];
        }
    } else {
        // not a header, but message
        $message .= $lines[$i]."\n";
    }

    if (trim($lines[$i])=="") {
        // empty line, header section has ended
        $splittingheaders = false;
    }
	
	//$a = "RE: [119-24] Work Order Request - test - dsfsd";
	preg_match("/\[[0-9]*-[0-9]*\]/",$subject,$matches);
	list($jobid, $custid) = split('[-]', $matches[0]);
	$jobid = substr($jobid, 1);	//removes first string
	$custid = substr($custid, …
digital-ether 399 Nearly a Posting Virtuoso Team Colleague
newDiv.innerHTML = '<input type="file" name="' + divIDName + '" size="57"> <a href="#" onclick="removeAdditionalFile(this.parentNode, this.count)">Remove</a>';

this.count would refer to the count property of the link (a element).

I don't think this is what is intended. Maybe:

newDiv.innerHTML = '<input type="file" name="' + divIDName + '" size="57"> <a href="#" onclick="removeAdditionalFile(this.parentNode, '+count+')">Remove</a>';
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Try piping to an empty PHP script.

See if that gives a different error message, or works, etc.

Also put an exit(0);

At the end of your PHP script just in case the MTA is waiting for a clean exit status.

You could also try piping some other program and seeing if it works. Eg: to a bash shell script, or perl etc.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

i dont understand how to execute the project.php file using eval.
can you give me a starting point?
thanks

There is a good example on the page I linked.

All you need to do is take the response from the HTTP Request (AJAX Call) and use eval to turn that string into an actual JavaScript Object.


var myObject = eval('(' + response + ')');

Anyway, I don't think this is the problem.

It looks like you don't have an XMLHttpRequest set up to execute when the page loads.

You need to attach an event handler for the window onload event, that will make the XMLHttpRequest to load the first image.

since you have JQuery, you can use something like:

$(document).ready(function() {
MyAjaxRequest('response', '/projects.php?mid=1&pid=1');
});

Or similar...

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You can execute JS by using eval(). If the JavaScript is specifically JSON, then you can use JSON library.
http://www.json.org/js.html

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Its actually displaying, but breaks the layout. The images come outside of the main box. So I think you may just have a CSS problem.

btw: You sent me the link to index.php which you mention:

When I display the smoothgallery in index.php page, it works perfectly

Is it not working in index.php or in projects.php?

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Do you get any JS errors?

Firefox has a great extension called Firebug. It has good JS debugging. Safari and Chrome also have similar debuggers/consoles.

Changing the url you have the AJAX stuff on does not make any difference. Only a change in domain would.

So you have some other problem. You can't know unless you do some JavaScript debugging.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

A change it the URL path won't affect "AJAX". Only a domain change, such as a subdomain.

So it must be something else in your code.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Background - this code adds & deletes file inputs from the screen as well as adds & deletes them from an array that will be used in the uploading process.

I'm having trouble splicing the correct value from an array. In the remove function, I think it is always removing file1/element 0 from the array rather than the corresponding file that's being deleted from the screen. Can anybody tell what's wrong with the count parameter it's using and how to fix it?

var fileNames = [];                   
fileNames[0] = "file1"; 

function addFileTextbox()                                                               
{                                                                                       
   //main div that the other divs will be added to                                       
   var divLocation = document.getElementById('addToDiv');                              
                                                                                           
   //create new div for holding textboxes, & give it a unique name for uploading         
   var newDiv = document.createElement('div');                                         
   var count = document.getElementById('addToDiv').getElementsByTagName('input').length + 2;  //+2 because since it hasn't been appended yet, the length will be short one. We need this number to set the unique div name.  
   var divIDName = 'file' + count;                                                     
   newDiv.innerHTML = '<input type="file" name="' + divIDName + '" size="57"> <a href="#" onclick="removeAdditionalFile(this.parentNode, this.count)">Remove</a>';   
                                                                                           
   //add the divIDName to the array, & store it in the hidden input.                     
   fileNames[count-1] = divIDName;  //-1 because the array starts at 0 - so file1 goes in [0], file2 in [1], etc.  
   document.fileForm.fileArray.value = fileNames.join();  //string - default comma delimiter  
                                                                                           
   //Attach new div to main div location:                                                
   divLocation.appendChild(newDiv);                                                      
}                                                                                       
                                                                                           
function removeAdditionalFile(divIDNode, count)                                         
{                                                                                       
   //get main div that the other divs are attached to                                    
   var divLocation = document.getElementById('addToDiv');                              
                                                                                          
   //delete the file textbox                                                             
   divLocation.removeChild(divIDNode);                                                   
                                                                                           
   //delete the file …