The site is currently not available due to technical problems

Site off-line

The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.

If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider’s database server is running. For more help, see the handbook, or contact your hosting provider.

There are two things you need to check.

1. Is mysqli is installed or not?

2. Is server able to connect database?

Is mysqli installed or not:

Check info.php file is mysqli is listed in this page, if not then your server will support only mysql not mysqli. If your host doesn’t have mysqli installed, you can it change to use mysql. (MySQLi stands for MySQL Improved.)

Open settings.php change $db_url from mysqli to mysql (settings usually in /sites/default-folder in your drupal installation).

BEFORE:
$db_url = ‘mysqli://user:password@hostname/table’;

AFTER
$db_url = ‘mysql://user:password@hostname/table’;
This means that you can either install MySQLi with your PHP install OR you can simply make the changes to your settings.php file as detailed above.

 Is server able to connect database?

Check whether you have passed right username, password and database name and also check whether you have given full permission to access the database from the server.

Hope this will be useful for those having similar problems.

Major difference between include and require

You people know very well there are 4 ways to include a file in PHP.

1. include().

2. include_once();

3. require().

4. require_once().

Because of four existence, sometimes beginners gets confuse which right one to use in their code. So in this post, i am going to give you a simple explanation of these four.

include() – This function is used to include a file in the current page and it take single argument. You can specify the file path either relative or absolute path. If the specified path is not found, then it will throw Warning message but still the application continues to run…This is good for production environment.

include_once() – This is similar to include() but only difference is it will include the file only once in the page. For example, you have an loop which contains common code to use in different places, and you put that common code in a separate file. So in this case include_once() will include the code only once even its running in the loop.

require() – This function will include a file in the current page and it take single argument. And this is also similar to include but it will throw fatal error if the specified file path is not found and the application will stops running further.

require_once() – This function will do action of require() and include_once(). So it will include only once and throw fatal error if the file is not found.

In common, there is a big difference between include and require, the include will run the file directly whereas require it will check the entire code in the file and then only it will execute. So require() will be slow when compare to include(). And most developers, will recommend to use require, because it will throw error even if it is there simple or small mistake in your code.

Hope i have explained to you people somewhat clearly….

 

Author: Vinodkumar Saravana

 

5 ways to write horribly ugly php code

Editors note:Yes, this post is just a little joke. Sometimes us developers just need to vent a little bit. Please don’t actually follow the advice in this post, kittens will die if you do.

Writing quality code these days is over rated. Why learn how to write proper php and coding when you can pick up a few tutorials online and start churning out security prone vomit code? Don’t let the professional developers fool you, the only reason they don’t write crappy code is because they have nothing better to do with their time! You have places to be don’t you? So why the hell would you spend so much time learning how to properly use php‽ It’s insane!

1. Don’t worry about errors, supress them!
Headers already sent? Screw you computer! I’ll tell you about my headers and errors! Instead of turning on error reporting while in development, just turn it off completely. This way you probably won’t have to worry about any annoying errors or things of that nature. If you do happen to get one of those annoying errors, simple supress is with the @ suppressor. Stick that in front of every function call and your code should have no errors at all!

If you still can’t figure out why you are getting errors, try rearranging the order of your code, putting things and function calls into different conditional statements. Don’t worry about any of the logic getting screwed up, someone else can fix that.

2. Use indecipherable variable and function names
Why spend and waste extra time making up and writing function and variable names when you can get right to the point? It’s not like anyone but you will ever read your code, and hell, you will surely remember!

Instead of something like this:

<?php
$user_name = try_user_login();//generic function call
?>

Try something like this:

<?
$a = z();//generic function call
?>

Notice that we also saved some space by using short tags! Hell yea! Which brings me to my next point…

3. Use server specific settings
Always user short tags when writing with php. It doesn’t matter if it might not work on some poor souls server without changing some configuration file, they’re too dumb to know that short tags are teh best! Also be sure to never use the php echo function, instead use the short echo tags like so:

<?=$narwhalBaconsMidnight; ?>

4.Don’t comment anything!
Why waste time explaining why a certain class or method does what it does? Hell, we don’t even care what a class is! Save your time by not commenting anything, if someone else can’t figure out what you were trying to do, it’s not your fault, they’re just ignorant.

5. Drop those curly brackets!
Stop wasting so much space and so many lines when your writing php. Technically, the curly braces aren’t required for control structures, so there must not even be any point to them! Get rid of them now!

<?php
if($bacon === true)
    $vegan = false;
    generic_function_call();//May or may not get called, it's more fun that way!
?>

Follow these steps and you are on your way to losing your job and becoming an art major. Best of luck!

Author: Drew Douglass

How to load data using JSON/PHP using jQuery

I have seen a good amount of people wanting to lern how to load data on their website using jquery,JSON and PHP. I have been studying parsing JSON from PHP using AJAX to display it in the client side and jQuery had been a great help to me. Here is a very simple code in parsing JSON using jQuery that i made.

tablejsondata.php
This file makes the request to a php file and displays the returned data into a table.

