How to send email after registering - database

After that someone registers in a site, a mail is usually sent to his mail account. But to generate this link or what info can be placed in this link so that it can be used to activate the user account??

you can place any thing which can identify a valid user
1- A Hash Value
2- An Encrypted String
3- A Guid
and when user clicks on the link , you can validate the value.

Check this part of code:
Generate code and e-mail:
/* if $acces = 0 everything is perfect so the system send a confirmation mail */
if($acces == 0)
{
print("<br>A mail has been send to " . $mail . "<br><br>") ;
/* prepare the vars */
$activ = $user . $pass ;
$code = md5($activ) ;
/* to how send to mail */
$to = $mail ;
/* prepare the subject */
$subject = "You need to confirm you registration to " . $_SERVER['HTTP_HOST'] ;
/* start writing the message */
$message = "Hello " . $user . ",\r\n\r\n" ;
$message .= "Thank you for registering at " . $_SERVER['HTTP_HOST'] . " Your account is created and must be activated before you can use it.\r\n" ;
$message .= "To activate the account click on the following link or copy-paste it in your browser :\r\n\r\n" ;
$message .= "http://" . $_SERVER['HTTP_HOST'] . "/~carron/registration/register_send.php?user=" . $user . "&activation=" . $code . "\r\n\r\n" ;
$message .= "After activation you may login to http://" . $_SERVER['HTTP_HOST'] . " using the following username and password:\r\n\r\n" ;
$message .= "Username - " . $user . "\r\nPassword - " . $pass . "\r\n" ;
/* To send HTML mail, you can set the Content-type header. */
$headers = "MIME-Version: 1.0";
$headers .= "Content-type: text/html; charset=iso-8859-1";
/* set up additional headers */
$headers .= "To: " . $to . "<br>\n" ;
$headers .= "From: " . $from . $addmail ;
/* writing data in the base */
$query = "INSERT INTO registration (user, pass, activ, mail) VALUES ('$user', '$pass', '$code', '$mail') ;" ;
$result = mysql_query($query, $db);
if ($result == false)
die("Failed " . $query);
else
{
/* everything went well so we can mail it now */
mail($to, $subject, $message, $headers);
}
}
Check activation:
/* controle if the validation link is right */
$x = 0 ;
$query = "SELECT user, pass, activ, mail FROM registration WHERE user = '" . $username . "';" ;
$result = mysql_query($query, $db);
if ($result == false) die("Failed " . $query);
while ($fields = mysql_fetch_row($result))
{
for ($i=0, $max=sizeof($fields) ; $i < $max ; $i++)
{
$tmp[$i] = $fields[$i] ;
}
/* the activation link is right so we can update
the datas in the data base */
if($activation == $tmp[2] AND $username == $tmp[0])
{
$x = 1 ;
$query2 = "UPDATE registration SET activated = '1' WHERE user = '" . $username . "' AND activ = '" . $activation . "' ;" ;
$result2 = mysql_query($query2, $db);
if ($result2 == false)
die("Failed " . $query2);
}
else
$x = -1 ;
}
/* give a confirmation message to the user */
if($x == 1)
print($username . " your activation has been done perfectly<br> Thank you...") ;
else
print($username . " your activation has not been done corectly<br> Please try again later...") ;
Script from PHPclasses.org

The idea is to have a link that only the recipient of the email knows. So when that link is visited on your site, you know that someone has read the email you sent and clicked on the link and so you can presume that the person who registered and the person who read the email are the same.
As such, you just need a link that can't be easily guessed. Pick something random (and record it in the user's profile) or hash the user name + a seed, or something.

When user registered, you can use uniqid() to create an activate code and stored in database. Then in mail, give a link like: http://....../activate.php?code=[uniqid()]
In activate.php, you can read activate code from database and check it.

Related

Need help to populate a structs array in perl

