Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday, March 4, 2010

PHP log errors to log file

Logging PHP errors to a log file is critical. You don't want to display PHP errors or warnings to users, but to log all errors to a file that you can view. This way you can fix all errors, warnings, notices and the client won't see any PHP error.

You can easily do this by adding two lines at the beginning of your code:

ini_set('log_errors', 1);
ini_set('error_log', '/path-to/error_log.file');

You can use later any editor to view contents of your log file and fix all problems that occured.

Wednesday, February 10, 2010

PHP date/time difference

I have found a great function that returns the difference in days, hours and minutes between 2 dates.

Here is the link, works like a charm:

http://www.gidnetwork.com/b-16.html

For example, this function can be used for events, to know how much time is left until the next event.

Tuesday, August 25, 2009

File_Get_Contents replacement (CURL)

Some servers have file_get_contents function disabled. But don't worry, most of them have curl library installed. Here is a replacement function for file_get_contents, using CURL library. Easy and working:

  1. function file_get_contents_curl($url) {
  2. $ch = curl_init();
  3. curl_setopt($ch, CURLOPT_HEADER, 0);
  4. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  5. curl_setopt($ch, CURLOPT_URL, $url);
  6. $data = curl_exec($ch);
  7. curl_close($ch);
  8. return $data;
  9. }



Using this function is easy, just like file_get_contents function :

$contents = file_get_contents_curl( 'http://...');

Tuesday, August 4, 2009

PHPMailer UTF-8 messages

Sending UTF-8 body messages with PHPMailer is pretty easy. You just have to set charset

Here is an example: $mail->CharSet = 'UTF-8';

So now you can send utf-8 mail messages using PHPMailer. Good luck.

Wednesday, June 24, 2009

How to validate a hex color in PHP

Validating a hex color code in PHP is easy.

Rules:

Hex colors must start with '#' and have 6 characters.
Hex colors can contain the following letters: [A-F]
Hex colors can contain the following digits: [0-9]

So using pregmatch, the hex validation code is:

if(preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid
{

}

Tuesday, June 23, 2009

PHP Upload and Image Manipulation Class

I've been looking for a simple to use class for uploading and manipulating images. And I have found it.

Here it is: http://www.verot.net/php_class_upload_overview.htm

You can upload files, validate mime types, set language for errors. It's really easy to use. It's free for non-commercial applications.

You can now easily upload and manipulate images (resize, watermark, etc) with this PHP class.

Sunday, May 10, 2009

PHP 301 redirect

301 redirect means "moved permanently"

Every website has to have SEO onpage. That means sometimes you need 301 redirects, when you want to replace some url with a new url. How do you get 301 redirect in PHP? Using header function.

Here is a simple example:

header ('HTTP/1.1 301 Moved Permanently');
header ('Location: '.$new_location);
exit();

This code must be used in the old file, that you want to remove from search engines. $new_location is the new path where the script is being redirected. exit() must be used to stop the script.
Remember to not display anything (any HTML or other text sent to browser) before calling header() function. Or if you do, you can use output buffering to clear the output.

Monday, May 4, 2009

PHP include path

How to set include path



Include path separator differs from one operating system to another. For Windows path separator is ; and for unix separator is :. So how do you make your code create the right include path regardless of your OS?

First, you detect server's OS:

if (stristr(PHP_OS, 'WIN'))
{
$separator = ';';
}
else {
$separator = ':';
}

Then you set your classes path, for example:
$yourpath = './classes';

And then you add this path to include path:

ini_set('include_path', ini_get('include_path') . $separator . $yourpath);

This way, either your server is Windows or a Unix system, it will always include your path using the right separator character, and you don't have to change the code everytime you switch to another OS.

Thursday, April 23, 2009

Get file extension in PHP

Here are some simple ways to retrieve extension of a file using PHP. You need this when you try to validate file uploads, for example.

So here is one simple way:

$extension = end(explode(".", $filename ));

Let's say we have: $filename = 'text.jpg' then the result will be jpg.

Another way of getting file extension is using pathinfo() function:
$fileinfo = pathinfo($filename);
$extension = $fileinfo['extension'];

And the third way:
$extension = substr(strrchr($filename,'.'),1);

I use the first method, works just fine. You can use what method you want to determine a file extension.

Thursday, April 9, 2009

Jquery ajax post form

How to post some data using jquery and ajax, and get the response in a div.

First you'll need jquery library.

Then you'll need a html form:


<script type="text/javascript" src="jquery.js></script>
<script type="text/javascript">

$(document).ready(function() {

$("#btn").click(function(){

$.post("ajax.php",{
myfield: $("#myfield").val(),
action: "check"
}, function(msg) {
$("#msg").empty();
$("#msg").html(msg);
});

});

});

</script>

<form action="" method="post">
<input type="text" name="myfield" id="myfield" />
<input type="button" name="btn" id="btn" value="Submit" />
</form>

<div id="msg"></div>

This file it's called index.html


And then the file ajax.php, will take the parameters sent through ajax, and echo the response:

$myfield = $_POST['myfield'];
echo $myfield;

This line returns the value in #msg div.

So there you go, ajax with jquery is pretty simple, you can see here how to send parameters through ajax, and how to get the response into a div. This code can be used to validate user input, emails, number, etc. Instead of $myfield you can echo an error message, or a success message, your choice.

Looking for a PHP or MySQL article?

If you are looking for an article that is not on this site, or looking for a solution regarding PHP or MySQL problem, please comment this post and I'll do my best to give you solutions to your problems as soon as possible.

I am writing these PHP articles and tutorials to help you become a better web developer. All my articles are short and with code examples.

So if you have a "How to...?" question and you need my help (for free :) ) please post it in comments area.

