PHP explode string, concat with search url and echo it - php

I have names of actors in variable $actor
Example:
Actor One, Actor Two,Someone
I need to split the string per person. I figured I'd use explode to get something like this:
[0] => Actor One
[1] => Actor Two
[2] => Someone
Then I need to build search links in following format:
http://site.com/?s=Actor+One
http://site.com/?s=Actor+Two
http://site.com/?s=Someone
And finally echo it like this:
<a href='http://site.com/?s=Actor+One'>Actor One</a>, <a href='http://site.com/?s=Actor+Two'>Actor Two</a>, <a href='http://site.com/?s=Someone'>Someone</a>
I'm just totally lost in PHP syntax. Help is appreciated.

(this is homework, isn't it?)
Anyway:
// $actors is an array with the names
$actors = explode(',', $actor);
foreach ($actors as $name) {
$e_name = urlencode($name);
print "" . htmlentities($name) . "";
}

<?php
$arr = array('Actor One','Actor Two','Someone');
foreach($arr as $value){
echo ''.htmlentities($value).'';
}
?>
Oops url encoding.. my bad!

Just to post a safe version that works independently of whether the array content has been maliciously prepared:
$cs = "UTF-8";
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", $cs);
/* ... */
foreach($actor as $name)
{
print('<a href="http://site.com/?s=' . htmlentities(urlencode($name), ENT_QUOTES, $cs)
. '">' . htmlentities($name, ENT_QUOTES, $cs) . '</a>');
Probably best to include the encoding as well, after all your array could contain all sorts of characters.

There are lots of steps to what you need to do:
explode the string into an array (as you did)
Create and echo the links with those urls
When the actor name goes into a url, remember to rawurlencode it
When it goes into HTML, remember to htmlspecialchars it
So the above can be translated into this code:
$actors = explode(',', $actor);
foreach($actors as $actor) {
printf('<a href=\'http://site.com/?s=%s\'>%s</a>',
rawurlencode($actor),
htmlspecialchars($actor));
}

Related

get all categories listing from database

Main purpose is to get all categories listing from database by passing variables to url and show it to the main page.here i have omitted some code bt i tried to clarify.
1.can I exclude encodeHtml() method, too difficult for me to understand
2.i am not getting specially this part of code and having my head for 4 days
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";//here id is 'category id' from database. this full line will echo what?
echo Helper::getActive(array('category' => $cat['id']));//it will output what ?
echo ">";
echo Helper::encodeHtml($cat['name']);//as from ur answer can we omit encodeHTML() method and use htmlspecialchars($cat['name']); instead ?
echo "</a>
3.any easier solution will be more appreciated
in our database we have 'id' and 'name' of catagory listing
please check below for reference
/*below is the code in header section of template */
<?php
$objCatalogue = new Catalogue();// creating object of Catalogue class
$cats = $objCatalogue->getCategories(); // this gets all categories from database
<h2>Categories</h2>
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
/*below is the helper class which is Helper.php */
public static function getActive($page = null) {
if(!empty($page)) {
if(is_array($page)) {
$error = array();
foreach($page as $key => $value) {
if(Url::getParam($key) != $value) //getParam takes name of the parameter and returns us the value by $_GET
{
array_push($error, $key);
}
}
return empty($error) ? " class=\"act\"" : null;
}
}
//CHECK THIS LINE BROTHER
return $page == Url::currentPage() ? " class=\"act\"" : null;// url::currentPage returns the current page but what is 'class =act ' :(
}
public static function encodeHTML($string, $case = 2) {
switch($case) {
case 1:
return htmlentities($string, ENT_NOQUOTES, 'UTF-8', false);
break;
case 2:
$pattern = '<([a-zA-Z0-9\.\, "\'_\/\-\+~=;:\(\)?&#%![\]#]+)>';
// put text only, devided with html tags into array
$textMatches = preg_split('/' . $pattern . '/', $string);
// array for sanitised output
$textSanitised = array();
foreach($textMatches as $key => $value) {
$textSanitised[$key] = htmlentities(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
foreach($textMatches as $key => $value) {
$string = str_replace($value, $textSanitised[$key], $string);
}
return $string;
break;
}
}
Firstly, in your URL (/?page=catalogue&category=) you don't need to put &, as this is an HTML entity for actually displaying an ampersand in a web page. Just use /?page=catalogue&category=.
Secondly, you can use urlencode() to prepare strings for sending in the URL, and urldecode() on the other end.
In answer to your first point you just need to make sure that ANYTHING from the user (whether via $_POST or $_GET) is sanitized, prior to being used in code, output to a web page, or used in database queries. Use htmlspecialchars() for cleaning before outputting to a web page, and prepared statements prior to entering user input into a query.
In answer to your second point please read the documentation in the links I have provided above. Just reading the documentation on htmlspecialchars() will help you a lot.
Hope this helps.
Alright then.
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
Im just going to kindof skim through it, because honestly if you really want to learn all this you should probably google the shit out of every piece of code you don't understand, it's the way we all learn things.
< ?php announces some php script to follow. And as you can see, there does follow some php code after.
foreach is a way of getting each element from an array or list and doing something to that element.
echo sends whatever string comes after it to the page, or whatever is listening to its output. In this case, it looks like the echo's are printing some <li> list item with an <a> anchor in it.
Helper::getActive(): Helper is some class that is defined somewhere, :: is syntax for calling a static function that belongs to the class (Helper in this case). getActive is the function name.
array('category' => $cat['id'] is a piece of code that creates an array with 1 element in it, being one with key 'category' and a value of whatever is in $cat['id'].
By looking at getActive: it looks like it's a function that checks the url for some value so it can determine which page to display. It also checks if the url contains errors.
By lookingat encodeHtml(): it looks like it's a function that makes sure that whatever text you're trying to put on the screen, isn't something that could cause harm. In some situations, people will try to make your server print javascript that could harm the user (by sending personal data to somewhere). The encodeHtml() will ensure that no such thing can be done by stripping certain characters from the text you're about to send to the page.
USE GOOGLE.

Get values from URL using GET from encode UTF-8

let me start by saying that I have no idea how to formulate this question, I have spend the last two days looking for some ways to to the following.
I send some information encoded using base64 as follow....
Values are:
Lóms Gruñes
this values came from an input box
beacuse of that I do this
$name = htmlentities(( $_POST ['name'] ) , ENT_NOQUOTES, 'UTF-8');
$midn = htmlentities(( $_POST ['midn'] ) , ENT_NOQUOTES, 'UTF-8');
the output for this should be
Lóms Gruñes
And that is what gets encode, until that everything is fine, and I can do whatever I need with that, in this case I'm going to encode it using base64
$datas ='&name='. $name .'&midn='. $midn;
$bd = base64_encode($datas);
// Now lets send that info to another file..
header( 'Location: other.php?d=$db' ) ;
So the url will be something like
domain.com/other.php?d=TCZvYWN1dGU7bXMgR3J1Jm50aWxkZTtlcw==
So now lets decode it so that it can be saved...
$ds = base64_decode($_GET['d']);
parse_str($ds, $params);
$name = htmlentities($params['name'], ENT_NOQUOTES);
$midn = htmlentities($params['midn'], ENT_NOQUOTES);
It looks pretty straight forward isn't it... but here is the problem because when I try to use the values nothing happen... lets say I just want to echo it...
echo $name . '<br>';
echo $midn;
What I get is
L
Gru
so where is the ó and the ñ?
ok, let say I don't encode anything so the URL will look like this...
domain.com/other.php?name=Lóms&midn=Gruñes
// and the I use echo like this:
echo $_GET['name'] . '<br>';
echo $_GET['midn'];
// the output is
L
Gru
Even if I put : header ('Content-type: text/html; charset=utf-8'); after the <?php ... nothing happen... so, the question... how can I get the ó as a value or better yet, how can I send the í,ó,ñ,á...etc as is in the url domain.com/file.php?data=íÄÑó and retrive it as is and save it as is and display it as is...
I;m not sure if this has some relevant information, the data is going to be saved in a DB, the DB is InnoDB, utf8_general_ci
Thank you for taking the time...
Always escape/encode for the technology you're using.
To get the UTF-8 encoded values from the form submission:
$name = $_POST['name'];
$midn = $_POST['midn'];
To output those into HTML:
<p><?php echo htmlspecialchars($name, ENT_COMPAT, 'UTF-8'); ?></p>
To embed them in a URL:
$url = sprintf('foo.php?name=%s&midn=%s', rawurlencode($name), rawurlencode($midn));
// or
$url = 'foo.php?' . http_build_query(array('name' => $name, 'midn' => $midn));
In foo.php, to get the values back:
$name = $_GET['name'];
$midn = $_GET['midn'];
And again, to output those into HTML:
<p><?php echo htmlspecialchars($name, ENT_COMPAT, 'UTF-8'); ?></p>
And that's basically all you need to do. Always escape values using the right function for the medium, don't escape more or earlier than you need to.
First of all, if you want to decode htmlentities try html_entity_decode().
For encoding the url try urlencode().
Example from php.net:
<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>
Hope it helps!
May be this will work for you . Instead of using htmlentites I used rawurlencode and rawurldecode function .
Below is same code
First get the values from the
$name = rawurlencode('Lóms Gruñes'); use can use //( $_POST ['name']
$mid = rawurlencode('Gruñes'); and here ($_POST ['midn'] )
then
echo $datas ='name='. $name .'midn='. $midn;
$en = base64_encode($datas);
Append this on next url . Then get the value and decode it using base64_decode function
$dd = base64_decode($en);
parse_str($dd);
echo $name;
echo $midn;

GET_CONTENT name from txt file

i have this list on name.txt file :
"name1":"Robert"
"name2":"George"
"name3":"Flophin"
"name4":"Fred"
in a web page i need a php code that takes only the name of the person by the name 1 2 3 4 id.
I've use this in test.php?id=name2
$Text=file_get_contents("./name.txt");
if(isset($_GET["id"])){
$id = $_GET["id"];
$regex = "/".$id."=\'([^\']+)\'/";
preg_match_all($regex,$Text,$Match);
$fid=$Match[1][0];
echo $fid;
} else {
echo "";
}
The result should be George ,
how do i change this to work??
Mabe is another way to do this more simply?
$file=file('name.txt');
$id = $_GET["id"];
$result=explode(':',$file[$id-1]);
echo $result[1];
Edit: $result[1] if you want just name.
Heres an ugly solution to your problem, which you can loop trough.
And Here's a reference to the explode function.
<?php
$text = '"name1":"Robert"
"name2":"George"
"name3":"Flophin"
"name4":"Fred"';
$x = explode("\n", $text);
$x = explode(':', $x[1]);
echo $x[1];
Load the text file into an array; see Text Files and Arrays in PHP as an example.
Once the array is loaded you can reference the array value directly, e.g. $fid = $myArray['name' . $id]. Please refer to PHP how to get value from array if key is in a variable as an example.

preg_replace_all() related issue

I am currently making a BBCode class for my website.
I need to do the following.
function bbCode([skill]Q[/skill]_________[skill]Q[/skill]_________[skill]Q[/skill]);
bbCode function has to replace all Q's between [skill] and [/skill] tags, and replace it with $skillArray['Q'] value. ($skillArray is character dependant.)
How can I do this?
A little clearer version is:
For example you're on a page of "Orc" character.
[skill]Q[/skill] tag should get "Orc's Q skill name" automatically.
For example you're on a page of "Hunter" character.
[skill]Q[/skill] tag should get "Hunter's Q skill name" automatically.
Ps. Don't want to use explode.
Assuming the tags you want to be replaced are within some form of template, you could use file_get_contents and then loop through the tags you want to replace with the desired values, for example:
$file = file_get_contents ( 'yourfile.php' );
$skillArray = array ( 'Q' => 'Hunter name' );
foreach ( $skillArray as $key => $val )
{
$file = str_replace ( '[skill]' . $key . '[\skill]', $val, $file );
}
Thats just a completely rough example, but if I'm understanding what you are trying to do; that should be along the right lines....
This is what you need
$data = "[skill]Q[/skill]_________[skill]Q[/skill]_________[skill]Q[/skill]";
$r['Q'] = "Yahoo";
function b($a){
global $r;
return $r[$a[1]];
}
$data = preg_replace_callback('|\[skill\](Q)\[\/skill\]|', 'b' , $data);
var_dump($data);
If you want to replace all the Qs with single "Yahoo" use Q+ instead of Q. If you want to match all words use \w+.
<?php
$skillArray=array('Q'=>'fishing');
$txt="test [skill]Q[/skill] test";
$txt=preg_replace("#\[skill\](.*)\[\/skill\]#e",'$skillArray["$1"]',$txt);
echo $txt; //test fishing test
?>

removing items from url strings in PHP

I would appreciate some help here:
What I want to do:
remove &itemsperpage=10 from:
http://localhost/thi/search/filter.html?type=featured&page=2&itemsperpage=10
and create a link from it:
http://localhost/thi/search/filter.html?type=featured&page=2&itemsperpage=15
here's what I have come up with so far:
<a href="<?php echo url::site(url::current()) . http_build_query($_GET) // don't know what follows ?>"
the framework functions I'm using are:
url::current() = returns current url in controller/action format
url::site() = returns absolute url i.e http://localhost/site/controller/action
so I have to remove '&itemsperpage' from the resulting string in the http_build_query function
but I am having trouble with character encodings and such! please help!
so here's the problem with character encoding:
$needle = '&itemsperpage';
$querystring = http_build_query($_GET) . '<br/>';
// echo $querystring . '<br/>';
$pos = strpos($querystring, $needle);
$remove = substr($querystring, ((int)$pos));
echo substr(str_replace($remove, '', $querystring), 1); // returns ';'
I can't remove the string '&itemsperpage' from the result of http_build_query which is:
'type=featured&page=2&itemsperpage=10' and functions like strstr outputs nothing
I would just do this:
$array = $_GET;
$array['itemsperpage'] = 15;
Then just use your code, but with the new variable (and the ?):
<a href="<?php echo url::site(url::current()) . '?' . http_build_query($array)">
The HttpQueryString class has several methods for getting, setting, modifying query strings and 'translating' their charsets.
You can achieve the effect you're looking for by removing the itemsperpage element from the $_GET array before building the query string.
unset($_GET['itemsperpage']);
And then just use the code you already wrote:
<a href="<?php echo url::site(url::current()) . http_build_query($_GET); ?>">
EDIT: I misread your post. I thought you only wanted to remove the field / value pair from the GET request. All you have to do is overwrite the value with the value you want:
$_GET['itemsperpage'] = 15;
And then use the code you already wrote.

Categories