I need some help to populate an array made of structs in perl.
The data for the array comesfrom a .SH file with the following format :
108,Country,Location,ap17,ip_149,ssh,model,12/8/2020
The code I am using is as follows:
use strict;
use warnings;
use Class::Struct;
struct(Net_Node => [hostname => '$', dir_ip => '$', access => '$', user => '$', pass => '$']);
my $node = Net_Node->new();
my #nodes;
my $user = "hjack";
my $pass = 'butstalion';
my $line;
my #all;
my $counter=0;
open(my $fh, '<', "exaple.sh") or die "Failed to open especified file";
#system('clear');
foreach $line (<$fh>) {
#all=split(',', $line);
$node->hostname ($all[3]);
$node->dir_ip ($all[4]);
$node->access ($all[5]);
$node->user ($user);
$node->pass ($pass);
$nodes[$counter] = $node;
$counter++;
}
my $size = #nodes;
print "\n \n";
print ("array size = $size\n\n");
$counter = 0;
while ($counter < 20) {
print ($counter,"\n\n");
print ($nodes[$counter]->hostname,"\n");
print ($nodes[$counter]->dir_ip, "\n");
print ($nodes[$counter]->access, "\n");
print ($nodes[$counter]->user, "\n");
print ($nodes[$counter]->pass, "\n\n");
$counter++;
}
close($fh);
The output of this code is a populated array but only with the last element generated in the foreach loop, is there any way to populate this array with the data of the .SH file?
Thanks in advance
the data of the file is as follows
89,Country,Location,sw01,ip_10,ssh,model,12/8/2020
90,Country,Location,sw02,ip_18,ssh,model,12/8/2020
91,Country,Location,sw03,ip_26,ssh,model,12/8/2020
92,Country,Location,sw04,ip_27,ssh,model,12/8/2020
93,Country,Location,sw05,ip_28,ssh,model,12/8/2020
94,Country,Location,sw06,ip_29,ssh,model,12/8/2020
95,Country,Location,ap02,ip_13,ssh,model,12/8/2020
96,Country,Location,ap03,ip_12,ssh,model,12/8/2020
97,Country,Location,ap04,ip_20,ssh,model,12/8/2020
98,Country,Location,ap05,ip_14,ssh,model,12/8/2020
99,Country,Location,ap06,ip_15,ssh,model,12/8/2020
100,Country,Location,ap07,ip_16,ssh,model,12/8/2020
101,Country,Location,ap08,ip_17,ssh,model,12/8/2020
102,Country,Location,ap09,ip_18,ssh,model,12/8/2020
103,Country,Location,ap10,ip_19,ssh,model,12/8/2020
104,Country,Location,ap11,ip_24,ssh,model,12/8/2020
105,Country,Location,ap12,ip_25,ssh,model,12/8/2020
106,Country,Location,ap14,ip_27,ssh,model,12/8/2020
107,Country,Location,ap15,ip_37,ssh,model,12/8/2020
108,Country,Location,ap17,ip_149,ssh,model,12/8/2020
my $node = Net_Node->new();
...
foreach $line (<$fh>) {
...
$nodes[$counter] = $node;
}
creates a single Net_Node instance and overwrites its data in every iteration of the foreach loop. It sounds like you want to create a new instance for each line of the loop. So you should move your Net_Node->new() call inside the loop.
foreach $line (<$fh>) {
my $node = Net_Node->new();
...
$nodes[$counter] = $node;
}
With a simpler data structure like a native Perl hash, you could have appended a copy of the data structure to your list like
$nodes[$counter] = { %$node };
but I would be more reluctant to do that with an object, which might not even be represented internally as a hash reference.
Perhaps the code could be implemented in the following shape
Comment:
define structure of node
for readability define an array with descriptive fields of interest
read file line by line
place temporary the data of interest into a hash
create a new node on each iteration
fill the node with data from hash
store the node in an array
generate an output for nodes data
#!/usr/bin/env perl
#
# vim: ai ts=4 sw=4
use strict;
use warnings;
use feature 'say';
use Class::Struct Net_Node => [
hostname => '$',
dir_ip => '$',
access => '$',
user => '$',
pass => '$'
];
my #fields = qw/hostname dir_ip access/;
my($user,$pass) = qw/hjack bustalion/;
my #nodes;
while( <DATA> ) {
next if /^$/; # skip empty lines
chomp;
my %data;
my $node = new Net_Node;
#data{#fields} = (split(',',$_))[3..5];
$node->hostname( $data{hostname} );
$node->dir_ip( $data{dir_ip} );
$node->access( $data{access} );
$node->user( $user );
$node->pass( $pass );
push #nodes, $node;
}
say "\nTotal nodes = " . #nodes;
my $counter = 10;
for my $node ( #nodes ) {
last unless $counter--;
say "
Hostname : " . $node->hostname . "
Dir_IP : " . $node->dir_ip . "
Access : " . $node->access . "
Userid : " . $node->user . "
Passwd : " . $node->pass;
}
__DATA__
89,Country,Location,sw01,ip_10,ssh,model,12/8/2020
90,Country,Location,sw02,ip_18,ssh,model,12/8/2020
91,Country,Location,sw03,ip_26,ssh,model,12/8/2020
92,Country,Location,sw04,ip_27,ssh,model,12/8/2020
93,Country,Location,sw05,ip_28,ssh,model,12/8/2020
94,Country,Location,sw06,ip_29,ssh,model,12/8/2020
95,Country,Location,ap02,ip_13,ssh,model,12/8/2020
96,Country,Location,ap03,ip_12,ssh,model,12/8/2020
97,Country,Location,ap04,ip_20,ssh,model,12/8/2020
98,Country,Location,ap05,ip_14,ssh,model,12/8/2020
99,Country,Location,ap06,ip_15,ssh,model,12/8/2020
100,Country,Location,ap07,ip_16,ssh,model,12/8/2020
101,Country,Location,ap08,ip_17,ssh,model,12/8/2020
102,Country,Location,ap09,ip_18,ssh,model,12/8/2020
103,Country,Location,ap10,ip_19,ssh,model,12/8/2020
104,Country,Location,ap11,ip_24,ssh,model,12/8/2020
105,Country,Location,ap12,ip_25,ssh,model,12/8/2020
106,Country,Location,ap14,ip_27,ssh,model,12/8/2020
107,Country,Location,ap15,ip_37,ssh,model,12/8/2020
108,Country,Location,ap17,ip_149,ssh,model,12/8/2020
Output
Total nodes = 20
Hostname : sw01
Dir_IP : ip_10
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : sw02
Dir_IP : ip_18
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : sw03
Dir_IP : ip_26
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : sw04
Dir_IP : ip_27
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : sw05
Dir_IP : ip_28
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : sw06
Dir_IP : ip_29
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : ap02
Dir_IP : ip_13
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : ap03
Dir_IP : ip_12
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : ap04
Dir_IP : ip_20
Access : ssh
Userid : hjack
Passwd : bustalion
Hostname : ap05
Dir_IP : ip_14
Access : ssh
Userid : hjack
Passwd : bustalion
Otherwise a slightly different approach can be taken to achieve similar result without Class::Struct module
#!/usr/bin/env perl
#
# vim: ai ts=4 sw=4
use strict;
use warnings;
use feature 'say';
my #fields = qw/hostname dir_ip access/;
my($user,$pass) = qw/hjack bustalion/;
my #nodes;
while( <DATA> ) {
next if /^$/;
chomp;
my $node;
$node->#{#fields} = (split(',',$_))[3..5];
$node->#{qw/user pass/} = ($user, $pass);
push #nodes, $node;
}
say "\nTotal nodes = " . #nodes;
for my $node ( #nodes ) {
say "
Hostname : " . $node->{hostname} . "
Dir_IP : " . $node->{dir_ip} . "
Access : " . $node->{access} . "
Userid : " . $node->{user} . "
Passwd : " . $node->{pass};
}
__DATA__
89,Country,Location,sw01,ip_10,ssh,model,12/8/2020
90,Country,Location,sw02,ip_18,ssh,model,12/8/2020
91,Country,Location,sw03,ip_26,ssh,model,12/8/2020
92,Country,Location,sw04,ip_27,ssh,model,12/8/2020
93,Country,Location,sw05,ip_28,ssh,model,12/8/2020
94,Country,Location,sw06,ip_29,ssh,model,12/8/2020
95,Country,Location,ap02,ip_13,ssh,model,12/8/2020
96,Country,Location,ap03,ip_12,ssh,model,12/8/2020
97,Country,Location,ap04,ip_20,ssh,model,12/8/2020
98,Country,Location,ap05,ip_14,ssh,model,12/8/2020
99,Country,Location,ap06,ip_15,ssh,model,12/8/2020
100,Country,Location,ap07,ip_16,ssh,model,12/8/2020
101,Country,Location,ap08,ip_17,ssh,model,12/8/2020
102,Country,Location,ap09,ip_18,ssh,model,12/8/2020
103,Country,Location,ap10,ip_19,ssh,model,12/8/2020
104,Country,Location,ap11,ip_24,ssh,model,12/8/2020
105,Country,Location,ap12,ip_25,ssh,model,12/8/2020
106,Country,Location,ap14,ip_27,ssh,model,12/8/2020
107,Country,Location,ap15,ip_37,ssh,model,12/8/2020
108,Country,Location,ap17,ip_149,ssh,model,12/8/2020

