This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Showing posts with label Php. Show all posts
Showing posts with label Php. Show all posts

Saturday, 1 February 2014

How to use php to create a register and a login form [closed]

There are a lot of user management scripts online if you search with the right keywords. This seems to be promising.
PHP Login Without MySql
The source code is available and the options are like:
  • No MySql needed
  • New security features
  • Easy to upload
  • Easy to understand
  • Loads of comments, which makes the PHP very easy to modify and read
  • Simple design
  • Create confidential pages in just minutes!
You are free to get the full source, as it is in sourceforge and you can change according to your needs. You can also take the source code as an inspiration to learn and build something of your own.

Prevent Adblock Users from Accessing Website? [closed]




Im one of the Users who use Adblock. And i love it.

That question could be interesting for all of us. Once i visited a german developer website, I just saw a jquery fancybox, on that box there was a Message something like this: "You are using Adblock, this site is financed with ads. If you want be able to see the content deactivate Adblock or Remove it."
First i thought WOW thats funny. Im sure there is also an hack for this. Just using another user agent would give you access to the website content or not? ididnt tested but it could be Possible. In Future most Website Owners will prevent Users seeing the content of the site who uses Adblock.
How could we implement an Script like the above? nomatter which language we use javascript,php,asp,jsp and how could we hack it? with hack i mean seeing the content without deactivating the Adblock.



Personally I will not stop adblock users visiting my site - there is such thing as freedom of the internet. As my site allows you freedom to say and discuss pretty much what you want, then doing such a thing would be hypocritical.
However having said that I would appreciate it if people did visit then they could turn off adblock for my sites pages. I do not have the massive finances to run my site like the big corporations and stores, so it would be a shame if I did have to remove guest posting or make my members pay a small subscription.
Some Internet users assume that small forum and website owners make a fortune in advertizing - this is a myth, in fact we barely even scrape a few bucks towards the hosting costs. Please try to remember this as many of your favorite website will be making a few dollars and taking away that valuable income may see your favorite website disappear.

Calculating hours and minutes between two times [duplicate]

$time1 = '12:58';
$time2 = '15:00';
list($hours, $minutes) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes);

list($hours, $minutes) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes);

$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));

echo "Time passed: <b>$hours</b> hours and <b>$minutes</b> minutes";

Grabbing the href attribute of an A element

87 down vote accepted

Reliable Regex for HTML are difficult. Here is how to do it with DOM:
$dom = new DOMDocument;
$dom
->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) {
echo $dom
->saveHtml($node), PHP_EOL;
}
The above would find and output the "outerHTML" of all A elements in the $html string.
To get all the text values of the node, you do
echo $node->nodeValue; 
To check if the href attribute exists you can do
echo $node->hasAttribute( 'href' );
To get the href attribute you'd do
echo $node->getAttribute( 'href' );
To change the href attribute you'd do
$node->setAttribute('href', 'something else');
To remove the href attribute you'd do
$node->removeAttribute('href'); 
You can also query for the href attribute directly with XPath
$dom = new DOMDocument;
$dom
->loadHTML($html);
$xpath
= new DOMXPath($dom);
$nodes
= $xpath->query('//a/@href');
foreach($nodes as $href) {
echo $href
->nodeValue; // echo current attribute value
$href
->nodeValue = 'new value'; // set new attribute value
$href
->parentNode->removeAttribute('href'); // remove attribute
}
Also see:

How can I convert ereg expressions to preg in PHP?

The biggest change in the syntax is the addition of delimiters.
ereg('^hello', $str);
preg_match
('/^hello/', $str);
Delimiters can be pretty much anything that is not alpha-numeric, a backslash or a whitespace character. The most used are generally ~, / and #.
You can also use matching brackets:
preg_match('[^hello]', $str);
preg_match
('(^hello)', $str);
preg_match
('{^hello}', $str);
// etc
If your delimiter is found in the regular expression, you have to escape it:
ereg('^/hello', $str);
preg_match
('/^\/hello/', $str);
You can easily escape all delimiters and reserved characters in a string by using preg_quote:
$expr = preg_quote('/hello', '/');
preg_match
('/^'.$expr.'/', $str);
Also, PCRE supports modifiers for various things. One of the most used is the case-insensitive modifier i, the alternative to eregi:
eregi('^hello', 'HELLO');
preg_match
('/^hello/i', 'HELLO');
You can find the complete reference to PCRE syntax in PHP in the manual, as well as a list of differences between POSIX regex and PCRE to help converting the expression.

