PHP Validations


Email Validation:

if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo “E-mail is not valid”;
}

 

Integer Validation:

is_int($var)  or is_integer($var)

Returns true/false

Valid: 2, 4, 10

Invalid: “2”, 2.5

 

Float Validation:

is_float($var)

Returns true/false

Valid: 11.5, 1e4

Invalid: “2.5”, 4, 0

 

Numeric Validation:

is_numeric($var)

Returns true/false

Valid: 40, 1e4, 1550, 9.5

Invalid: “2.5”

 

String Validation:

is_string($var)

Returns true/false

Valid: ‘abc’, “abc”

Invalid: 11.5, 23, true

Advertisements

Joomla Extension Manager warning (PHP temporary directory is not set)


Have you ever seen this warning message in your Joomla Extension Manager

The PHP temporary directory is not set. The PHP temporary directory is the directory that PHP uses to store an uploaded file before Joomla! can access this file. Whilst the directory not being set isn’t always a problem, if you are having issues with manifest files not being detected or uploaded files not being detected, setting this in your php.ini file might fix the issue.”

Okay here is the solution to remove this message

1. Create a php.ini file in the root folder of your Joomla web site
2. Add your temp directory path to it. It will be like this: upload_tmp_dir = /home/youraccontname/public_html/tmp
3. (Optional) Add a line to your .htaccess file so that your site can use the php.ini file. Add this line to .htaccess

SetEnv PHPRC /home/youraccountname/public_html

Thanks,

Jaswant

MySQL – Fetch duplicate records


If your database table having duplicate records and you want to remove all duplicates, this query will help you to find out duplicate records in a table. You can check the records based on any specific field.

SELECT *
FROM mdl_user
WHERE email IN (
	SELECT email
	FROM mdl_user
	GROUP BY email
	HAVING count(email) > 1
	)
ORDER BY email

This query will find all the records in mdl_user table having duplicate emails.

Cheers,
Jaswant

PHP header to prompt file download


Many times I need this function but every time when I try myself I get a new issue, so I thought why not I put it on my blog to help me and other who wanted to prompt a download alert using PHP. I just copied this 😉 from php.net

<?php
function downloadFile($fullPath){

// Must be fresh start
if( headers_sent() )
die(‘Headers Sent’);

// Required for some browsers
if(ini_get(‘zlib.output_compression’))
ini_set(‘zlib.output_compression’, ‘Off’);

// File Exists?
if( file_exists($fullPath) ){

// Parse Info / Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts[“extension”]);

// Determine Content Type
switch ($ext) {
case “pdf”: $ctype=”application/pdf”; break;
case “exe”: $ctype=”application/octet-stream”; break;
case “zip”: $ctype=”application/zip”; break;
case “doc”: $ctype=”application/msword”; break;
case “xls”: $ctype=”application/vnd.ms-excel”; break;
case “ppt”: $ctype=”application/vnd.ms-powerpoint”; break;
case “gif”: $ctype=”image/gif”; break;
case “png”: $ctype=”image/png”; break;
case “jpeg”:
case “jpg”: $ctype=”image/jpg”; break;
default: $ctype=”application/force-download”;
}

header(“Pragma: public”); // required
header(“Expires: 0”);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Cache-Control: private”,false); // required for certain browsers
header(“Content-Type: $ctype”);
header(“Content-Disposition: attachment; filename=\””.basename($fullPath).”\”;” );
header(“Content-Transfer-Encoding: binary”);
header(“Content-Length: “.$fsize);
ob_clean();
flush();
readfile( $fullPath );

} else
die(‘File Not Found’);

}
?>

Javascript Select All Checkboxes


Ok so last week I was trying to implement Check ALL / Unckeck ALL functionality. The form was having a root checkbox and by selecting this checkbox all the checkboxes on form should also be selected. Same for uncheck all should be unchecked.

There are many code snippets available but the problem was I was submitting this form to a PHP script and to process the checked entires PHP needs an array. So the checkboxes name should be something like chktopic[],

<input type="checkbox" name="chktopic[]” value=”topic_1″ />
<input type="checkbox" name="chktopic[]” value=”topic_2″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_3″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_4″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_5″ />

and then in PHP script you can use it like

