How to make an automatic code generator in codeigniter - php

How to make an automatic code generator so that I can send it to a mobile using my API then verify it after checking in php codeigniter
My one related controller looks like:
public function print_patientdetails($id,$veri,$phone,$username) {
if($veri == 0){
$verifycode = "12345"; // here I need an automatic code generator function
$result['verifycode'] = "12345";//and here need to keep the code and pass hidden throughout the pages
echo $this->sendverifymsg($phone, $verifycode);
$result['query'] = $this->panel_model->hospitaldetails($sess_id);
$result['query1'] = $this->register_model->view_register($phone, $username);
$this->load->view('innerheader', $result);
$this->load->view('verify', $result);
$this->load->view('footer', $result);
}else{
$sess_id = $this->session->userdata('id');
$result['query'] = $this->panel_model->hospitaldetails($sess_id);
$result['query1'] = $this->register_model->edit_patient($id);
foreach ($result['query1'] as $row)
{
$phone = $row->phone;
$username = $row->userid;
$email = $row->email;
$this->load->view('print_patientdetail', $result);
echo $this->sendregistermsg($phone, $username);
echo $this->mail($email, $phone, $username);
}
}
}

Just use php uniqid() native function like this:
$verifycode = uniqid();

what i understood is you just need something which can generate a random code for you.
if this is purpose you can use rand(0,99999); function which generates random numbers.
Moreover if you need that this random number should not b one from already generated then you can use db to store random numbers, enter it when it generates and at the time of new generating compare it with already stored random numbers.

Related

How to deal with unencoded URL redirects to my website correctly?

We are using CleverReach to redirect people to our website after they have double opt-in their mail account. We redirect the email as a query parameter to our website, like: example.com/thanks?email=foo#bar.com (by setting up a redirect in the CleverReach backend like example.com/thanks?email={EMAIL}). Apparently, the email parameter doesnt get urlencoded by cleverreach.
Now, in Drupal, if the URL is like so: example.com/thanks?email=hello+world#bar.com and using this code:
$request = \Drupal::request();
$email = $request->query->get('email');
$email is hello world#bar.com. Now, I dont know what the correct processing is here. Obviously, I cant tell CleverReach to urlencode their redirects beforehand. I dont even know if that would be best practice or if I need to imlement something...
The only thing I found out is that $_SERVER['QUERY_STRING'] contains the "real" string, which I can urlencode and then redirect, and then, by reading the query params, urldecode them. But I feel like I am missing some crucial inbuilt functionality.
TL;DR
If a website redirects to my website using not urlencoded query params, how do I read them?
My current approach:
<?php
public function redirectIfIllegalUri() {
$request = \Drupal::request();
$email = $request->query->get('email', '');
$needsRedirect = (false !== strpos($email, ' ') || false !== strpos($email, '#'));
if ($needsRedirect && isset($_SERVER['QUERY_STRING']) && false !== strpos($_SERVER['QUERY_STRING'], 'email=')) {
$sqs = $_SERVER['QUERY_STRING'];
$sqs = htmlspecialchars($sqs);
$sqs = filter_var($sqs, FILTER_SANITIZE_STRING);
$sqs = filter_var($sqs, FILTER_SANITIZE_ENCODED);
$sqs = urldecode($sqs);
$sqs = explode('&', $sqs);
foreach ($sqs as $queryParam) {
if (false === strpos($queryParam, 'email=')) continue;
$values = explode('=', $queryParam);
$email = $values[1];
}
$emailEncoded = urlencode($email);
$query = $request->query->all();
$query['email'] = $emailEncoded;
$refreshUrl = Url::fromRoute('<current>');
$refreshUrl->setOptions([
'query' => $query,
]);
$response = new RedirectResponse($refreshUrl->toString(), 301);
$response->send();
return;
}
}
$request = \Drupal::request();
$email = urldecode($request->query->get('email', false));
drupal request() docs
The problem you are facing is that the + will be treated as a space when you get the value from $_GET global variable.
Currently in PHP doesn't exist a method that returns these values without urldecoding and you need to build a custom function to achieve what you are asking:
A simple function will return not encoded input is by using this function:
function get_params() {
$getData = $_SERVER['QUERY_STRING'];
$getParams = explode('&', $getData);
$getParameters = [];
foreach ($getParams as $getParam) {
$parsed = explode('=', $getParam);
$getParameters[$parsed[0]] = $parsed[1];
}
return $getParameters;
}
This solution can be used if you do not have any other option. By using this function you will always get the data encoded.
If you can encode the value from cleverreach then the best approach is to encode it there.
Encoding the value in cleverreach for email hello+world#bar.com will give you this url example.com/thanks?email=hello%2Bworld%40bar.com and in $_GET you will have the email containing the + sign.