Are PHP short tags acceptable to use?

They're not recommended because it's a PITA if you ever have to move your code to a server where it's not supported (and you can't enable it). As you say, lots of shared hosts do support shorttags but "lots" isn't all of them. If you want to share your scripts, it's best to use the full syntax.
I agree that <? and <?= are easier on programmers than <?php and <?php echo but it is possible to do a bulk find-and-replace as long as you use the same form each time (and don't chuck in spaces (eg: <? php or <? =)
I don't buy readability as a reason at all. Most serious developers have the option of syntax highlighting available to them.
As ThiefMaster mentions in the comments, as of PHP 5.4, <?= ... ?> tags are supported everywhere, regardless of shorttags settings. This should mean they're safe to use in portable code but that does mean there's then a dependency on PHP 5.4+. If you want to support pre-5.4 and can't guarantee shorttags, you'll still need to use <?php echo ... ?>.

UTF-8 all the way through

Data Storage:
  • Specify the utf8 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8 encoding if a utf8_* collation is specified (without any explicit character set).
  • The MySQL utf8 encoding is only a subset of actual UTF-8, supporting only the BMP. MySQL 5.5 and higher support utf8mb4, which is "real" UTF-8 and should be preferred if supported.
Data Access:
  • In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to utf8. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.
  • Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:
    • If you're using the PDO abstraction layer with PHP ≥ 5.3.6, you can specify charset in the DSN:
      $dbh = new PDO('mysql:charset=utf8');
    • If you're using mysqli, you can call set_charset():
      $mysqli->set_charset('utf8');       // object oriented style
      mysqli_set_charset($link, 'utf8'); // procedural style
  • If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8'.
  • The same consideration regarding utf8/utf8mb4 applies as above.
Output:
  • If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).
  • In PHP, you can use the default_charset php.ini option, or manually issue the Content-Type MIME header yourself, which is just more work but has the same effect.
Input:
  • Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's mb_check_encoding()does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.
  • From my reading of the current HTML spec, the following sub-bullets are not necessary or even valid anymore for modern HTML. My understanding is that browsers will work with and submit data in the character set specified for the document. However, if you're targeting older versions of HTML (XHTML, HTML4, etc.), these points may still be useful:
    • For HTML before HTML5 only: you want all data sent to you by browsers to be in UTF-8. Unfortunately, if you go by the the only way to reliably do this is add the accept-charset attribute to all your <form> tags: <form ... accept-charset="UTF-8">.
    • For HTML before HTML5 only: note that the W3C HTML spec says that clients "should" default to sending forms back to the server in whatever charset the server served, but this is apparently only a recommendation, hence the need for being explicit on every single <form> tag.
Other Code Considerations:
  • Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.
  • You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's mbstring extension.
  • PHP's built-in string operations are not by default UTF-8 safe.There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring function.
  • To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from utf8.com for some good resources to learn everything you need to know.

Secure hash and salt for PHP passwords

TL;DR

Don'ts

  • Don't limit what characters users can enter for passwords. Only idiots do this.
  • Don't limit the length of a password. If your users want a sentence with supercalifragilisticexpialidocious in it, don't prevent them from using it.
  • Never store your user's password in plain-text.
  • Never email a password to your user except when they have lost theirs, and you sent a temporary one.
  • Never, ever log passwords in any manner.
  • Never hash passwords with SHA1 or MD5! Modern crackers can exceed 60 and 180 billion hashes/second (respectively).

Do's

  • Use scrypt when you can; bcrypt if you cannot.
  • Use PBKDF2 if you cannot use either bcrypt or scrypt, with SHA2 hashes.
  • Reset everyone's passwords when the database is compromised.
  • Implement a reasonable 8-10 character minimum length, plus require at least 1 upper case letter, 1 lower case letter, a number, and a symbol. This will improve the entropy of the password, in turn making it harder to crack. (See the "What makes a good password?" section for some debate.)

Why hash passwords anyway?

The objective behind hashing passwords is simple: preventing malicious access to user accounts by compromising the database. So the goal of password hashing is to deter a hacker or cracker by costing them too much time or money to calculate the plain-text passwords. And time/cost are the best deterrents in your arsenal.
Another reason that you want a good, robust hash on a user accounts is to give you enough time to change all the passwords in the system. If your database is compromised you will need enough time to at least lock the system down, if not change every password in the database.
Jeremiah Grossman, CTO of Whitehat Security, stated on his blog after a recent password recovery that required brute-force breaking of his password protection:
Interestingly, in living out this nightmare, I learned A LOT I didn’t know about password cracking, storage, and complexity. I’ve come to appreciate why password storage is ever so much more important than password complexity. If you don’t know how your password is stored, then all you really can depend upon is complexity. This might be common knowledge to password and crypto pros, but for the average InfoSec or Web Security expert, I highly doubt it.
(Emphasis mine.)

