GET string from user and process it - php

I am getting input from user and performing filter on that input text.
Here is the example : CODE
Problem with this is when I take $s statically it works fine, but when I pass it in this way:
http:/mylocalpi/phone_filter.php?text=%27my%20long%20STRING%20with%20124%20mynumberis%208989243three56%20some%2040one34two3473%27
And get
$s = $_GET['text']; //
// $s = "my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533"; this works fine
Then it does not filter last word. can some one tell what can be issue here?

use this
$s = urldecode($_GET['text']);

As far as I can tell, there is a lack of similarity between the string you use in the constant and the one you send through the URL:
Constant:
$s = "my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533";
URL:
$s = "'my long STRING with 124 mynumberis 4054545456 8989243three56 some Numbers 402three1345233nine3 5023one34533'";
Because your URL looks like this:
?text=%27…%27
Which is the same as
?text='…'
As you can see you send an extra pair of ' (%27) that surround your string, you don't need them. Try and see what happens if your static version of the string starts and ends with those '. Your URL should look like this:
?text=my%20long%20STRING%20with%20124%20mynumberis%204054545456%208989243three56%20some%20Numbers%20402three1345233nine3%205023one34533
Without any leading or trailing ' (%27).
It's either that, or try to fix your filter to ignore the ' while processing the string. This is most certainly the cause.

Related

Insert a value in a string and check right position

I'm trying to figure out a way to solve my problem:
I receive a string like "Hello world.\nHi" and a certain position where I have to add a char.
So the problem is that the position is for a string without \n and I need to find out a way to count those '\n' and define how many '\n's are there before position to increment it.
Here's an example:
$string="Hi\nThis is\na test";
$position=7;
$value=0;
//CODE
$correct_result="Hi\nThis 0is\na test";
$wrong_result="Hi\nThi0s is\na test";
So basically I just need a way to check how many '\n's are there before the position
I solved by using substr from 0 to $position and using count to check if there where "\n"

