Categories
PHP

Php script redirects even when output started before calling header() function

This happens because of output_buffering is on.

In order to turn off output buffering modify php.ini if you have access and set:

output_buffering = Off

or add in the local directory a .htaccess file containing this line:

php_value output_buffering Off   # or 0 
Categories
MySQL mysqldump PHP

mysqldump – with exec() function from php outputs empty file

This error occurs on any operating system (windows, linux). The problem is that instead of getting a sql file with the database data you get a empty (0 kb.) file.

So we have the following code:

$command = "mysqldump --opt --skip-extended-insert --complete-insert -h ".$DB_HOST." -u ".$DB_USER." -p ".$DB_PASS." ".$DB_NAME." > backup.sql";

exec($command, $ret_arr, $ret_code);
echo "ret_arr: <br />";
print_r($ret_arr);

and we get an empty file and no output.

So we will fix this error in a few steps:

1. First we need to make sure that we have access to mysqldump command. For Linux machines this command is accessible from anywhere if not you will have to find the place where mysqldump file is (usually the bin folder of mysql).

In order to do this we have to get some output from our command so we will strip all the options from the command and we will remain with this:

$command = "mysqldump"; // mysqldump.exe on Windows

So execute the php script. It’s ok if you get output like this:

Array
(
    [0] => Usage: mysqldump [OPTIONS] database [tables]
    [1] => OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
    [2] => OR     mysqldump [OPTIONS] --all-databases [OPTIONS]
    [3] => For more options, use mysqldump --help
)

If you don’t see something like that then you must check to see the path to the mysqldump command.

If you are in windows make sure you append the full path to the command. If you have a folder like I have C:\\Program Files\\MySQL\\MySQL Server 4.1\\bin\\mysqldump.exe with spaces in it you must make sure that you enclose the command between quotes like this:

$command = "\"C:\\Program Files\\MySQL\\MySQL Server 4.1\\bin\\mysqldump.exe\" --opt --skip-extended-insert --complete-insert -h ".$DB_HOST." -u ".$DB_USER." -p ".$DB_PASS." ".$DB_NAME." > backup.sql";

If append the right path to the command and you still cannot get the output then this article can’t help.

2. Make sure you have the rights to create the sql file. This step is mostly for Linux machines where it is very possible that you may try to create a file from php in a folder where you don’t have writing rights.

So to test this after the previous step is done you can do the following: append to the previous command extra options so that the output is not returned but instead written in a file. So we have the previous command:

In Windows:

$command = "\"C:\\Program Files\\MySQL\\MySQL Server 4.1\\bin\\mysqldump.exe\" > backup.sql";

In Linux:

$command = "mysqldump > backup.sql";

After running the file “backup.sql” should  be created.

3.  You must now correct your statement. This means that we must use the long versions of the options like this:

Windows:

$command = "\"C:\\Program Files\\MySQL\\MySQL Server 4.1\\bin\\mysqldump.exe\" --opt --skip-extended-insert --complete-insert --host=".$DB_HOST." --user=".$DB_USER." --password=".$DB_PASS." ".$DB_NAME." > backup.sql";

Linux:

$command = "mysqldump --opt --skip-extended-insert --complete-insert --host=".$DB_HOST." --user=".$DB_USER." --password=".$DB_PASS." ".$DB_NAME." > backup.sql";

The fix: The options for mysqldump when called from php must be in the longer version. Instead of –u use –user, instead of –p use –password and so on.

Categories
PHP

The attachment of an email sent via PHP has 0 bytes

I wanted to send an email that only contained an attachment as follows:

