Not able to remove backslash from below code? - php

below is my code the issue is that when i enter any username with apostrophe (') Additional character "\ backslash" is being displayed when Search results are returned.
Below is my code i find that a function addslashes is used in the checkusername function so backslash is getting added.
if ( 0 < count( $my_field_place ))
{
for ( $i = 0; $i < count( $my_field_place ); $i++ )
{
if ( true === isset( $Fields[$i] ))
{
print "gMapping[$i] = new MappingItem( '" .
addslashes( $Fields[$i] ) .
"', '" .
checkusername( $my_field_place[$i] ) .
"' );";
}
}
}
function checkusername($inStr)
{
$orig = array();
$new = array();
$orig[00] = "/\n/`" ; $new[00] = "\\?n";
$orig[01] = "/[^\x-*()]/"; $new[01] = "";
$var1 = preg_replace($orig, $new, $inStr);
$var2 = addslashes($var1 ); // i am not sure why addslashes is used but i am asked not to remove because of security reasion?
return $var2;
}
Note: I google and find that it used for security reason
Since in my case we are only displaying the searched result. So i am not sure why this function is used here.
My fix is to add stripslashes() function before returning which will removes backslashes added by the addslashes() function.
Please find the code snippet and the comment for code change below:
function checkusername($inStr)
{
$orig = array();
$new = array();
$orig[00] = "/\n/`" ; $new[00] = "\\?n";
$orig[01] = "/[^\x-*()]/"; $new[01] = "";
$var1 = preg_replace($orig, $new, $inStr);
$var2 = addslashes($var1);
return stripslashes($var2); // i am not sure stripslashes is correct fix or not?
}
Please help is it fine to added stripslashes or is there any other way to handle it ?

You can restrict user from those special characeter
though in gmail ,yahoo,fb etc they will never
allow this character.since t allows multiple words to be represented in a somewhat readable manner
below are some doc
https://support.google.com/a/answer/33386?hl=en
see second guidelines

Related

PHP Smalot PdfParser get certain section

I need help about PHP Smalot\PdfParser. https://github.com/smalot/pdfparser
Does anybody know how to get or access certain section.
Example. Invoice and want to get access to items/products object section as Object/Array
getText method works but retrieves all the text on invoice.
Thanks alot!
You could use some loop like this:
$metaData = $pdf->getDetails(); //Gets PDF metadata
$xtargetTextCoordinate = "12.345" ///////////USE YOUR OWN
$ytargetTextCoordinate = "678.90" ///////////USE YOUR OWN
//Going through each PDF's page...
for ($x=0 ; $x < $metaData['Pages']; $x++ ){
//Reset variables
$streamOfThisPage = [];
$streamOfThisPage = $pdf->getPages()[$x]->getDataTm();
$targetText= "";
//Going through each key element of this page...
foreach($streamOfThisPage as $arrayEle){
if( ($arrayEle[0][4] == $xtargetTextCoordinate ) && ($arrayEle[0][5] == $ytargetTextCoordinate ) ){ //X & Y depend of your document structure...
$targetText = "";
//Remove unecessary data if any
$thisRowWords = explode(" " , $arrayEle[1] );
$referencePeriod = $thisRowWords[0];
foreach($thisRowWords as $position => $word){
$targetText = $targetText . $word . " ";
}
}
}
echo $targetText;

php strpos and approximate match with 1 character difference

I searched the system but couldn't find any help I could understand on this, so here goes...
I need to find an approximate match for a string in php.
Essentially I'm checking that all the $names are in the $cv string and if not it sets a flag to true.
foreach( $names as $name ) {
if ( strrpos( $cv, $name ) === false ) {
$nonameincv = true;
}
}
It works fine. However, I had a case of $cv = "marie_claire" and a $name = "clare" which set the flag (of course) but which I'd have liked for strpos to have "found" as it were.
Is it possible to do an approximate match so that if a string has 1 extra letter anywhere in it, it would match? For example so that:
$name = "clare" is found in $cv = "marie_claire"
$name = "caire" is found in $cv = "marie_claire"
$name = "laire" is found in $cv = "marie_claire"
and so on...
Note: This will work perfectly fine when there is difference of 1 character, as stated in question above.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$stringToSearch="mare";
$wholeString = "marie_claire";
$wholeStringArray= str_split($wholeString);
for($x=0;$x<strlen($wholeString);$x++)
{
$tempArray=$wholeStringArray;
unset($tempArray[$x]);
if(strpos(implode("", $tempArray), $stringToSearch)!==false)
{
echo "Found: $stringToSearch in ".implode("", $wholeStringArray);
break;
}
}
Try this, not considering performance, but would work for your case.You can play with the the number of different chars deviation you want to accept.
$names = array("clare", "caire", "laire");
$cv = "marie_claire";
foreach( $names as $name ) {
$sname = str_split($name);
$words = explode('_', $cv);
foreach($words as $word) {
$sword = str_split($word);
$result = array_diff($sword, $sname);
if(count($result) < 2)
echo $name. ":true\r\n";
}
}

PHP replace a character in string fetched from mysql

I'm trying to replace a string which contains value with operator : like "2456:72" to "2456.72" where data is fetched from mysql, I tried using str_replace which sucks. $row_loop3["Tot_minutes"] is the row which I should replace the character, please find my code:
$mysqli = new mysqli("172.16.10.102", "******", "RND#ISO-3306", "eTrans");
if (!$mysqli->multi_query("call sp_get_Android_Online_minutes_Chart ('2015-01-01','2016-01-30')")) {
$response["success"] = 0;
}
do {
if ($res_loop3 = $mysqli->store_result()) {
$response_loop3["minutes"] = array();
$find = ":";
$re = ".";
while ($row_loop3 = $res_loop3->fetch_assoc()) {
$j = 5;
$value_loop3 = array();
$value_loop3["File_Day"] = $row_loop3["edit_date"];
$value_loop3["File_Minutes"] = $row_loop3["FileDay"];
$val["Tot1_Minutes"] = $row_loop3["Tot_minutes"];
$value_loop3["Total_Minutes"] = str_replace($val, $find, $re); //value which I should replace : with .
array_push($response_loop3["minutes"], $value_loop3);
$response_loop3["success"] = 1;
}
echo $merger = json_encode(array_merge($response, $response_loop2, $response_loop3));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
please help me, thanks in advance
You are not making variable instead you are making associative array.
change this
$val["Tot1_Minutes"] = $row_loop3["Tot_minutes"];
to
$val= $row_loop3["Tot_minutes"];
and also order in str function to
$val = $row_loop3["Tot_minutes"];
$value_loop3["Total_Minutes"]=str_replace($find,$re,$val);
str_replace should be used in this way:
str_replace( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
The function's argument are search, replace, and subject, so for your case should be like : str_replace($find,$re,$val)

Change portion of value within an array knowing only part of string and restric

Before I got this answer
preg_replace("~(?<=$str&&).*~", '7', $str);
which is good but what if within the array I have a similar string mary&&5 and rosemary&&5 and I stricktly want to change only mary&&5 and not disturb the other array, is it posible? and how?
The question before was:
`$array = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8", etc..);`
and I know only the string before && which is username. $str = "mary&&"; Note that I don't know what is after &&
I want to know whether exist or not within the array, and if exist change the value to something new like mary&&7
`$isExists = preg_replace("some","some", $array);
if ($isExists){
echo "Its exists";
} else {
echo "Not exixts"
} ;`
How can I change the portion of the value after && in mary&&5 or completely change mary&&5 to mary&&7 since I don't know before hand the value mary&&5?
Thanks for your answer :)
`$name = "mary";
$res = "7";
$str = array("josh&&3", "mary&&5", "cape&&4", "doggy&&8","rosemary&&5");
for ($i = 0; $i < count($str); ++$i) {
$r = preg_replace("~(?<=$name).*~",$res, $str);}`
$arr = array('josh&&3', 'mary&&5', 'cape&&4', 'doggy&&8', 'rosemary&&5');
$name = 'mary';
$number = '7';
$replacement = $name . '&&' . $number;
So, a way without regex:
foreach($arr as $k=>$v) {
if (explode('&&', $v)[0] === $name)
$arr[$k] = $replacement;
}
( or you can use strpos($v, $name . '&&') === 0 as condition)
a way with regex:
$arr = preg_filter('~\A' . $name . '&&\K.*~', $number, $arr);
(where \K removes all on the left from the match result, so the name and && aren't replaced)

php - foreach loop - correct (most efficient way to handle a first case scenario )

I have a function that builds a MySQL query from the supplied arguments. My current code is:
($args can be an empty array or up to a set of 5 field_names=>array_of_ids ...)
if( !(empty( $args )) )
{
$flag = 0;
$sql_append = '';
foreach( $args as $field_name => $id_array )
{
if( $flag == 0 )
{
$where_connector = " WHERE ";
$flag = 1;
}
else
{
$where_connector = " AND ";
}
${ $field_name . '_string'} = join(',',${ $field_name . '_ids'});
$sql_append .= $where_connector . 'link_id IN ($ids)";
}
}
I'm self-taught and so constantly worry about best practices. I seem to remember some sort of function that handles arguments, perhaps in a way that can be applied here more efficiently. Any ideas?
To neatly construct your WHERE $fieldname IN($ids) clauses from a $fieldname=>$id_array array, you can try this :)
function buildWhereIns(array $args)
{
if(!is_array($args) || empty($args)) return "";
$ids = array_map(function($item){
return implode(',',$item);
}, array_values($args));
$fields = array_map(function($item,$id){
return $item.' IN('.$id.') ';
}, array_keys($args),$ids);
return = count($fields) > 0 ? count($fields) > 1 ? " WHERE " . implode(' AND ', $fields) : " WHERE " . array_shift($fields) : "";
}
I would say that the larger issue here is that you should be using some sort of technique to protect your code against SQL injection. For example, PHP's built-in PDO classes provide a really easy way to do this: http://www.php.net/manual/en/pdo.prepared-statements.php.
In general, though, if you want a loop that behaves differently on the first or last iteration, your method isn't bad. The other obvious method is to just do the first (or last) iteration outside the loop, and then perform the iterations which are the same inside the loop body.

Categories