Yii2 how to download database

I want to download my database by clicking on a button. I have search around and found this code.
yii2 database download
I have added a action on my controller and added this modified code. I've removed database connection in the original code as I guess I don't need to make the connection again. I'm getting error at 'fetch_row()'. I tried Yii::$app->db->createCommand('fetch_row')but still getting error.
define('BACKUP_DIR', 'download/' ) ;
// Define Database Credentials
define('HOST', 'localhost' ) ;
define('USER', 'root' ) ;
define('PASSWORD', 'x24613rt' ) ;
define('DB_NAME', 'panthoibi' ) ;
$files = scandir(BACKUP_DIR);
if(count($files) > 2) {
for ($i=2; $i < count($files); $i++) {
unlink(BACKUP_DIR."/".$files[$i]);
}
}
/*
Define the filename for the sql file
If you plan to upload the file to Amazon's S3 service , use only lower-case letters
*/
$fileName = 'mysqlibackup--' . date('d-m-Y') . '#'.date('h.i.s').'.sql' ;
// Set execution time limit
if(function_exists('max_execution_time')) {
if( ini_get('max_execution_time') > 0 )
set_time_limit(0) ;
}
// Check if directory is already created and has the proper permissions
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ;
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ;
// Create an ".htaccess" file , it will restrict direct accss to the backup-directory .
//$content = 'deny from all' ;
//$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ;
//$file->fwrite($content) ;
// Introduction information //
$return = "";
$return .= "--\n";
$return .= "-- A mysqli Backup System \n";
$return .= "--\n";
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
$return = "--\n";
$return .= "-- Database : " . DB_NAME . "\n";
$return .= "--\n";
$return .= "-- --------------------------------------------------\n";
$return .= "-- ---------------------------------------------------\n";
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ;
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ;
$tables = array() ;
// Exploring what tables this database has
$result = Yii::$app->db->createCommand('SHOW TABLES');
// Cycle through "$result" and put content into an array
while ($row = $result->fetch_row())
$tables[] = $row[0] ;
// Cycle through each table
foreach($tables as $table)
{
// Get content of each table
$result = $mysqli->query('SELECT * FROM '. $table) ;
// Get number of fields (columns) of each table
$num_fields = $mysqli->field_count ;
// Add table information
$return .= "--\n" ;
$return .= '-- Tabel structure for table `' . $table . '`' . "\n" ;
$return .= "--\n" ;
$return.= 'DROP TABLE IF EXISTS `'.$table.'`;' . "\n" ;
// Get the table-shema
$shema = $mysqli->query('SHOW CREATE TABLE '.$table) ;
// Extract table shema
$tableshema = $shema->fetch_row() ;
// Append table-shema into code
$return.= $tableshema[1].";" . "\n\n" ;
// Cycle through each table-row
while($rowdata = $result->fetch_row())
{
// Prepare code that will insert data into table
$return .= 'INSERT INTO `'.$table .'` VALUES ( ' ;
// Extract data of each row
for($i=0; $i<$num_fields; $i++)
$return .= '"'.$rowdata[$i] . "\"," ;
// Let's remove the last comma
$return = substr("$return", 0, -1) ;
$return .= ");" ."\n" ;
}
$return .= "\n\n" ;
}
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; ' . "\n" ;
$return .= 'COMMIT ; ' . "\n" ;
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n" ;
//$file = file_put_contents($fileName , $return) ;
$zip = new ZipArchive() ;
$resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ;
if( $resOpen )
$zip->addFromString( $fileName , "$return" ) ;
$zip->close() ;
$fileSize = $this->get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ;
You are mixing Yii query command with mysqli command this don't work ..
eg:
You are using CreateCommand
// Exploring what tables this database has
$result = Yii::$app->db->createCommand('SHOW TABLES');
but don't execute .. you should try
$result = Yii::$app->db->createCommand('SHOW TABLES')->execute();
or
$result = Yii::$app->db->createCommand('SHOW TABLES')->queryOne();
or
$result = Yii::$app->db->createCommand('SHOW TABLES')->queryAll();
Then try take a look at the $result content eg:
var_dump($result);
Your $result content don't shoul be adapt for
$result->fetch_row()
but eventually you can iterate or manage the actual $result content with php function ..

