Admins eHow SysAdmin Tips & Tricks

April 26, 2017

Email to Telegram gateway

Filed under: PHP — Tags: , , , — admin @ 7:21 am

1.Create your own Telegram bot based on this tutorial :
https://www.domoticz.com/wiki/Telegram_Bot
or this one :
https://www.forsomedefinition.com/automation/creating-telegram-bot-notifications/
2.Create an email forwarder in cPanel and pipe it into a PHP script. make sure the script is executable (755 permission).
3.Here is the php script that will forward the email to your telegram bot :
Dont forget to adjust $url variable in telegram function based on first step.

#!/usr/local/bin/php -q
<?php
function mailRead($iKlimit = "")
{
	if ($iKlimit == "") {
		$iKlimit = 1024;
	}
	$sErrorSTDINFail = "Error - failed to read mail from STDIN!";
	$fp = fopen("php://stdin", "r");
	if (!$fp) {
		echo $sErrorSTDINFail;
		exit();
	}
	$sEmail = "";
	if ($iKlimit == - 1) {
		while (!feof($fp)) {
			$sEmail .= fread($fp, 1024);
		}
	}
	else {
		while (!feof($fp) && $i_limit < $iKlimit) {
			$sEmail .= fread($fp, 1024);
			$i_limit++;
		}
	}
	fclose($fp);
	return $sEmail;
}

function telegram($m)
{
	$url = 'https://api.telegram.org/botxxxxxxx:xxxxxxxxx/sendMessage?chat_id=xxxxx&text=';
	$url .= urlencode($m);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);
	curl_close($ch);
}

$mail = mailRead(4096);
$lines = explode("\n", $mail);

$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;

for ($i = 0; $i < count($lines); $i++) {
	if ($splittingheaders) {
		$headers .= $lines[$i] . "\n";
		if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
			$subject = $matches[1];
		}
		if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
			$from = $matches[1];
		}
		if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
			$to = $matches[1];
		}
	}
	else {
		$message .= $lines[$i] . "\n";
	}
	if (trim($lines[$i]) == "") {
		$splittingheaders = false;
	}
}

telegram("From: $from\nSubject: $subject\nMessage: $message");
?>

September 9, 2011

Install Apache2 + PHP5 on Debian

Filed under: Apache,Debian,PHP — Tags: , , , , — admin @ 8:16 am

Very Simple…

apt-get install libapache2-mod-php5
/etc/init.d/apache2 restart

May 27, 2011

file_post_contents php function

Filed under: PHP — Tags: , , — admin @ 6:30 pm

This php function is useful when you want to send arguments by POST method instead of GET. very handy πŸ˜‰
The usage is same as file_get_contents

function file_post_contents($url,$headers=false) {
    $url = parse_url($url);

    if (!isset($url['port'])) {
      if ($url['scheme'] == 'http') { $url['port']=80; }
      elseif ($url['scheme'] == 'https') { $url['port']=443; }
    }
    $url['query']=isset($url['query'])?$url['query']:'';

    $url['protocol']=$url['scheme'].'://';
    $eol="\r\n";

    $headers2 =  "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol. 
                "Host: ".$url['host'].$eol. 
                "Referer: ".$url['protocol'].$url['host'].$url['path'].$eol. 
                "Content-Type: application/x-www-form-urlencoded".$eol. 
                "Content-Length: ".strlen($url['query']).$eol.
                $eol.$url['query'];
    $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30); 
    if($fp) {
      fputs($fp, $headers2);
      $result = '';
      while(!feof($fp)) { $result .= fgets($fp, 128); }
      fclose($fp);
      if (!$headers) {
        //removes headers
        $pattern="/^.*\r\n\r\n/s";
        $result=preg_replace($pattern,'',$result);
      }
      return $result;
    }
}

March 18, 2010

Prevent MySQL Injection in PHP

Filed under: General,MySQL,PHP,Security — Tags: , , , , — admin @ 5:21 pm