Also if you need a professional web developer, I am available for freelance, providing quality code, security, database optimization, fast websites

Tuesday, April 7, 2009

PHP strip everything but numbers

Stripping non digits in PHP is easy and smooth.

Here is the code:

$digits = eregi_replace('[^[:digit:]]', '', $string );

So having a $string = 'ab345dc-.';

The result would be: $digits = 345;

Using eregi_replace all the non digits charactes will be removed. Filter out everything but numbers using this code.

PHP format days, month in your language

How do you display day and month from a date in your language (other than English)

Eg: 14/03/2009 in English would be: Saturday 14 March 2009. So how do you get "Saturday" and "March" in your language. Easy. Using setlocale function.

Here is a simple example, displaying day and month in Romanian language:

setlocale(LC_ALL, 'ro-RO');
echo iconv('ISO-8859-1', 'UTF-8',strftime("%A, %d %B %Y",strtotime('2009/03/14')));

so strftime is using setlocale to display date and time. inconv function is converting all the weird characters from to UTF-8 so they are displayed properly.

So now you can easily display dates (days and months) in your native language if is other than English, just setlocale to your language and display through strftime.

Wednesday, April 1, 2009

How to parse a PHP file and get contents

file_get_contents function only gets a file contents, but it does not parse it. So if you are interested in parsing a file, and the get its contents, here is the way:

ob_start();
include($filename);
$return_str = ob_get_contents();
ob_end_clean();

So using output buffering, we will include the file, and then get the output result in a variable.

Wednesday, March 25, 2009

PHP get number of lines in a text file

Counting number of lines in a text file is easy.

Here is the code:

$file = "file.txt";
$nr_lines = count(file($file));

Now you know how to count the number of lines in a text file with PHP.

Friday, December 7, 2007

PHP force file download

How to force file download in PHP



Here is how you can force a client to download a file.

$text = 'force me to download';

header("Content-Length: " . strlen($text) );
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename=downloadme.txt');

This will force browser to download/save the file named 'downloadme.txt'

You you want to download other types of files here is a small list of types of files that you can use in Content-Type field:

  • "pdf": "application/pdf"
  • "exe": "application/octet-stream"
  • "zip": "application/zip"
  • "xls": "application/vnd.ms-excel"
  • "ppt": "application/vnd.ms-powerpoint"
  • "gif": "image/gif"
  • "png": "image/png"
  • "jpg": "image/jpg"


Friday, November 16, 2007

Smarty format date

How to format date in Smarty



When you extract a date field from database, it is in the format yyyy-mm-dd. But maybe you want to list it other format, for example dd-mm-yyyy. You can retrieve this format directly from database, usign MySQL function DATE_FORMAT, or if you are using Smarty you can use date_format function.

Here is an example of Smarty date formatting:

{$smarty.now|date_format:"%d:%m:%Y"}

This will format current time, in dd-mm-yyyy format.
You can find all date conversions on smarty website.


Formatting dates using Smarty

Tuesday, November 13, 2007

Disabling magic quotes in PHP

How to disable magic quotes




You cannot disable magic quotes from .htaccess or php.ini, only from apache httpd.conf file.

You can use PHP to disable magic quotes at runtime. Here is the function:

if (get_magic_quotes_gpc()) {
function
stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);

return
$value;
}

$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}

This function will strip slashes for all REQUEST values. If you make SQL queries with these values, you have to use mysql_real_escape_string function in order to prevent sql injection.


Disabling magic quotes, using Apache and PHP

Thursday, November 8, 2007

Form Validation with PHP

Validating forms in PHP


Using validation class from PEAR http://pear.php.net/package/Validate, it's very easy to validate forms. Forms validation is neede in order to protect your website from xss injection, sql injection, email injection. For example if you are expecting an email address in a field, you should validate that field for an email address.

This class validation from PEAR has the following validation methods:
  • number
  • email
  • date
  • string
  • and more
All you have to do is download this validation class from PEAR, and you now can have a safe website by validationg user input. Open downloaded class, and you will see all the methods, with all the parameters required for each validation method.

How to validate form submission in PHP

Tuesday, November 6, 2007

How to check if a text exists in a string

How to check if a substring exists in a string in PHP



Having a string:

$mystring = 'teststringforme';

I want to know if, for example, 'for' exists in $mystring. Using PHP function strpos, it's very easy.

if( strpos( $mystring, 'for' ) !== false )
{
echo 'string exists';
}
else
{
echo 'string does not exist';
}


Find if a text exists in a string using PHP