Push notifications from a Web App in codename one

I need to implement a web app that consists in publishing events with the option of send notifications to subscribed people. How can I use the codename one libraries from a Web App?
Another question: When a cell phone receive the notification, can the application be opened in a specific window, in this case, the window which contain the event description?
Thank you in advance.
If your web app server is running php, you can use CURL to send push notifications to devices. You can easily do the same with other languages. See below sample php code I used.
Shai mentioned recently that you can include some hidden payload in your push message. You can add some variables to this data which you'll check and use to open the necessary form.
PHP sample code:
$cloudServerURL = "https://push.codenameone.com/push/push";
$token = "Your_Developer_token"; //Can be found under account tab of Dashboard
$auth = "Google_Push_Key";
$certPassword = "Your_Certificate_Password";
$cert = "https://www.dropbox.com/path_to_your_iOS_cert/MyAppDevPush.p12?dl=1"; //Test
//Note the 'dl=1', this will download the certificate, instead of opening it.
//$cert = "https://www.dropbox.com/path_to_your_iOS_cert/MyAppProPush.p12?dl=1"; //Live
$production = "false"; //Test
//$production = "True"; //Live
$burl = "";
$bbAppId = "";
$bbPass = "";
$bbPort = "";
$device = 'device_key';
$type = "3"; //Or other types like (2, 101) as required
$body = "Hello world";
$arguments = 'token=' . $token . '&device=' . $device . '&type=' . $type . '&auth=' . $auth . '&certPassword=' . $certPassword . '&cert=' . $cert . '&body=' . $body . '&burl=' . $burl . '&bbAppId=' . $bbAppId . '&bbPass=' . $bbPass . '&bbPort=' . $bbPort . '&production=' . $production;
$ch = curl_init($cloudServerURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$response = unserialize(curl_multi_getcontent($ch));));
curl_close($ch);