What makes a good password anyway?

Entropy. (Not that I fully subscribe to Randall's viewpoint.)
In short, entropy is how much variation is within the password. When a password is only lowercase roman letters, that's only 26 characters. That isn't much variation. Alpha-numeric passwords are better, with 36 characters. But allowing upper and lower case, with symbols, is roughly 96 characters. That's a lot better than just letters. One problem is, to make our passwords memorable we insert patterns—which reduces entropy. Oops!
Password entropy is approximatedeasily. Using the full range of ascii characters (roughly 96 typeable characters) yields an entropy of 6.6 per character, which at 8 characters for a password is still too low (52.679 bits of entropy) for future security. But the good news is: longer passwords, and passwords with unicode characters, really increase the entropy of a password and make it harder to crack.
There's a longer discussion of password entropy on the Crypto StackExchange site. A good Google search will also turn up a lot of results.
In the comments I talked with @popnoodles, who pointed out that enforcinga password policy of X length with X many letters, numbers, symbols, etc, can actually reduce entropy by making the password scheme more predictable. I do agree. Randomess, as truly random as possible, is always the safest but least memorable solution.
So far as I've been able to tell, making the world's best password is a Catch-22. Either its not memorable, too predictable, too short, too many unicode characters (hard to type on a Windows/Mobile device), too long, etc. No password is truly good enough for our purposes, so we must protect them as though they were in Fort Knox.

Best practices

Bcrypt and scrypt are the current best practices. Scryptwill be better than bcrypt in time, but it hasn't seen adoption as a standard by Linux/Unix or by webservers, and hasn't had in-depth reviews of its algorithm posted yet. But still, the future of the algorithm does look promising. If you are working with Ruby there is an scrypt gem that will help you out, and Node.js now has its own scrypt package.
I highly suggest reading the documentation for the crypt function if you want to roll your own use of bcrypt, or finding yourself a good wrapper or use something like PHPASS for a more legacy implementation. I recommend a minimum of 12 rounds of bcrypt, if not 15 to 18.
I changed my mind about using bcrypt when I learned that bcrypt only uses blowfish's key schedule, with a variable cost mechanism. The latter lets you increase the cost to brute-force a password by increasing blowfish's already expensive key schedule.

Average practices

I almost can't imagine this situation anymore. PHPASS supports PHP 3.0.18 through 5.3, so it is usable on almost every installation imaginable—and should be used if you don't know for certain that your environment supports bcrypt.
But suppose that you cannot use bcrypt or PHPASS at all. What then?
Try an implementation of PDKBF2 with the maximum number of roundsthat your environment/application/user-perception can tolerate. The lowest number I'd recommend is 2500 rounds. Also, make sure to use hash_hmac() if it is available to make the operation harder to reproduce.

Future Practices

Coming in PHP 5.5 is a full password protection librarythat abstracts away any pains of working with bcrypt. While most of us are stuck with PHP 5.2 and 5.3 in most common environments, especially shared hosts, @ircmaxell has built a compatibility layer for the coming API that is backward compatible to PHP 5.3.7.

Cryptography Recap & Disclaimer

The computational power required to actually crack a hashed password doesn't exist. The only way for computers to "crack" a password is to recreate it and simulate the hashing algorithm used to secure it. The speed of the hash is linearly related to its ability to be brute-forced. Worse still, most hash algorithms can be easily parallelized to perform even faster. This is why costly schemes like bcrypt and scrypt are so important.
You cannot possibly foresee all threats or avenues of attack, and so you must make your best effort to protect your users up front. If you do not, then you might even miss the fact that you were attacked until it's too late... and you're liable. To avoid that situation, act paranoid to begin with. Attack your own software (internally) and attempt to steal user credentials, or modify other user's accounts or access their data. If you don't test the security of your system, then you cannot blame anyone but yourself.
Lastly: I am not a cryptographer. Whatever I've said is my opinion, but I happen to think it's based on good ol' common sense ... and lots of reading. Remember, be as paranoid as possible, make things as hard to intrude as possible, and then, if you are still worried, contact a white-hat hacker or cryptographer to see what they say about your code/system.

Using a regular expression to validate an email address

There is no simple regular expression for this problem: see this fully RFC‑822–compliant regex, which is anything but simple. (It was written before the days of grammatical patterns.) The grammar specified in RFC 5322is too complicated for primitive regular expressions, although the more sophisticated grammatical patterns in Perl, PCRE, and PHP can all manage to correctly parse RFC 5322 without a hitch. Python and C# should also be able to manage it, but they use a different syntax from those first three.
However, if you are forced to use one of the many less powerful pattern-matching languages, then it’s best to use a real parser. But understand that validating it per the RFC tells you absolutely nothing about whether the person entering the address is its true owner. People sign others up to mailing lists this way all the time. Fixing that requires a fancier kind of validation that involves sending that address a message that includes a confirmation token meant to be entered in the same web page as was the address.
That's the only way to know you got the address of the person entering it, which is why most mailing lists now use that mechanism to confirm sign-ups. After all, anybody can put down president@whitehouse.gov, and that will even parse as legal, but it isn’t likely to be the person at the other end.
For PHP, you should not use the pattern given in Validate an E-Mail Address with PHP, the Right Way from which I quote:
There is some danger that common usage and widespread sloppy coding will establish a de facto standard for e-mail addresses that is more restrictive than the recorded formal standard.
That is no better than all the other non-RFC patterns. It isn’t even smart enough to handle even RFC 822, let alone RFC 5322. This one, however, is.
If you want to get fancy and pedantic, implement a complete state engine. A regular expression can only act as a rudimentary filter. The problem with regular expressions is that telling someone that their perfectly valid e-mail address is invalid (a false positive) because your regular expression can't handle it is just rude and impolite from the user's perspective. A state engine for the purpose can both validate and even correct e-mail addresses that would otherwise be considered invalid as it disassembles the e-mail address according to each RFC. This allows for a potentially more pleasing experience, like
The specified e-mail address 'myemail@address,com' is invalid. Did you mean 'myemail@address.com'?
See also Validating Email Addresses, including the comments. Or Comparing E-mail Address Validating Regular Expressions.
share|improve this answer

56  
You said "There is no good regular expression." Is this general or specific to e-mail address validation? –  Tomalak Oct 14 '08 at 14:33
11  
@Tomalak: only for email addresses. As bortzmeyer said, the RFC is extremely complicated –  Luk Oct 14 '08 at 16:23
20  
ietf.org/rfc/rfc5322.txt for the brave :-) –  bortzmeyer Oct 14 '08 at 19:27
6  
I've heard of an attempt to do a regular expression that covers much of the RFC. It was over a page long and still hopelessly incomplete. :-) –  Bloodboiler Oct 22 '08 at 18:00
18  
The linux journal article you mention is factually wrong in several respects. In particular Lovell clearly hasn't read the errata to RFC3696 and repeats some of the errors in the published version of the RFC. More here: dominicsayers.com/isemail –  Dominic Sayers Apr 8 '09 at 15:56

