Posts Tagged ‘PHP’

FTP clean-up script – PHP (delete old files on server)

2 Comments »

One of my blog user “Chris” asked for FTP clean up script, so here it is:

01//CONFIG SECTION
02//*******************************************************
03// Credentials for FTP Server
04$source_server_ip = "your_domain_or_IP"; // Server IP or domain name eg: 212.122.3.77 or ftp.domain.tld
05// Credentials for FTP account
06$ftphost = "ip_or_hostname_of_ftp"; // FTP host IP or domain name
07$ftpacct = "userid"; // FTP account
08$ftppass = "password"; // FTP password
09$logs_dir = "/"; //FTP Remote Folder
10$email_notify = 'your_email@domain.com'; // Email address for backup notification
11$backupexpireindays=21; //3 weeks expire time in days, 21 days = 7*24*60
12//END OF CONFIG SECTION
13//*******************************************************
14 
15 
16//Do not edit below this line
17$backupexpireindays=($backupexpireindays*24)*3600; //convert it to seconds, 24 hours * 60 minutes * 60 seconds
18 
19// Delete any other backup with filetime greater than expire time, before create new backup
20$conn_id = ftp_connect($ftphost);
21$login_result = ftp_login($conn_id, $ftpacct, $ftppass);
22 
23ftp_chdir($conn_id, $logs_dir);
24$files = ftp_nlist($conn_id, ".");
25foreach ($files as $filename) {
26        $fileCreationTime = ftp_mdtm($conn_id, $filename);
27        //$date = date("F j, Y, g:i a", ftp_mdtm($conn_id, $filename));
28        //print "<br>Timestamp of '$filename': $date";
29        $fileAge=time();
30        $fileAge=$fileAge-$fileCreationTime;
31        if ($fileAge > $backupexpireindays) { // Is the file older than the given time span?
32               //echo "<br>The file $filename is older than Expire time :$expiretime ...Deleting\n";
33               ftp_delete($conn_id, $filename);
34               //echo "<br>Deleted<br><br>";
35               }
36}
37 
38ftp_close($conn_id);
39  
40print "Remote FTP clean up Finish deleted files older than $backupexpireindays days";
41?>

Enjoy !


CPanel full backup (all files+databases+emails) PHP script

23 Comments »

 

I was looking for a working script to take full backup (all files+databases+emails) manually or using cron services on my hosting server, each CPanel user by one. But most of the scripts are either old, totally unusable or commercial.
So I wrote one for my own use and sharing here so others don’t need to re-invent the wheel

01<!--?php
02// Must include cPanel API
03include "xmlapi.php";
04  
05//CONFIG SECTION
06//*******************************************************
07// Credentials for cPanel account
08$source_server_ip = "your_domain_or_IP"; // Server IP or domain name eg: 212.122.3.77 or cpanel.domain.tld
09$cpanel_account = "userid"; // cPanel username
10$cpanel_password = "password"; // cPanel password
11// Credentials for FTP remote site
12$ftphost = "ip_or_hostname_of_ftp"; // FTP host IP or domain name
13$ftpacct = "userid"; // FTP account
14$ftppass = "password"; // FTP password
15$logs_dir = "/"; //FTP Remote Folder
16$email_notify = 'your_email@domain.com'; // Email address for backup notification
17$backupexpireindays=21; //3 weeks expire time in days, 21 days = 7*24*60
18//END OF CONFIG SECTION
19//*******************************************************
20//Do not edit below this line
21 
22$backupexpireindays=($backupexpireindays*24)*3600; //convert it to seconds, 24 hours * 60 minutes * 60 seconds
23 
24$xmlapi = new xmlapi($source_server_ip);
25$xmlapi--->password_auth($cpanel_account,$cpanel_password);
26$xmlapi->set_port('2083');
27  
28// Delete any other backup with filetime greater than expire time, before create new backup
29$conn_id = ftp_connect($ftphost);
30$login_result = ftp_login($conn_id, $ftpacct, $ftppass);
31 
32ftp_chdir($conn_id, $logs_dir);
33$files = ftp_nlist($conn_id, ".");
34foreach ($files as $filename) {
35        $fileCreationTime = ftp_mdtm($conn_id, $filename);
36        //$date = date("F j, Y, g:i a", ftp_mdtm($conn_id, $filename));
37        //print "<br>Timestamp of '$filename': $date";
38        $fileAge=time();
39        $fileAge=$fileAge-$fileCreationTime;
40        if ($fileAge > $backupexpireindays) { // Is the file older than the given time span?
41               //echo "<br>The file $filename is older than Expire time :$expiretime ...Deleting\n";
42               ftp_delete($conn_id, $filename);
43               //echo "<br>Deleted<br><br>";
44               }
45}
46 
47ftp_close($conn_id);
48  
49$api_args = array(
50                           'passiveftp',
51                           $ftphost,
52                           $ftpacct,
53                           $ftppass,
54                           $email_notify,
55                            21,
56                            '/'
57                         );
58  
59$xmlapi->set_output('json');
60print $xmlapi->api1_query($cpanel_account,'Fileman','fullbackup',$api_args);
61  
62?>