How to provide default output

I'm trying to get the following Perl program to print a default value, if no result is returned from a query. I am not sure how to do that.
When I run the script, I get the error: Can't call method "country_name" on an undefined value. Are there Any ideas on how I can change the program to print a default value, if no results are returned?
#!/usr/bin/perl update IP addresses with country
use strict;
use warnings;
use Net::IPInfoDB;
my $psql = "/usr/local/pgsql/current/bin/psql";
my $db = 'cpi';
my $args = "-U postgres -qc";
my $date = `/bin/date +\%y\%m\%d%H`;
my $reportfile = "/tmp/multiiplogins-$date";
my $sendmail = "/usr/sbin/sendmail -t -fcpi\#user.com";
my $mailsubject = "Login Report";
my $mailto = 'email#user.com';
my $query = "SELECT userid, login, email, logins, ips FROM (SELECT userid,login,email, count(userid) AS logins, count(ipaddr) AS ips FROM (SELECT l.userid, u.login, u.email, l.ipaddr FROM synloginaccess l, synusers u$
my $query2 = "SELECT l.userid, login, email, ipaddr FROM synloginaccess l, synusers u where l.accesstime > (now() - interval '24 hours') and l.type=2 and l.userid=u.userid ORDER BY l.userid;";
open (REPORT, ">$reportfile");
my $command = qq/$psql $db $args "$query"/;
my $command2 = qq/$psql $db $args "$query2"/;
my $result = `$command`;
my $result2 = `$command2`;
my $g = Net::IPInfoDB->new;
$g->key("api_key");
#we split $login into an array, line-by-line
my #lines = split("\n", $result2);
for my $line (#lines) {
#now we iterate through every line one-by-one
if ($line =~ /(?<ip>\d+\.\d+\.\d+\.\d+)/) {
my $city = $g->get_city("$1");
my $addr = $g->get_country("$1");
print "$line " . "| " . "\t" . $city->city_name . ", " . $addr->country_name ."\n";
print REPORT "$line " . "| " . "\t" . $city->city_name . ", ". $addr->country_name ."\n";
}
else {
print "$line \n ";
}
}
close REPORT;
mailReport();
sub mailReport{
#mail it
open(MAIL, "|$sendmail");
print MAIL "To: $mailto\n";
print MAIL "Subject: $mailsubject\n";
print MAIL "\n";
open (INFILE, "$reportfile");
my #contents = <INFILE>;
my $line;`
$addr ? $addr->country_name : "default"

Who user only DB class from PERA?

I want to use only PEAR DB class, I try follow:
$pearPfad ="PEAR_DB-1.7.14/DB-1.7.14/DB.php";
error_reporting(E_ALL);
require_once($pearPfad);
$DB_dbType ="mysql";
$DB_user = "myuser";
$DB_pass = "mypassword";
$DB_host = "localhost";
$DB_dbName ="mydatabase";
$dsn = $DB_dbType . "://" // Build a DSN string (Data Source Name)
. $DB_user . ":" // Required by DB::connect()
. $DB_pass . "#"
. $DB_host . "/"
. $DB_dbName;
$db = DB::connect($dsn, TRUE);
if (DB::isError($db)) {
die("FEHLER: ".$db->getMessage() );
}
$sql = "SELECT id, title , created FROM h1z4e_content";
$res = $db->query($sql);
if (DB::isError($res)) {
die($res->getMessage());
}
while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) {
if (DB::isError($row)) {
die($row->getMessage());
}
print ("<p>Hey, it s:<br />" . $row->id . " " . $row->title . " ... and their freaky et: " . $row->created. "</p>\n");
}
$res->free();
// Similar to: mysql_free_resul
$db->disconnect();
But I get this error:
Warning: require_once(PEAR.php): failed to open stream: No such file or directory in /var/www/PEAR/PEAR_DB-1.7.14/DB-1.7.14/DB.php on line 30 Fatal error: require_once(): Failed opening required 'PEAR.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/PEAR/PEAR_DB-1.7.14/DB-1.7.14/DB.php on line 30
I found here in Stack Overflow this link: PHP-PEAR require_once('DB.php');
I don't want install PEAR on my computer.
I want only user PEAR DB class, is this possible without install PEAR?
Yes, but you need to set the include path correctly - in your case, to /full/path/to/PEAR_DB-1.7.14/DB-1.7.14/

Resources