PHP: “Notice: Undefined variable” and “Notice: Undefined index”

From the vast wisdom of the PHP Manual:
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Some explanations:

Although PHP does not require variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that he will use later in the script. What PHP does in the case of undeclared variables is issue a very low level error, E_NOTICE, one that is not even reported by default, but the Manual advises to allow during development.

Ways to deal with the issue:

  1. Recommended: Declare your variables. Or use isset() to check if they are declared before referencing them.
  2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file). set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT).
  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is error_reporting( error_reporting() & ~E_NOTICE ).
  4. Suppress the error with the @ operator.
Note: It's strongly recommended to implement just point 1.
Related:

Reference - What does this error mean in PHP?

Warning: Cannot modify header information - headers already sent

Happens when your script tries to send a HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.
This is an E_WARNING and it will not stop the script.
A typical example would be a template file like this:
<html>
<?php session_start(); ?>
<head><title>My Page</title>
</html>
...
The session_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html> element to the output stream. You'd have to move the session_start() to the top.
You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.
An often overlooked output is new lines after PHP's closing ?>. Good practise is to omit them when they are the last thing in the file. Likewise, another common cause for this warning when your code is all PHP, is when the starting <?php have an empty space or line before it, causing the webserver to send the headers and the whitespace/newline thus when PHP starts parsing won't be able to submit any header.
If your file has more than one block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)
Also make sure you don't have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.
Related questions:
share|improve this answer