<a href="#" id="loaduserdata">User Data</a>
<table id="userdata" border="1">
 <thead>
 <th>First Name</th>
 <th>Last Name</th>
 <th>Email Address</th>
 <th>City</th>
 </thead>
 <tbody></tbody>
</table>
<script>
$(document).ready(function(){
});
$("#loaduserdata").click(function(){
 $("#userdata tbody").html("");
 $.getJSON(
 "jsondata.php",
 function(data){
 $.each(data.userdata, function(i,user){
 var tblRow =
 "<tr>"
 +"<td>"+user.first+"</td>"
 +"<td>"+user.last+"</td>"
 +"<td>"+user.email+"</td>"
 +"<td>"+user.city+"</td>"
 +"</tr>"
 $(tblRow).appendTo("#userdata tbody");
 });
 }
 );
});
</script>

jsondata.php
This is the file that contains the JSON data.
<?php
$json = '{
"userdata": [
 {
 "first":"Ciaran",
 "last":"Huber",
 "email":"elementum.purus@utdolordapibus.edu",
 "city":"Mayagüez"
 },
 {
 "first":"Lester",
 "last":"Watkins",
 "email":"orci.sem.eget@quamvelsapien.edu",
 "city":"Laguna Beach"
 },
 {
 "first":"Mannix",
 "last":"Gilmore",
 "email":"sed.sem.egestas@AliquamnislNulla.com",
 "city":"Minot"
 },
 {
 "first":"Nathaniel",
 "last":"Holland",
 "email":"a.odio@Donecnibh.org",
 "city":"San Angelo"
 },
 {
 "first":"Wylie",
 "last":"Drake",
 "email":"lobortis.nisi.nibh@Integer.edu",
 "city":"Roseville"
 },
 {
 "first":"Salvador",
 "last":"Alford",
 "email":"fringilla@adipiscing.edu",
 "city":"Vacaville"
 },
 {
 "first":"Kiara",
 "last":"Barton",
 "email":"fringilla.est.Mauris@utpellentesqueeget.ca",
 "city":"Johnson City"
 },
 {
 "first":"Moses",
 "last":"Miller",
 "email":"per.inceptos@aliquam.edu",
 "city":"Boulder Junction"
 },
 {
 "first":"Hillary",
 "last":"Serrano",
 "email":"elit.pretium.et@scelerisquesedsapien.com",
 "city":"Martinsburg"
 }
]
}';
echo $json;
?>

References and Guides:

http://docs.jquery.com/GetJSON

http://www.json.org/js.html
Download the latest jquery file.
Author: Jhoy Imperial

Very useful PHP code snippets for PHP developers

php-logoFollowing are list of  most useful PHP code snippets that a PHP developer will need at any point in his career. Few of the snippets are shared from my projects and few are taken from useful php websites from internet. You may also want to comment on any of the code or also you can share your code snippet through comment section if you think it may be useful for others.

1. Send Mail using mail function in PHP

$to = "viralpatel.net@gmail.com";
$subject = "VIRALPATEL.net";
$body = "Body of your message here you can use HTML too. e.g. <br>
         <b> Bold </b>";
$headers = "From: Peter\r\n";
$headers .= "Reply-To: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.com\r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$body,$headers);
?>

2. Base64 Encode and Decode String in PHP

function base64url_encode($plainText) {
	$base64 = base64_encode($plainText);
	$base64url = strtr($base64, '+/=', '-_,');
	return $base64url;
}

function base64url_decode($plainText) {
	$base64url = strtr($plainText, '-_,', '+/=');
	$base64 = base64_decode($base64url);
	return $base64;
}

3. Get Remote IP Address in PHP

function getRemoteIPAddress() {
	$ip = $_SERVER['REMOTE_ADDR'];
	return $ip;
}

The above code will not work in case your client is behind proxy server.

In that case use below function to get real IP address of client.

function getRealIPAddr()
{
	if (!empty($_SERVER['HTTP_CLIENT_IP']))
	{
		$ip=$_SERVER['HTTP_CLIENT_IP'];
	}
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
	{
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	else
	{
		$ip=$_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}

4. Seconds to String

This function will return the duration of the given time period in days, hours, minutes and seconds.

e.g. secsToStr(1234567) would return “14 days, 6 hours, 56 minutes, 7 seconds”

function secsToStr($secs) {
	if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
	if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
	if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
	$r.=$secs.' second';if($secs<>1){$r.='s';}
	return $r;
}

5. Email validation snippet in PHP

$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&amp;amp;amp;amp;amp;'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
	echo 'This is a valid email.';
} else{
	echo 'This is an invalid email.';
}

6. Parsing XML in easy way using PHP

Required Extension: SimpleXML

//this is a sample xml string
$xml_string="<?xml version='1.0'?>
<moleculedb>
    <molecule name='Benzine'>

        <symbol>ben</symbol>
        <code>A</code>
    </molecule>
    <molecule name='Water'>

        <symbol>h2o</symbol>
        <code>K</code>
    </molecule>
</moleculedb>";

//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);

//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
   //attribute are accessted by
   echo $record['name'], '  ';
   //node are accessted by -> operator
   echo $record->symbol, '  ';
   echo $record->code, '<br />';
}