As it is explained everywhere on the web , the general solution to prevent mysql injection attacks in php is to use mysql_real_escape_string function , there are many guides on how to use it in conjunction with sprintf to escape dangerous characters before executing a mysql query, but I found a very innovative solution in a comment on php.net website , it recommends to escape all variables sent by user by get or post method in the beginning of every page which executes mysql queries :
first make sure magic_quotes_gpc is turned off on your php configuration , it can be checked on php info page.
this step makes sure your variables are not escaped twice.
This article explains how to disable magic quotes : Disabling Magic Quotes Guide
put the following code in the beginning of every page executing mysql queries :

	include ('mysql_connect.php');
	
	//This stops SQL Injection in POST vars
	foreach ($_POST as $key => $value) {
		$_POST[$key] = mysql_real_escape_string($value);
	}

	//This stops SQL Injection in GET vars
	foreach ($_GET as $key => $value) {
		$_GET[$key] = mysql_real_escape_string($value);
	}

mysql_real_escape_string needs you to be connected to your mysql database when you call it , so I have placed include (‘mysql_connect.php’); in the beginning of script , you can replace it with your own mysql connect commands.

June 7, 2009

Change Linux Password from PHP Script

Filed under: CentOS,Debian,General,PHP — Tags: , , , — admin @ 8:48 pm

There are a few scripts available on net which allow you to change a linux user password from PHP. but all of them are very complex and hard to implement , so after some hours of work , I’ve written this PHP script πŸ™‚ it is very simple , in order for this to work you need to allow your webserver to run sed command as root through sudoers , or allow your webserver to write on your /etc/shadow file.

$username='USERNAME';
$password='PASSWORD';  // New Password
$sed='/bin/sed'; //Path to sed command
$salt = substr($username, 0, 2);
$pass_crypt = crypt($password, $salt);
$pass_crypt=str_replace("/","\/",$pass_crypt);
system($sed." -i 's/".$username.":[a-zA-z0-9/$\.]*/".$username.":".$pass_crypt."/g' /etc/shadow",$retval);

June 1, 2009

Turn on displaying all PHP errors

Filed under: PHP — Tags: , , , — admin @ 4:46 pm

Add the Following code at the top of your php script :

error_reporting(E_ALL);
ini_set('display_errors', '1');

May 31, 2009

How to configure nginx + php5 + mysql on debian 5 lenny

Filed under: Debian,General,MySQL,Nginx,PHP — Tags: , , , , — admin @ 3:56 pm

1.Install PHP5
We will use dotdeb repo for installing the latest version of PHP5 and MySQL Server so first we need to configure apt to use dotdeb repo.
Edit /etc/apt/sources.list :

nano /etc/apt/sources.list

Add The following lines to end of it :

deb http://packages.dotdeb.org stable all
deb-src http://packages.dotdeb.org stable all

Press CTRL+X Choose Yes to save the file and Exit.
update apt cache :

apt-get update

Now install PHP5 :

apt-get install php5-cgi php5-mysql

Now edit /etc/php5/cgi/php.ini :

nano /etc/php5/cgi/php.ini

and change cgi.fix_pathinfo to 1 :

cgi.fix_pathinfo = 1

Save File and Exit.
2. Install MySQL Server

apt-get install mysql-server

3. Install Lighttpd
We need to install lighttpd because Nginx does not come with a FastCGI package, and there isn’t a standalone package yet. So we are going to install Lighttpd, disable it, and use spawn-fcgi from the Lighttpd package.

apt-get install lighttpd
/etc/init.d/lighttpd stop
update-rc.d -f lighttpd remove

Also remove lighttpd executable file :

rm /usr/sbin/lighttpd

4. Setup spawn-fcgi
Since we are going to use spawn-fcgi to handle PHP, we need to set it up to start when our server starts and make an init script so that we can control the processes. For starters, create the init script:

nano /etc/init.d/php-fastcgi

and add the following code to it and save it:

#! /bin/sh
### BEGIN INIT INFO
# Provides:          php-fastcgi
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop php-cgi in external FASTCGI mode
# Description:       Start and stop php-cgi in external FASTCGI mode
### END INIT INFO

# Author: Kurt Zankl <[EMAIL PROTECTED]>

# Do NOT "set -e"

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="php-cgi in external FASTCGI mode"
NAME=php-fastcgi
DAEMON=/usr/bin/php-cgi
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
PHP_CONFIG_FILE=/etc/php5/cgi/php.ini

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