2  
Probably a good idea to add a note about UTF-8 BOM. –  luiscubal Oct 7 '12 at 16:23
4  
@luiscubal click "edit" and write the note :-) –  Jocelyn Oct 7 '12 at 16:37
 
If you are using WordPress, check the theme files. When I upgraded a site to a new version of WordPress, I was unable to update the theme because it has not been updated in several years. This problem cropped up. It turned out that the functions.php file had more than one <? ?> block with spaces in between. –  Roy Leban Mar 31 '13 at 8:41
 
@RoyLeban "If your file has more than one block in it..." I'm not sure what this means. What is a "block"? Would one block consist of <?php ?> and so "more than one block" would be <?php ?> <?php ?>? –  Andrew Fox 2 days ago

mysql_fetch_array() expects parameter 1 to be resource, boolean given in select

Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the mysql_query documentation for possible return values and suggestions for how to deal with them.
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");

if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}

while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
This example is only to illustrate what should be done (error handling), not how to do it. Production code shouldn't use or diewhen outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.

How to fix “Headers already sent” error in PHP

No output before sending headers!

Functions that send/modify HTTP headers must be invoked before any output is made. Otherwise the call fails:
Warning: Cannot modify header information - headers already sent (output started at file:line)
Some functions modifying the HTTP header are:
Output can be:
  • Unintentional:
  • Intentional:
    • print, echo and other functions producing output (like var_dump)
    • Raw <html> areas before <?php code.

Why does it happen?

To understand why headers must be sent before output it's necessary to look at a typical HTTP*response. PHP scripts mainly generate HTML content, but also pass a set of HTTP/CGI headers to the webserver:
 HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8

<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=about:note> ...
The page/output always follows the headers. PHP is required to pass the headers to the webserver first. It can only do that once. And after the double linebreak it can't ever append to them again.
When PHP receives the first output (print, echo, <html>) it will "flush" the collected headers. Afterwards it can send all the output bits it wants. But sending further headers is impossible from then.

How can you find out where the premature output occured?

The header() warning contains all relevant information to locate the problem source:
Warning: Cannot modify header information - headers already sent by (output started at /www/usr2345/htdocs/auth.php:52) in /www/usr2345/htdocs/index.php on line 100
Here "line 100" refers to the script where the header() invocation failed.
The message in the inner parenthesis is more crucial. It mentions auth.php and line 52 as the source of premature output. One of the typical problem causes will be there:

Print, echo

Intentional output from print and echo statements will terminate the opportunity to send HTTP headers. The application flow must be restructured to avoid that. Use functionsand templating schemes. Ensure header() calls occur before messages are written out.
Functions that can write output include print, echo, printf, trigger_error, vprintf, ob_flush, var_dump, readfile, passthruamong others and user-defined functions.

Raw HTML areas

Unparsed HTML sections in a .php file are direct output as well. Script conditions that will trigger a header() call must be noted before any raw <html> blocks.
<!DOCTYPE html>
<?php
// Too late for headers already.

Whitespace before <?php when "somefile.php line 1" mentioned

If the message says the error is in line 1, then it is typically leading whitespace, text or HTML before the opening <?php marker.
 <?php
# There's a SINGLE! space/newline before <? - Which already seals it.
It can likewise occur for appended scripts or script sections:
?>

<?php
PHP actually eats up a single linebreak after close tags. But it won't compensate multiple newlines or tabs or spaces shifted into such gaps.

UTF-8 BOM

Linebreaks and spaces alone can be a problem. But there are also "invisible" character sequences which can cause this. Most famously the UTF-8 BOM (Byte-Order-Mark)which isn't displayed by most text editors. It's the byte sequence EF BB BF, which is optional and redundant for UTF-8 encoded documents. But the PHP interpreter treats it as raw output. It may show up as the characters  in the output (if the client interprets the document as Latin-1) or similar "garbage".
In particular graphical editors and Java based IDEs are oblivious to its presence. They don't visualize it (obliged by the Unicode standard). Some programmer and console editors however do:
joes editor showing utf-8 bom placeholder, and mc editor a dot
There it's easy to recognize the problem early on. Without such an editor available (or Notepad++ on Windows, which can remedy the problemper menu command), another resort would be a hexeditor. Programmers should have one, as they simplify auditing these kind of issues:
beav hexeditor showing utf-8 bom
The easy fix is to set the text editor to save files as "UTF-8 (no BOM)" or similar such nomenclature. Many newcomers resort to creating new files and just copy&pasting the previous code back in.