$headers  = "MIME-Version: 1.0\r\n";
$headers .= "To: <".$to_email.">\r\n";
$headers .= "From: ".$from_name." <".$from_email.">";
$random_hash = md5(date('r', time()));
// add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
// read the atachment file contents from a string previously formed,
// encode it with MIME base64,
// and split it into smaller chunks
$attachment = chunk_split(base64_encode($content));
// construct the body of the message
$message = "--PHP-mixed-".$random_hash;
// my attachment was an html file
$message .= "\r\nContent-Type: text/html; name=\"".$filename."\"";
$message .= "\r\nContent-Transfer-Encoding: base64";
$message .= "\r\nContent-Disposition: attachment\r\n".$attachment."\r\n";
$message .= "\r\n--PHP-mixed-".$random_hash."--";
// Windows
ini_set('sendmail_from', $return_email);
mail($to_email, addslashes($subject), $message, $headers);
ini_restore('sendmail_from');
// Linux
// mail($to_email, addslashes($subject), $message, $headers, "-r ".$return_email);

I received an email with an attachment, but the problem was that the attached file had 0 bytes.
To my surprise, after comparing the source of the email with the source of an email with a complete attachment, I found out the problem: before the actual content of the attachment ($attachment) there should be an empty line.
I replaced the line of code:

$message .= "\r\nContent-Disposition: attachment\r\n".$attachment."\r\n";

with:

$message .= "\r\nContent-Disposition: attachment\r\n\r\n".$attachment."\r\n"; // notice the double \r\n

and it worked! This way I received the email with the correct attachment.

Categories
How to MySQL PHP Tutorial

How to use specific language characters with PHP and MySQL (example: Romanian)

Problem: Using specific characters from European languages like Romanian, Bulgarian, Czech and so on (usually the ones without support in ISO 8859-1) rises errors when displaying the content in browsers turning special characters in unrecognizable ones.

My fix for this problem is using UTF-8 character set encoding for every page of the website and the MySQL tables that contain the fields you are using. Also all the html encodings from PHP use the UTF-8 character set encoding (this is not mandatory).

If you already have the database, but with the default character set (latin1) and collation (latin1_swedish_ci) for the tables with text fields (of type CHAR, VARCHAR, TEXT etc) in which you need to have special characters, you should change the character set of each of those tables like this:

ALTER TABLE my_table CONVERT TO CHARACTER SET utf8;

If you don’t have the database then you should create it and when you create a table that you need to use with specific language characters, you should specify the character set for that table:

CREATE TABLE `my_table` (
`idmy_table` tinyint(3) unsigned NOT NULL auto_increment,
`my_field` varchar(255) NOT NULL default '',
PRIMARY KEY  (`idmy_table`)
) CHARSET=utf8;

The most important thing is that in PHP, after opening a database connection, before executing any query to the database, you should ensure that this code is executed

mysql_query("SET NAMES utf8", $my_conn);

This tells the server what character set the client is using for sending SQL statements and the character set the server should use to return the results to the client.

A simple example:

<?php
$my_conn = @mysql_connect("localhost", "user", "pass")
or die("There was a problem connecting to MySQL. Please try again later.");
if(!@mysql_select_db("test", $my_conn))
{
die ("There was a problem connecting to the database. Please try again later.");
}
mysql_query("SET NAMES utf8", $my_conn);
if(!empty($_GET['mystr']))
{
// insert the string into the database
$str = htmlspecialchars($_GET['mystr'], ENT_QUOTES, "UTF-8");
$query = "INSERT INTO my_table_t (my_field) VALUES('".$str."')";
$result = mysql_query($query, $my_conn);
if($result)
{
// save the id of the table row inserted
$last_insert_id = mysql_insert_id($my_conn);
// get the last inserted value
$query = "SELECT my_field FROM my_table_t WHERE idmy_table = '".$last_insert_id."'";
$result = mysql_query($query, $my_conn);
if($result && $row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$db_string = $row['my_field'] ;
}
}
}
elseif(!empty($_GET['searchstr']))
{
$str = htmlspecialchars($_GET['searchstr'], ENT_QUOTES, "UTF-8");
$query = "SELECT * FROM my_table_t WHERE my_field LIKE '%".$str."%'";
$result = mysql_query($query, $my_conn);
if($result)
{
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$search_results[$row['idmy_table']] = $row['my_field'];
}
}
}
mysql_close($my_conn);
?>
<html>
<head>
<title>Page title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<body>
<?php
if(!empty($db_string))
{
echo "<strong>Inserted string</strong>: $db_string<br />";
}
?>
<form method="get" action="">
String to insert into the database <input type="text" name="mystr"/>
<input type="submit" value="GO"/>
</form>
<?php
if(!empty($search_results))
{
echo "<strong>Search results</strong>:<br />";
foreach($search_results as $id => $value)
{
echo $value."<br />";
}
}
?>
<form method="get" action="">
Search query <input type="text" name="searchstr"/>
<input type="submit" value="GO"/>
</form>
</body>
</html>