I want to write a function that uses $_POST['first_name '] and $_POST['password '] as parameters

I want to write a function to -log users in / check log in details- that uses $_POST['first_name '] and $_POST['password'] as parameters. I must be doing something silly. Can someone help me out??
function log_user_in($_POST['first_name'],$_POST['password']) {
if ( !empty($_POST['first_name']) && !empty($_POST['password']) ) {
$first_name = $_POST['first_name'];
$first_name = mysqli_real_escape_string($dbc, $first_name);
$password = $_POST['password'];
$password = mysqli_real_escape_string($dbc, $password);
---mysqli queries----
session_start();
redirect_user('page.php');
} // close if all set
} // close function log user in
I get the feeling, that $_POST['information'] cannot be used as parameters/arguments in functions, I may be wrong, in which case how do I substitute them for variables or something e.g.
function log_user_in ($a, $b) {
if ( !empty($a) && !empty($b) ) {
$first_name = $a;
$first_name = mysqli_real_escape_string($dbc, $first_name);
$password = $b;
$password = mysqli_real_escape_string($dbc, $password);
--- mysqli stuff ---
session_start();
redirect_user('page.php');
} // close if all set
} // close function log_user_in
and then call--
log_user_in($_POST['first_name'],$_POST['password']);
Can you tell me where I'm going wrong and what I can do to improve or give me a better method, thanks people!
J
So let's talk good coding for a moment here. Function arguments cannot be superglobals because you're defining what variables you're using, not what values they actually are. Thankfully PHP won't let you do this
function log_user_in($_POST['first_name'],$_POST['password']) {
echo $_POST['first_name'];
}
log_user('Bob', 'Smith');
Results in
Fatal error: Cannot re-assign auto-global variable _POST in /in/INsWe on line 3
At least prior to PHP7 (which throws a different error but still won't work)
So your second function is correct. Define your arguments (which should be clear names, not just $a, so you know which data is which) and then call the function with your superglobal values. In your case, you'll also have to pass your mysqli connection as well. So let's get this right
function log_user_in ($dbc, $first_name, $last_name) {
$first = mysqli_real_escape_string($dbc, $first_name);
//other stuff here
$sql = 'SELECT *
FROM users
WHERE first_name = "' . $first . '"
AND last_name = "' . $last . '"';
$dbc->query($sql);
}
So we've avoided using any globals or superglobals inside the function (called dependency injection). This lets you and anyone else who reads your code know what the data is expected to do (no chasing down another include file or guessing where a variable is set). And we've used clear variable names so we know what the data is.
As already stated by commenters, your second code is the right one.
But it can be simplified:
You don't need to assign an argument to a new variable, e.g. $first_name = $a;: directly use $first_name as argument name.
session_start() is not needed here (you don't use any $_SESSION[...]).
Anyway, even if you needed it here, it should be located elsewhere (most generally at the very begin of your file), because it must exist only once and before any other places where $_SESSION[...] is used.
Last point, your redirect_user('page.php'); seems a bit weird here. In fact you should probably end your function with a TRUE|FALSE result returned (depending on your mysql stuff), then using it when calling the function.
Actually something like this:
session_start();
// ... other stuff ...
function log_user_in ($first_name, $password) {
$first_name = mysqli_real_escape_string($dbc, $first_name);
$password = mysqli_real_escape_string($dbc, $password);
--- mysqli stuff ---
return // TRUE|FALSE depending on your mysql stuff result
}
if (log_user_in($_POST['first_name'],$_POST['password'])) {
redirect_user('page.php');
} else {
// echo some deny message...
}

how to stop duplicate values from being written to text file using php

i have a script that keeps reloading every 2 seconds, i made a code to create a txt file for each user IP and write the user name $name inside it. my problem is that everytime my script reloads it will write the $name of the specific IP again with every reload.
the code is
$ip_file = "ips/".$ip.".txt";
$logip = fopen($ip_file,"a", 1);
$name = $name."\n";
fwrite($logip, $name);
fclose($logip);
return;
i need some way to verify if the name is already in the $ip_file and if it's there then not to write it again.
the idea behind this is to check if the same IP is used by more than one $name and then create a function to check all the $ip_file files for more than 1 $name and if so ban the violating $ip
thanks in advance
$ip_file = "ips/".$ip.".txt";
$names = file_get_contents($ip_file); //read names into string
if(false === strpos($names,$name)) { //write name if it's not there already
file_put_contents($ip_file,"$name\n",FILE_APPEND);
}
Is this what you need?
<?php
$ip_file = "ips/".$ip.".txt";
$name = $name."\n";
if (file_exists($ip_file)) {
$valueInFile = file_get_contents($ip_file, true);
if ($valueInFile == $name) {
//Do something
}
} else {
$logip = fopen($ip_file,"a", 1);
fwrite($logip, $name);
fclose($logip);
}
return;
?>
From:
http://php.net/manual/en/function.file-exists.php

get json data in function php

I am new in this json chapter.I have a file named mysql_conn.php .This file have a php function to call data from mysql database.So can anyone help me to create one json file to get data from mysql_conn.php.Below is my code
mysql_conn.php
function getWrkNoTest($wrkno){
$conf = new BBAgentConf();
$log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(), $conf->get_BBLogPriority() );
$connection = MySQLConnection();
$getWrkNoTest ="";
$lArrayIndex = 0;
$query = mysql_query("
SELECT
a.jobinfoid,
a.WRKNo,
a.cate,
a.det,
a.compclosed,
a.feedback,
a.infoID,
b.callerid,
b.customername
FROM bb_jmsjobinfo a
LEFT JOIN bb_customer b
ON a.customerid = b.customerid
WHERE a.WRKNo = '$wrkno';"
);
$result = mysql_query($query);
$log->LogDebug("Query[".$query."]");
while ($row = mysql_fetch_array($result)){
$getWrkNoTest = array("jobinfoid"=>$row['jobinfoid'],
"WRKNo"=>$row['WRKNo'],
"cate"=>$row['cate'],
"det"=>$row['det'],
"compclosed"=>$row['compclosed'],
"feedback"=>$row['feedback'],
"infoID"=>$row['customerid'],
"customerid"=>$row['infoID'],
"callerid"=>$row['callerid'],
"customername"=>$row['customername']);
$iList[$lArrayIndex] = $getWrkNoTest;
$lArrayIndex = $lArrayIndex + 1;
}
$QueryResult = print_r($getWrkNoTest,true);
$log->LogDebug("QueryResult[".$QueryResult."]");
closeDB($connection);
return $iList;
}
json.php
if ($_GET['action']=="getJsonjms"){
$wrkno = $_GET["wrkno"];
if($wrkno != ""){
$jms = getWrkNoTest($wrkno);
if(!empty($jms)){
echo json_encode($jms);
}else{
echo "No data.";
}
}else{
echo "Please insert wrkno";
}
}
I dont know how to solve this.Maybe use foreach or something else.Sorry for my bad english or bad explanation.I'm really new in this json things. Any help will appreciate.Thanks
If I understand your question right, you want to convert the results you receive from your MySQL query into JSON and then store that data into a file?
If this is correct, you can build off of what you currently have in json.php. In this block here, you use json_encode():
if(!empty($jms)){
echo json_encode($jms);
}
We can take this data and pass it to file_put_contents() to put it into a file:
if (!empty($jms)) {
$json = json_encode($jms);
// write the file
file_put_contents('results.json', $json);
}
If this is a script/page that's visited frequently, you'll want to make the filename (above as results.json) into something more dynamic, maybe based on the $wrkno or some other schema.

How to manage HTML special characters stored in an array

I have the $user array that contains data with special characters. It seems like each element of $user that contains special characters can't render properly after they are stored in a session.
Here is my code:
<?php
session_start();
include_once('../application/classes/DataLayer.class.php');
$dl = new DataLayer();
$user = $dl->doLogin($_POST['email_sub'], $_POST['password_sub']);
if(isset($user)) {
foreach($user as $detail_array => $detail){
$fn = html_entity_decode($user['fn']);
$ln = html_entity_decode($user['ln']);
}
var_dump($fn, $ln); // $fn and $ln display well here
$_SESSION['user'] = $user;
$_SESSION['fn'] = $fn;
$_SESSION['ln'] = $ln;
var_dump($_SESSION['fn'], $_SESSION['ln']); // $_SESSION['fn'], $_SESSION['ln'] display well here too
}
else {
//do something here
}
?>
Any help would be appreciated. Sorry for my bad english.
Use the function from this link https://stackoverflow.com/a/8454838/997178 to encode the data for output
Use encode_output_vars function , param $vars is your session data ... return value will be a single element encoded for output or an array with all elements encoded , depending what your parameter is .
Or just use php function htmlentities for your session data before you output it . Here is link http://php.net/manual/en/function.htmlentities.php

Categories