Correction utilities

Actually there are automated tools to rewrite text files. For PHP specifically there is the phptags tag tidier. It rewrites close and open tags into long and short forms, but also easily fixes leading and trailing whitespace (and BOM) issues:
 phptags  --whitespace  *.php
It's sane to use on a whole include or project directory.

Whitespace after ?>

If the error source is mentioned as behind the closing ?>then this is where some whitespace or raw text got written out. The PHP end tag does not terminate script executation at this point. Any characters after it will be output as page content still.
It's commonly advised, in particular to newcomers, that trailing ?> PHP close tags should be omitted. This eschews a significant part of these cases. (Quite commonly include() scripts are the culprit.)
Again phptags --whitespace *.php fixes that more easily.
Likewise phptags --unclosed ./includes could drop redundant ?> from scripts.

Error source mentioned as "Unknown on line 0"

It's typically an PHP extension or php.ini setting if no error source is specified. It's occasionally the gzip stream encoding extension or the ob_gzhandler. But it could also be any doubly loaded extension= module, which let to an implicit warning message.

Preceding error messages

If another PHP statement or expression causes a warning message or notice being printeded out, that also counts as premature output.
In this case you need to eschew the error, delay the statement execution, or suppress the message with e.g. isset() or @() - when this doesn't obstruct debugging later on.

No error message

If you have error_reporting or display_errors disabled per php.ini, then no warning will show up. But ignoring errors won't make the problem go away. Headers cannot be sent after premature output still.
So when header("Location: ...") redirects fail siliently it's good to probe for warnings. Reenable them with two simple commands (atop the very first script):
error_reporting(E_ALL);
ini_set("display_errors", 1);
Or set_error_handler("var_dump"); if all else fails.
Speaking of redirect headers, you should often use an idiom like this for final code paths:
exit(header("Location: /finished.html"));
Preferrably even a utility function, which prints a user message in case of header() failure.

Output buffering as workaround

PHPs output bufferingis suitable to alleviate this issue. It often does so quite reliaby, but should be considered strictly a workaround. Its actual purpose is minimizing chunked transfers to the webserver. Restructuring the application to avoid premature output is preferable.
Nevertheless does the output_buffering=setting help. Configure it in the php.ini*or via .htaccess*or even .user.ini*. With that enabled content gets buffered and not instantly passed on to the webserver. Thus HTTP headers can be aggregated.
It can likewise be engaged with a call to ob_start();atop the invocation script. This however is less reliable for a few reasons:
  • Even if <?php ob_start(); ?> starts the first script, whitespace or a BOM can get shuffled before, rendering it ineffective.*
  • It can conceal whitespace for HTML output; but as soon as the application logic attempts to send binary content (a generated image for example), the buffered extraneous spaces become a problem. (Though ob_clean() often is another workaround.)
  • The buffer is limited in size. While usually a hypothetical problem, it might however overrun - which wouldn't be easy to trace.
See also the basic usage examplein the manual, and for more pros and cons:

But it worked on the other server!?

If you didn't get the headers warning before, then the php.ini settinghas been changed. Output buffering then was enabled on the other server, but not on the current. See previous section.

Checking with headers_sent()

You can always use headers_sent() to probe if it's still possible to... send headers. That's useful to conditionally print an info or apply other fallback logic.
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=...>");
}
else{
exit(header("Location: /user.php"));
}

HTML <meta> tag workaround

If your application is structurally hard to fix, then an easy (but totally unprofessional) way to allow redirects is injecting HTML. A redirect can be achieved by:
 <meta http-equiv="Location" content="http://example.com/">
Or with a short delay:
 <meta http-equiv="Refresh" content="2; url=../target.html">
This will make your website non-valid (even if faux XHTML) when printed outside the <head> part. Most browsers still accept it. As alternative a Javascript redirectcould do:
 <script> location.replace("target.html"); </script>
It's an acceptable approach if this is used as a fallback by specialized redirect utility functions. Which should first attempt to send a proper header(), but use the meta tag equivalents and a user-friendly message and link as last resort.

Why setcookie() and session_start() are also affected

Both setcookie() and session_start() need to send a Set-Cookie: HTTP header(). The same conditions therefore apply, and similar error messages will be generated with premature output situations.
Header output problems are not the only cause for non-functionality with them of course. Disabled cookies in the browser, or even proxy issues should always be checked. The session functionality also depends on free disk space and other php.ini settings.

Further links

How do you parse and process HTML/XML in PHP?