Tip: The search in Romanian language over the database (tested with MySQL LIKE operator) works like a charm when searching words that have special characters or not.

For example: In Romanian language the word “peasant” is written as “ţăran” and someone who searches it gets the same result for the search terms “taran” or “ţăran” or “ţaran” or “tărân” and so on – so this is the real magic.

UPDATE: You may also need to add a header to the php script if you use ob_start or similar php functions like this:

header("Content-type: text/html; charset=UTF-8");

this usually fixes the encoding selection in Internet Explorer for this case.

Categories
Apache Web Server How to PHP Tutorial

How to receive a failure notice when the recipient cannot be reached after sending an email using the PHP mail() function

I could not receive a failure notice when sending email to an email address that does not exist ($to_address), using this code:

$subject = "Email subject";
$message = "line1\r\nline2\r\nline3";
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "To: <$to_email>\r\n";
$headers .= "From: Me <$my_email_address>\r\n";
$headers .= "Return-Path: <$my_return_email_address>r\n";
mail($to_email, $subject, $message, $headers);

The problem was that the email address I wanted to receive the failure notices to ($my_return_email_address) was not the same as the value of the configuration option sendmail_from in the php.ini file (Apache web server installed on a machine with the Windows Professional operating system). So the failure notices were sent to the sendmail_from email address if this was an existing address, instead of the email address specified in the Return-path header of the email.

The solution is replacing the lines:

$headers .= "Return-Path: <$my_return_email_address>r\n";
mail($to_email, $subject, $message, $headers);

with:

// when the PHP server runs on Windows
ini_set(sendmail_from, $my_return_email_address);
mail($to_email, $subject, $message, $headers);
ini_restore(sendmail_from);
// when the PHP server runs on UNIX
mail($to_email, addslashes($subject), $message, $headers, "-r $my_return_email_address");

This means that, before sending the email, we set the value of the sendmail_from configuration option to $my_return_email_address and we restore the default value of the configuration option after the email is sent.

Categories
PHP

Warning: mail(): SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in path_to_php_file on line #

Full error message: Warning: mail(): SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in path_to_php_file on line #

This is an error message that I got lots of times and it was always the same problem. So I decided to write here the solution for the next time I encounter it and I thought it might also help other people.

So I tried to send an email in plain text using the PHP function mail() :

// consider this being an existing email address
$to_address = "abc@def.com";
$subject = "Email subject";
$message = "line1
line2
line3";
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "To: <".$to_email.">\r\n";
$headers .= "From: Me <".$my_email_address.">\r\n";
mail($to_email, $subject, $message, $headers);

It worked fine with Apache server running on Linux operating system, but I got the error message mentioned before with the server running on Windows.
It looks like while Unix-based systems recognize \n character (the equivalent in PHP of LF – line feed) as a newline even when sending emails, Windows systems are stricter in comunicating using some textual Internet Protocols (such as SMTP) that mandate the line terminator to be the ASCII CR+LF (carriage return + line feed) sequence, which is abstracted in PHP to \r\n character sequence.

So the problem was the $message variable. The correct way to assign the multiple lines value to it is:

$message = "line1\r\nline2\r\nline3";  // separate the lines with \r\n
// or,  elegantly:
$message = "line1\r\n";
$message .= "line2\r\n";
$message .= "line3";

And now it works on Windows, too.