You need to save it with .php extension (upload it to your server) and download include file from xmlapi.zip(right click->save as) and extract it to the same folder (on your web server). Create cron job from your CPanel or trigger it manually to get full backup in your FTP server, That’s it.
OR
You can fork from my git hub Repositories at cpanel-Fullbackup
Enjoy


Update PHP 5.1 to PHP 5.3 in CentOS

1 Comment »

 

Updating PHP in CentOS to latest PHP 5.3 or PHP 5.4 is not an easy task so I am writing this post. I had to do this for a project in which I need to install latest Zend Loader with PHP 5.3 support. Read the rest of this entry »


Syntax Highlighter

1 Comment »

SyntaxHighlighter:

SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript.


PHP Validations

1 Comment »

Validate Email

We can perform an email validation through this function.

1function isValidEmail($email){
2    return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email);
3}

After fainted for a few seconds when i saw unreal4u finding, i decided to throw up preg_match solution instead.

1function isValidEmail($email){
2    return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $email);
3}

PHP 5.2 and above.

1function fnValidateEmail($email)
2{
3  return filter_var($email, FILTER_VALIDATE_EMAIL);
4}

Sanitize Email

We can further sanitize our email to ensure that everything is alright.

1function fnSanitizeEmaill($string) {
2     return  preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
3}

PHP 5.2 and above.

1function fnSanitizeEmaill($url)
2{
3  return filter_var($url, FILTER_SANITIZE_EMAIL);
4}

Validate Email Exist

This is not possible but certain validation can be use to validate email existence.

01function check_email($email)
02{
03    $email_error = false;
04    $Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
05    if ($Email == '') { email_error = true; }
06    elseif (!eregi('^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+', $Email)) { email_error = true; }
07    else {
08    list($Email, $domain) = split('@', $Email, 2);
09        if (! checkdnsrr($domain, 'MX')) { email_error = true; }
10        else {
11        $array = array($Email, $domain);
12        $Email = implode('@', $array);
13        }
14    }
15 
16    if (email_error) { return false; } else{return true;}
17}

Validate Number Only

We can use PHP built-in function to validate whether a given value is a number.

1function fnValidateNumber($value)
2{
3    #is_ double($value);
4    #is_ float($value);
5    #is_ int($value);
6    #is_ integer($value);
7    return is_numeric($value);
8}

PHP 5.2 and above.

1function fnValidateNumber($value)
2{
3    #return filter_var($value, FILTER_VALIDATE_FLOAT); // float
4    return filter_var($value, FILTER_VALIDATE_INT); # int
5}

Sanitize Number

We can force all value to be only numeric by sanitize them.

1function fnSanitizeNumber($str)
2{
3    #letters and space only
4    return preg_match('/[^0-9]/', '', $str);
5}

PHP 5.2 and above.

1function fnSanitizeNumber($value)
2{
3    #return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT); // float
4    return filter_var($value, FILTER_SANITIZE_NUMBER_INT); # int
5}

Validate String Only

Sometimes to validate name we can use this function to restrict only letters and spaces.

1function fnValidateStringr($str)
2{
3    #letters and space only
4    return preg_match('/^[A-Za-z\s ]+$/', $str);
5}

Sanitize String

We can sanitize it instead of validate user input.

1function fnSanitizeStringr($str)
2{
3    #letters and space only
4    return preg_replace('/[^A-Za-z\s ]/', '', $str);
5}

PHP 5.2 and above. built-in function by PHP provides a much more powerful sanitize capability.

1function fnSanitizeStringr($str)
2{
3    return filter_var($str, FILTER_SANITIZE_STRIPPED); # only 'String' is allowed eg. '<br>HELLO</br>' => 'HELLO'
4}

Validate Alphanumeric Characters

This validates alphanumeric characters.

1function fnValidateAlphanumeric($string)
2{
3    return ctype_alnum ($string);
4}

Sanitize Alphanumeric Characters

This sanitize alphanumeric characters. eg. “HELLO! Do we have 90 idiots running around here?” => “HELLO Do we have 90 idiots running around here”

1function fnSanitizeAlphanumeric($string)
2{
3    return preg_replace('/[^a-zA-Z0-9]/', '', $string);
4}

Validate URL Exist

This function will check whether a given URL exist and not only validate it.

01function url_exist($url)
02{
03    $url = @parse_url($url);
04 
05    if (!$url)
06    {
07        return false;
08    }
09 
10    $url = array_map('trim', $url);
11    $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
12    $path = (isset($url['path'])) ? $url['path'] : '';
13 
14    if ($path == '')
15    {
16        $path = '/';
17    }
18 
19    $path .= (isset($url['query'])) ? '?$url[query]' : '';
20 
21    if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host']))
22    {
23        if (PHP_VERSION >= 5)
24        {
25            $headers = @get_headers('$url[scheme]://$url[host]:$url[port]$path');
26        }
27        else
28        {
29            $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
30 
31            if (!$fp)
32            {
33                return false;
34            }
35            fputs($fp, 'HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n');
36            $headers = fread($fp, 4096);
37            fclose($fp);
38        }
39        $headers = (is_array($headers)) ? implode('\n', $headers) : $headers;
40        return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
41    }
42    return false;
43}

