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.

Monday, March 23, 2009

Synchronize MySQL structure

Here is the scenario:

You have a localhost database, that is your development database.
And you have a production database, somewhere on a server.

After you've done some updates on your localhost development mysql database, you want to synchronize with the production database.

You can do that very easy using Navicat for MySQL. Tools -> Data Synchonization. You cand download it, it is fully functional for 30 days, after that you'll have to buy it.

So no more searching for altered tables, new tables, deleted fields, just synchronize your database easy.

Friday, March 20, 2009

First letter uppercase in MySQL

So you have all types of string in a mysql database.

Eg:

MySQL
MYSQL
mysql
MySqL

And you want to make the first letter of each record uppercase and the rest lowercase.
Here is the update syntax for this job:

UPDATE mytable SET myfield=CONCAT(UPPER(SUBSTRING(myfield, 1, 1)), LOWER(SUBSTRING(myfield FROM 2)))

Thursday, March 12, 2009

MySQL implode like function

If you need an implode like function in MySQL, there is a solution: GROUP_CONCAT

GROUP_CONCAT concatenates a string by comma (,).

So if you had a table tags (id, tag)

1 test
2 test2
3 test3

SELECT GROUP_CONCAT(tag) FROM tags

The result would be: test,test2,test3

Pretty cool, huh?

Friday, March 6, 2009

Javascript back button

Create a link or a button to go to the previous page, using this code:
<a href="javascript:history.go(-1)">Back</a>



This way, the visitor can go back to the previous page without pressing the "Back" button of his browser.