PHP variables look the same but are not equal (I'm confused)

OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.

Codeigniter - Character Limiter not working

I am echoing a users first name in the header. I have a test first name with many characters.
For eg:
$firstname = "asdfasdfasdfjkljldkafjsddfjakdsjflaksjdfl"
I'm doing
<?php $first_name = character_limiter($first_name, 10);
echo $firstname;?>
But It's not working. It displays all the characters (asdfasdfasdfjkljldkafjsddfjakdsjflaksjdfl) instead of only first 10 characters.
I only want to see teh first 10 characeters. How can I fix this?
Use $firstname as first parameter instead of $first_name (which initially contains nothing) while using character_limiter() function
$firstname = "asdfasdfasdfjkljldkafjsddfjakdsjflaksjdfl";
$first_name = character_limiter($firstname, 10); // limits $firstname to 10 chars and outputs to $first_name
echo $first_name;
In case that was a typo error while you posted your question, then problem might be with loading of Text Helper in Codeigniter which is required for using this function (CI Text Helper).
You can load Text Helper by specifying it in application/config/autoload.php like this:
$autoload['helper'] = array('text');
Or by loading it specifically in a Controller function like this:
$this->load->helper('text');
UPDATE :
Codeigniter maintains "the integrity of words so the character count may be slightly more or less then what you specify" (ref. CI Text Helper)
Let me explain you this by an example:
$firstname = "asdfasdfasdfjkljldkafjsddfjakdsjflaksjdfl"; //contains only single word
$first_name = character_limiter($firstname, 10);
Here, CI tries to limit $firstname to 10 chars but since, it encounters a word, it will not try to break it instead it outputs till the end of the word.
Now say you had used,
$firstname = "asdfa sdfasdfj kljldkafjsddfjakdsjflaksjdfl sdjbfsdufb";
This contains three words, so the output will be asdfa sdfasdfj…
Note that here too the limited string contains more than 10 chars but since CI tries to maintain word integrity, it does not break the last word.
If you need to strictly limit input string by character, then, you'll have to use the inbuilt php function substr() as described by Hudixt.
Yes character_limiter() function does not work for longer word to prevent word break and/or distort meaning.
According to codeigniter documentation, it will not try to break long word to maintain its integrity.
As per documentation of
character_limiter
Truncates a string to the number of characters specified. It maintains the integrity of words so the character count may be slightly more or less than what you specify.
but codeigniter does not stops you from limiting exact character, ahead it mentions in note
If you need to truncate to an exact number of characters please see the ellipsize() function below.
so instead of character_limiter() you can use ellipsize() function and it will do exact same.
Hope it help.
Try this,it will fix your issue.
$this->load->helper('text');
$string = "your text here";
$string = character_limiter($string, 10);
echo $string;
Output:your text…
You can also use substr() for this purpose.If you want to add ... after 10 character then take the help of strlen(). Use the code below
<?php
if(strlen($first_name)>10){
$first_name = substr($first_name,0, 10)."...";
}
else{
$first_name = substr($first_name,0, 10);
}
echo $first_name;
?>
Hope this helps you

PHP get request returning nothing

Using window.location.hash (used to pass in ID for page) returns something like the following:
Also, for people asking why I used window.location.hash instead of window.location.href is because window.location.href started looping infinitely for some reason, and .hash does not. I don't think this should be a big deal, but let me know if it is and if I need to change it.
http://website.com/NewPage.php#?name=1418019307305
[The string of numbers is actually epoch system time]
When using PHP to try to retrieve this variable It is not picking up any text in the file It's supposed to write to.
<?php
$myfile = fopen("File1.txt","w");
echo $_GET['name'];
fwrite($myfile, $_GET['name']);
fclose($myfile);
?>
Try to print $_SERVER variable and it will give you the array and in the desired key you can get the values. It can help you to find that variable in the string.
If you want to get the value after the hash mark or anchor, that isn't possible with "standard" HTTP as this value is never sent to the server. However, you could parse a URL into bits, including the fragment part, using parse_url().
This should do the trick:
<?php
$name_query = parse_url("http://website.com/NewPage.php#?name=1418019307305");
$get_name = substr($name_query['query'], strpos($name_query['query'], "=") + 1);
echo $get_name;
?>
Working example: http://codepad.org/8sHYUuCS
Then you can use $get_name to store "name" value in a text file.
The hash tag is a fragment that never gets processed by the server, but rather the user-agent, i.e. the browser, so JavaScript may certainly access it. (See https://www.rfc-editor.org/rfc/rfc3986#section-3.5). PHP does allow you to manipulate a url that contains a hash tag with parse_url(). Here's another way to get the info:
<?php
$parts = parse_url("http://website.com/NewPage.php#?name=1418019307305");
list(,$value) = explode("=",$parts['fragment']);
echo $value; // 1418019307305
The placement of the hash tag in this case wipes out the query string so $_SERVER['QUERY_STRING'] will display an empty string. If one were to rewrite the url following best practice, the query string would precede the hash tag and any info following that mark. In which case the script for parsing such a url could be a variation of the preceding, as follows:
<?php
$bestPracticeURL = "http://website.com/NewPage.php?name=1418019307305#more_data";
$parts = parse_url( $bestPracticeURL );
list(,$value) = explode("=", $parts['query']);
$hashData = $parts['fragment'];
echo "Value: $value, plus extra: $hashData";
// Value: 1418019307305, plus extra: more_data
Note how in this case parse_url was able to capture the query string as well as the hash tag data. Of course, if the query string had more than one key and value, then you might need to explode on the '&' into an array and then explode each array element to extract the value.

Add ' \ ' before " ' " of a string variable in javascript

I have a javascript variable which hold the value taken from somewhere else(lets say from a API call), taken string is given bellow,
He's the reason for this
I assign this string to a variable name 'sample'. But when I print it, it doesn't work since the string has " ' " character. I want to add " \ " before the " ' " character. I tried using this,
var sample = (get the string from a api call).replace(/'/g,"\\\'");
But it doesn't work?
in my javascript file I use window.location.href = "test.php?detail="+sample; to send the data.
Use encodeURIComponent to escape a string for inserting into a URI.
In my test.php, I use $detail = $_GET["detail"]; and echo $detail; to print it.
If you are printing it into HTML then use htmlspecialcharsto make it safe.
If you are printing it into JavaScript then use json_encode to make it safe.
You're overdoing the escape characters:
var sample = (get the string from a api call).replace(/'/g,"\\'");
Is enough, a single quote, delimited by double quotes needn't be escaped, so just escape one backslash.A sidenote, though: if the string you're checking is a return value, the single quotes shouldn't be a problem (if they are, the api code would break before returning the string). If you really really really want to be extra-super-mega-sure and the string is long:
var sample = (get the string from a api call).split('\'').join('\\\'');
//or (to avoid confusion with all that escaping
var sample = (get the string from a api call).split("'").join("\\'");
Splitting is faster for longer strings (not short strings, as the array constructor is called, an array-object is created, looped,...)
Presumably the problem is with (get the string from a api call). If you have some server-side code (PHP?) like this:
var sample = <?php echo $mystring ?>.replace(…);
…and it produces output sent to the browser like this:
var sample = 'my dad's car'.replace(…);
…then your server-side code has produced syntatically-invalid JavaScript that cannot be fixed by more JavaScript. Instead you need to fix it on the server, something like:
var sample = <?php echo json_encode($mystring); ?>;
It's impossible to help you further without your actual code details, however.

Categories