# If the daemon is not enabled, give the user a warning and then exit,
# unless we are stopping the daemon
if [ "$START" != "yes" -a "$1" != "stop" ]; then
log_warning_msg "To enable $NAME, edit /etc/default/$NAME and set START=yes"
exit 0
fi

# Process configuration
export PHP_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS
DAEMON_ARGS="-q -b $FCGI_HOST:$FCGI_PORT -c $PHP_CONFIG_FILE"

do_start()
{
# Return
#   0 if daemon has been started
#   1 if daemon was already running
#   2 if daemon could not be started
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
|| return 1
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON \
--background --make-pidfile --chuid $EXEC_AS_USER --startas $DAEMON -- \
$DAEMON_ARGS \
|| return 2
}

do_stop()
{
# Return
#   0 if daemon has been stopped
#   1 if daemon was already stopped
#   2 if daemon could not be stopped
#   other if a failure occurred
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE > /dev/null # --name $DAEMON
RETVAL="$?"
[ "$RETVAL" = 2 ] && return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently.  A last resort is to
# sleep for some time.
start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
[ "$?" = 2 ] && return 2
# Many daemons don't delete their pidfiles when they exit.
rm -f $PIDFILE
return "$RETVAL"
}
case "$1" in
start)
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
do_start
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
stop)
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
do_stop
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
restart|force-reload)
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
case "$?" in
0|1)
do_start
case "$?" in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
exit 3
;;
esac

There is no editing needed for the code above. Now we need to make it executable.

chmod +x /etc/init.d/php-fastcgi

Now we will create the configuration file for spawn-fcgi:

nano /etc/default/php-fastcgi

and add:

START=yes

# Which user runs PHP? (default: www-data)

EXEC_AS_USER=www-data

# Host and TCP port for FASTCGI-Listener (default: localhost:9000)

FCGI_HOST=localhost
FCGI_PORT=9000

# Environment variables, which are processed by PHP

PHP_FCGI_CHILDREN=4
PHP_FCGI_MAX_REQUESTS=1000

In this file, you can change the FCGI_PORT, PHP_FCGI_CHILDREN, and PHP_FCGI_MAX_REQUESTS. If you change the port, make sure to note what you change it to because we will need it for later. Now, we want to make sure that spawn-fcgi starts when the server starts:

update-rc.d php-fastcgi defaults
/etc/init.d/php-fastcgi restart

5. Install Nginx

apt-get install nginx

6. Configure Nginx and your default vhost
For help with configuring Nginx beyond just the default configuration, please refer to the Nginx Wiki. We are now going to configure the default vhost so that we can verify that PHP is working with Nginx.

nano /etc/nginx/sites-available/default

In the default vhost, change the following lines to look like this:

server_name _;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/nginx-default$fastcgi_script_name;
include fastcgi_params;
}

What we did here was changed the server_name to accept all incoming requests, uncommented the location stanza and defined where Nginx needs to look for spawn-fcgi. If you changed the port above in the /etc/default/php-fastcgi file, then you need to change the port on the fastcgi_pass line as well. On the line fastcgi_param SCRIPT_FILENAME /var/www/nginx-default$fastcgi_script_name;, you need to change /var/ww/nginx-default to match your web root. On the line include fastcgi_params; you need to add a space between the include and the fastcgi_params as there is a bug in the default configuration and that space was omitted. Once you save the default-vhost, you need to restart Nginx.

/etc/init.d/nginx restart

Now we will create an info.php file in your web root:

nano /var/www/nginx-default/info.php

Add the following code and save the file:

<? phpinfo(); ?>

Now in your web browser, pull up the newly created file (http://your-ip/info.php). You should see information about the version of PHP that you are running.

Note: When I installed Nginx, it did not start automatically, however it was setup to start when the server booted. I have heard stories of users having issues with Nginx starting automatically when the server boots. If Nginx does not start when you boot your server, run the following command which will make it start on boot:

update-rc.d nginx defaults

Enjoy!

Reference : ChrisJohnston.org

Powered by WordPress