7. Database Connection in PHP

<?php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost";        //Location Of Database usually its localhost
$dbUser = "xxxx";            //Database User Name
$dbPass = "xxxx";            //Database Password
$dbDatabase = "xxxx";       //Database Name

$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");

# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
function send_404()
{
    header('HTTP/1.x 404 Not Found');
    print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n".
    '<html><head>'."n".
    '<title>404 Not Found</title>'."n".
    '</head><body>'."n".
    '<h1>Not Found</h1>'."n".
    '<p>The requested URL '.
    str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
    ' was not found on this server.</p>'."n".
    '</body></html>'."n";
    exit;
}

# In any file you want to connect to the database,
# and in this case we will name this file db.php
# just add this line of php code (without the pound sign):
# include"db.php";
?>

8. Creating and Parsing JSON data in PHP

Following is the PHP code to create the JSON data format of above example using array of PHP.

$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
echo json_encode($json_data);

Following code will parse the JSON data into PHP arrays.

$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
$obj=json_decode($json_string);
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google

9. Process MySQL Timestamp in PHP

$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records))
{
	echo $row;
}

10. Generate An Authentication Code in PHP

This basic snippet will create a random authentication code, or just a random string.

<?php
# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
    $pos = rand(0,36);
    $str .= $string{$pos};
}
echo $str;
# If you have a database you can save the string in
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify
?>

11. Date format validation in PHP

Validate a date in “YYYY-MM-DD” format.

function checkDateFormat($date)
{
	//match the format of the date
	if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
	{
		//check weather the date is valid of not
		if(checkdate($parts[2],$parts[3],$parts[1]))
			return true;
		else
		return false;
	}
	else
		return false;
}

12. HTTP Redirection in PHP

<?php
	if (!empty($_SERVER['HTTPS']) &amp;amp;amp;amp;&amp;amp;amp;amp; ('on' == $_SERVER['HTTPS'])) {
		$uri = 'https://'; / what?
	} else {
		$uri = 'http://'; / what?
	}
	$uri .= $_SERVER['HTTP_HOST'];
	header('Location: 'http://you_stuff/url.php'); // stick your url here
	exit;
?>

13. Directory Listing in PHP

<?php

function list_files($dir)
{
	if(is_dir($dir))
  	{
  		if($handle = opendir($dir))
  		{
  			while(($file = readdir($handle)) !== false)
  			{
  				if($file != "." &amp;amp;amp;amp;&amp;amp;amp;amp; $file != ".." &amp;amp;amp;amp;&amp;amp;amp;amp; $file != "Thumbs.db"/*pesky windows, images..*/)
  				{
  					echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
  				}
  			}
  			closedir($handle);
  		}
	}
}

/*
To use:

<?php
	list_files("images/");
?>
*/
?>

14. Browser Detection script in PHP

<?php
	$useragent = $_SERVER ['HTTP_USER_AGENT'];
	echo "<b>Your User Agent is</b>: " . $useragent;
?>

15. Unzip a Zip File

<?php
    function unzip($location,$newLocation){
        if(exec("unzip $location",$arr)){
            mkdir($newLocation);
            for($i = 1;$i< count($arr);$i++){
                $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
                copy($location.'/'.$file,$newLocation.'/'.$file);
                unlink($location.'/'.$file);
            }
            return TRUE;
        }else{
            return FALSE;
        }
    }
?>

//Use the code as following:
<?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
    echo 'Success!';
else
    echo 'Error';
?>

16. Email address check

Checks for a valid email address using the php-email-address-validation class.

Source and docs: http://code.google.com/p/php-email-address-validation/

include('EmailAddressValidator.php');
 
$validator = new EmailAddressValidator;
if ($validator->check_email_address('test@example.org')) {
    // Email address is technically valid
}
else {
    // Email not valid
}

?>

17. Random password generator

PHP password generator is a complete, working random password generation function for PHP. 

It allows the developer to customize the password: 

set its length and strength. Just include this function anywhere in your code and then use it.

Source : http://www.webtoolkit.info/php-random-password-generator.html

function generatePassword($length=9, $strength=0) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength & 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength & 2) {
        $vowels .= "AEUY";
    }
    if ($strength & 4) {
        $consonants .= '23456789';
    }
    if ($strength & 8) {
        $consonants .= '@#$%';
    }
 
    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}


?>

18. Force downloading of a file

Forces a user to download a file, for e.g you have an image 

but you want the user to download it instead of displaying it in his browser.

header("Content-type: application/octet-stream");
 
// displays progress bar when downloading (credits to Felix ;-))
header("Content-Length: " . filesize('myImage.jpg'));
 
// file name of download file
header('Content-Disposition: attachment; filename="myImage.jpg"');
 
// reads the file on the server
readfile('myImage.jpg');


?>

How you like this small collection of PHP code snippets. You may want to paste your code snippet in the comment section below and share it with others. :)

« Older entries