$topics = $_POST[“chktopic”];
$totaltopics = count($topics);
for ($i=0; $i<$totaltopics; $i++) {
$status = deleteTopic($topics[$i]);
}

You can see I am trying to Delete all the selected topics. That was the PHP part but how about JavaScript how we will implement check all / uncheck all. So initially I tried with is function

My root checkbox

<input type=”checkbox” name=”all” title=”Select All” onClick=”checkAll(document.form_topics.chktopic,this)”>

and the JS function was

function checkAll(checkname, root) {
for (i = 0; i < checkname.length; i++)
checkname[i].checked = root.checked? true:false
}

But this function was not working as you can see the name is having [] (an array), if you use a single name (like name=”chktopic”) for all checkboxes this function will work smoothly but then PHP will refuse, as PHP needs an array.

So to handle this situation we will use the same JavaScript function but on root checkboxes we will do a tweak

<input type=”checkbox” name=”all” title=”Select All” onClick=”checkAll(document.form_topics[‘chktopic[]’],this)”>

Simple right 🙂

Cheers..

Install Apache and MySQL as a Service


Ok so you have successfully configured apache and MySQL on your windows machine, I know that Apache and MySQL automatically configure their services to auto start but in case if you cant see both or one of them into Microsoft -> Administrative Tools -> Services, and you want to configure so that both can start automatically on system startup.

So to install or configure a new service you will need command prompt (windows\system32\cmd.exe) go to this directory right click on cmd.exe and click on Run as Administrator (otherwise windows will not allow you to add a service)

Install Apache as a service

First go to apache\bin directory

D:\>cd apache\bin
D:\apache\bin> httpd -k install -n “ApacheServiceName”

Install MySQL as a service

Again this time go to MySQL bin directory

D:\>cd mysql\bin
D:\mysql\bin> mysqld –install

Now when you go to Administrative Tools-> Services you can see both the service are there you can right click on that and set properties->Startup type as automatic

To remove the services, type these commands

D:\>cd apache\bin
D:\apache\bin> httpd -k uninstall -n “ApacheServiceName”

D:\>cd mysql\bin
D:\mysql\bin> mysqld –remove

Drupal CSS optimization failed


My colleague Gaurav he is Drupal expert, is working on a Drupal project. He has almost completed the project so now the time was to switch the project from development to production environment. In the development environment we have Windows Xp, Apache2.2.17, PHP 5.2 and MySQL 5.0.7 and on production environment we have the same PHP, the same Apache, the same MySQL and Windows 2003.

I helped him during server configuration and deployment, everything deployed successfully we were able to see the site. But when he turned on the CSS and JS optimization from admin->performance setting in drupal.

Browser was going nowhere we were just getting the message “Page can not be displayed”. Why we don’t know, because there was no any apache error log, no any php error log. Finally we came to know that CSS optimization is creating an issue, the reason was drupal optimizer was not able to create CSS cache file in sites/default/files/css folder. Whereas JS cache was created in sites/default/files/js folder.

Then we again disabled the CSS optimization, (just only CSS optimization because JS optimization was working very well), now we tried to access the site this time it rendered properly, but only with firefox. Not with IE, this time the reason was clear, because IE only allows 31 CSS request at a time and we were having 34 CSS. We could reduce the CSS requests by disabling few unused modules but it was not a solution to our problem.

Everything was okay but without solving this issue we would not be able to say that everything is working very well. We spent almost two days to find out the reason and solution. Finally I found a solution on Drupal issues page. I found that this is not a strange issue many drupal expert has already faced this. Here is the link to the post

http://drupal.org/node/444228

Somebody has posted a patch for common.inc file which basically does the optimization work, here is the patch

http://drupal.org/node/444228#comment-2095622

So open common.inc file find this code and replace it (offcourse to play safely, first do a backup)


if ($_optimize) {
// Perform some safe CSS optimizations.
$contents = preg_replace('< - \s*([@{}:;,]|\)\s|\s\()\s* | # Remove whitespace around separators, but keep space around parentheses. /\*[^*\\\\]*\*+([^/*][^*]*\*+)*/ | # Remove comments that are not CSS hacks. [\n\r] # Remove line breaks. >x', '\1', $contents);
}

I hope this will help you guys if you work someday on Drupal and face the same issue 🙂 which is very rare.

Cheers,
Jaswant