Native XML Extensions

I prefer using one of the native XML extensionssince they come bundled with PHP, are usually faster than all the 3rd party libs and give me all the control I need over the markup.

DOM

The DOM extension allows you to operate on XML documents through the DOM API with PHP 5. It is an implementation of the W3C's Document Object Model Core Level 3, a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents.
DOM is capable of parsing and modifying real world (broken) HTML and it can do XPath queries. It is based on libxml.
It takes some time to get productive with DOM, but that time is well worth it IMO. Since DOM is a language-agnostic interface, you'll find implementations in many languages, so if you need to change your programming language, chances are you will already know how to use that language's DOM API then.
A basic usage example can be found in Grabbing the href attribute of an A element and a general conceptual overview can be found at DOMDocument in php
How to use the DOM extension has been covered extensively on StackOverflow, so if you choose to use it, you can be sure most of the issues you run into can be solved by searching/browsing Stack Overflow.

XMLReader

The XMLReader extension is an XML pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.
XMLReader, like DOM, is based on libxml. I am not aware of how to trigger the HTML Parser Module, so chances are using XMLReader for parsing broken HTML might be less robust than using DOM where you can explicitly tell it to use libxml's HTML Parser Module.
A basic usage example can be found at getting all values from h1 tags using php

SimpleXml

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.
SimpleXML is an option when you know the HTML is valid XHTML. If you need to parse broken HTML, don't even consider SimpleXml because it will choke.
A basic usage example can be found at A simple program to CRUD node and node values of xml file and there is lots of additional examples in the PHP Manual.

3rd Party Libraries (libxml based)

If you prefer to use a 3rd-party lib, I'd suggest using a lib that actually uses DOM/libxml underneath instead of string parsing.

phpQuery

phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library written in PHP5 and provides additional Command Line Interface (CLI).

Zend_Dom

Zend_Dom provides tools for working with DOM documents and structures. Currently, we offer Zend_Dom_Query, which provides a unified interface for querying DOM documents utilizing both XPath and CSS selectors.

QueryPath

QueryPath is a PHP library for manipulating XML and HTML. It is designed to work not only with local files, but also with web services and database resources. It implements much of the jQuery interface (including CSS-style selectors), but it is heavily tuned for server-side use. Can be installed via Composer.

FluentDom

FluentDOM provides a jQuery-like fluent XML interface for the DOMDocument in PHP. Selectors are written in XPath, rather than CSS (claims to improve performance). Can be installed via Composer.

fDOMDocument

fDOMDocument extends the standard DOM to use exceptions at all occasions of errors instead of PHP warnings or notices. They also add various custom methods and shortcuts for convenience and to simplify the usage of DOM.

3rd-Party (not libxml-based)

The benefit of building upon DOM/libxml is that you get good performance out of the box because you are based on a native extension. However, not all 3rd-party libs go down this route. Some of them listed below

SimpleHtmlDom

  • An HTML DOM parser written in PHP5+ lets you manipulate HTML in a very easy way!
  • Require PHP 5+.
  • Supports invalid HTML.
  • Find tags on an HTML page with selectors just like jQuery.
  • Extract contents from HTML in a single line.
I generally do not recommend this parser. The codebase is horrible and the parser itself is rather slow and memory hungry. Any of the libxml based libraries should outperform this easily.

Ganon

  • A universal tokenizer and HTML/XML/RSS DOM Parser
    • Ability to manipulate elements and their attributes
    • Supports invalid HTML and UTF8
  • Can perform advanced CSS3-like queries on elements (like jQuery -- namespaces supported)
  • A HTML beautifier (like HTML Tidy)
    • Minify CSS and Javascript
    • Sort attributes, change character case, correct indentation, etc.
  • Extensible
    • Parsing documents using callbacks based on current character/token
    • Operations separated in smaller functions for easy overriding
  • Fast and Easy
Never used it. Can't tell if it's any good.

HTML 5

You can use the above for parsing HTML5, but there can be quirks due to the markup HTML5 allows. So for HTML5 you want to consider using a dedicated parser, like
html5lib
A Python and PHP 

How can I prevent SQL injection in PHP?

If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:
$unsafe_variable = $_POST['user_input']; 

mysql_query("INSERT INTO table (column) VALUES ('" . $unsafe_variable . "')");
That's because the user can input something like value'); DROP TABLE table;--, and the query becomes:
INSERT INTO table (column) VALUES('`**`value'); DROP TABLE table;--`**`')
What can be done to prevent this from happening?