Validate URL Format

This function will validate a given url to ensure the format is correct.

1function fnValidateUrl($url){
2return preg_match('/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i', $url);
3}

PHP 5.2 and above.

1function fnValidateUrl($url)
2{
3  return filter_var($url, FILTER_VALIDATE_URL);
4}

Sanitize URL

PHP 5.2 and above.

1function fnSanitizeUrl($url)
2{
3  return filter_var($url, FILTER_SANITIZE_URL);
4}

Validate Image Exist

This function will check whether a given image link exist and not only validate it.

1function image_exist($url) {
2if(@file_get_contents($url,0,NULL,0,1)){return 1;}else{ return 0;}
3}

Validate IP Address

This function will validate an IP address.

1function fnValidateIP($IP){
2    return preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)
3}

PHP 5 and above. This can also specific validation for IPV4 or IPV6.

1function fnValidateIP($ip)
2{
3  return filter_var($ip, FILTER_VALIDATE_IP);
4}

Validate Proxy

This function will let us detect proxy visitors even those that are behind anonymous proxy.

01function fnValidateProxy(){
02    if ($_SERVER['HTTP_X_FORWARDED_FOR']
03       || $_SERVER['HTTP_X_FORWARDED']
04       || $_SERVER['HTTP_FORWARDED_FOR']
05       || $_SERVER['HTTP_VIA']
06       || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))
07       || @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))
08    {
09        exit('Proxy detected');
10    }
11}

Validate Username

Before we validate whether a given username is matches the one in our database, we can perform a validation check first to prevent any unnecessary SQL call.

1function fnValidateUsername($username){
2    #alphabet, digit, @, _ and . are allow. Minimum 6 character. Maximum 50 characters (email address may be more)
3    return preg_match('/^[a-zA-Z\d_@.]{6,50}$/i', $username);
4}

Validate Strong Password

Another good thing is to validate whether a particular password given by the user is strong enough. You can do that using this function which required the password to have a minimum of 8 characters, at least 1 uppercase, 1 lowercase and 1 number.

1function fnValidatePassword($password){
2    #must contain 8 characters, 1 uppercase, 1 lowercase and 1 number
3    return preg_match('/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/', $password);
4}

Validate US Phone Number

This function will validate US phone number for US users.

1function fnValidateUSPhone($phoneNo){
2    return preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x', $phoneNo);
3}

Validate US Postal Code

This function validate US postal code.

1function fnValidateUSPostal($postalcode){
2    #eg. 92345-3214
3    return preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$postalcode);
4}

Validate US Social Security Numbers

This function validate US Social Security Numbers.

1function fnValidateUSSocialSecurityCode($ssb){
2    #eg. 531-63-5334
3    return preg_match('/^[\d]{3}-[\d]{2}-[\d]{4}$/',$ssn);
4}

Validate Credit Card

This function validate credit card format.

1function fnValidateCreditCard($cc){
2    #eg. 718486746312031
3    return preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc);
4}

Validate Date

This is a date format MM-DD-YYYY or MM-DD-YY validation which validate from year 0000-9999.

1function fnValidateDate($date){
2    #05/12/2109
3    #05-12-0009
4    #05.12.9909
5    #05.12.99
6    return preg_match('/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.][0-9]?[0-9]?[0-9]{2})*$/', $date);
7}

This is a date format YYYY-DD-MM or YY-MM-DD validation which validate from year 0000-9999.

1function fnValidateDate($date){
2    #2009/12/11
3    #2009-12-11
4    #2009.12.11
5    #09.12.11
6    return preg_match('#^([0-9]?[0-9]?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01]))*$#'', $date);
7}

Validate Hexadecimal Colors

This is a good validation for people who allows their user to change color in their system.

1function fnValidateColor($color){
2    #CCC
3    #CCCCC
4    #FFFFF
5    return preg_match('/^#(?:(?:[a-f0-9]{3}){1,2})$/i', $color);
6}

Make Query Safe

This function help sanitize our data to be SQL injection safe.

1function _clean($str){
2return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES));
3}
4 
5//usage call it somewhere in beginning of your script
6_clean($_POST);
7_clean($_GET);
8_clean($_REQUEST);// and so on..

Make Data Safe

This function help to keep us protected against XSS, JS and SQL injection by removing tags.

1function _clean($str){
2return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', strip_tags(trim(htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES))));
3}
4 
5//usage call it somewhere in beginning of your script
6_clean($_POST);
7_clean($_GET);
8_clean($_REQUEST);// and so on..