Use prepared statements and parameterized queries.These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
  1. Using PDO:
    $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

    $stmt->execute(array('name' => $name));

    foreach ($stmt as $row) {
    // do something with $row
    }
  2. Using mysqli:
    $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
    $stmt->bind_param('s', $name);

    $stmt->execute();

    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
    // do something with $row
    }

PDO

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And gives the developer the chance to catch any error(s) which are thrown as PDOExceptions.
What is mandatory however is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use realprepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

What happens is that the SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute, the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not a SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains 'Sarah'; DELETE * FROM employees the result would simply be a search for the string "'Sarah'; DELETE * FROM employees", and you will not end up with an empty table.
Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute(array('column' => $unsafeValue));

Friday, 15 November 2013

How php language execute?

php is a interpretend language

An interpreted language is a programming language that executes instructions directly, without previously compiling a program into machine-language instructions. The interpreter executes the program directly, translating each statement into machine code on the fly as required. Compiled language programs, on the other hand, must explicitly be entirely translated ("compiled") into a sequence of machine language instructions before they can be executed.

What is the difference between strstr() and stristr()?

strstr -- Find first occurrence of a string and get the string from that character

strstr() example

<?php
$mail = 'pass@examplem.com';
$domain = strstr($mail, '@');
echo $domain; // prints @examplem.com
?>

stristr -- Case-insensitive strstr()

stristr() example

<?php
$email = 'USER@EXAMPLE.com';
echo stristr($email, 'e');
// outputs ER@EXAMPLE.

What are the differences between split, implode and explode?



split() and explode() are aliases for one-another. implode() and join() are
aliases for each other. i believe the name was originally explode(), but
split() was chosen later to suit perl programmers.

Different between implode and explode in php?

Implode

Join array elements with a string


Example

implode() example

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>

EXPLODE:

split string as array


<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

What is PEAR?

 PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:

    A structured library of open-source code for PHP users
    A system for code distribution and package maintenance
    A standard style for code written in PHP, specified here
    The PHP Extension Community Library (PECL), see more below
    A web site, mailing lists and download mirrors to support the PHP/PEAR community

PEAR is a community-driven project governed by its developers. PEAR's governing bodies are subdivided into the PEAR Group, Collectives, and a President. PEAR's constitution (adopted in March 2007) defining these groups is documented here. The PEAR project was founded in 1999 by Stig S. Bakken and quite a lot of people have joined the project.
PEAR Mission Statement

PEAR's mission is to provide reusable components, lead innovation in PHP, provide best practices for PHP development and educate developers.
Structured Libraries and Applications of PHP Code

The code in PEAR is partitioned in "packages". Each package is a separate project with its own development team, version number, release cycle, documentation and a defined relation to other packages (including dependencies). Packages are distributed as gzipped tar files with a description file inside, and installed on your local system using the PEAR installer.

Packages may relate to each other through explicit dependencies, but there is no automatic dependency relationship between packages based on the package name. For example, "HTTP_Post" is by default independent of "HTTP". Dependencies between packages with similar names is not forbidden, and does happen. As an example,the "DB_DataObject" package depends on the "DB" package.

A style guide, the PEAR Coding Standards (short PCS), exists to ease collaboration between PEAR developers, to enforce quality, and to enforce a consistent visual appearance of all source code distributed as a PEAR package.
Code Distribution and Package Maintenance

All PEAR packages are registered in and downloaded from a central server at pear.php.net. Other third-party servers called "channels" also distribute packages that can be installed by the PEAR Installer, see the Channels list for more information. pear.php.net does not endorse the packages from these channels, and only provides support for packages distributed from pear.php.net.

Pear.php.net provides both a human-friendly (HTML) and machine-friendly (currently REST) interface to the packages available from pear.php.net. All communication occurs over the HTTP protocol. Other functions the pear.php.net site provides are:

    user account management (independent of the SVN server)
    package management
    release management

Packages are distributed as a gzipped tar file with an XML description file inside. The description file (package.xml) contains some information about the package, a list of files and their roles, and dependencies.
The PHP Extension Community Library (PECL)

PECL

PECL (pronounced "pickle") is a separate project that distributes PHP extensions (compiled code written in C, such as the PDO extension). PECL extensions are also distributed as packages and can be installed using the PEAR installer with the pecl command.

More information and all PECL packages can now be found on the PECL homepage.

Twitter Delicious Facebook Digg Stumbleupon Favorites More