I have a site that offers a keyword search. The user can perform a search by either selecting from a set of pre-defined keywords displayed as hyperlinks or utilize a search form on the same page.
When the user searches for Russian Blue Cat, the following is added to the page URL:
If using the pre-defined hyperlink search term, then ?keywords=Russian%20Blue%20Cat is added to the URL as follows:
http://mydomain.com/index.php?keywords=Russian%20Blue%20Cat
If using the search form, then ?keywords=Russian+Blue+Cat is added to the URL as follows:
http://mydomain.com/index.php?keywords=russian+blue+cat
The following $_GET line of code is placed within two PHP files, the original index.php file that contain both the pre-defined hyperlink search terms and the search form and another PHP file called process.php that utilizes the keywords for another process.
if(empty($_GET['keywords'])){$keywords = '';} else {$keywords = $_GET['keywords'];}
The above $_GET line of code contained within the index.php file works properly and retrieves all three keywords. In this case the words Russian Blue Cat is retrieved.
The above $_GET line of code contained within the process.php file does not work properly and only retrieves the first of the three keywords. In this case only the word Russian is retrieved.
Is there a simple or proper way to fix this such that all keywords are retrieved properly?
Thank you in advance.
Check for the string '%20' and if present, explode by '%20'. Otherwise, check for the presence of a plus sign and explode by it instead.
This method is agnostic of the differing input format from the two sources entering the same script.
The caveat is that the string '%20' or the character '+' cannot occur inside a word in the other format or you will get unusual behavior.
$keyword = array();
if(stripos($keywords,"%20")) {
$keyword = explode("%20",$keywords);
}
else if(stripos($keywords,"+")) {
$keyword = explode("+",$keywords);
}
'$keyword' will then contain your keywords in an array.
Related
In my PHP application I am displaying embedded videos from various sources - youtube, vimeo etc.
In my articles table I store the id of my embed videos:
Article.video_url = 'e5dkjwkdek'
Then in my video_providers table I store the embed code, but I want to dynamically add the video_url, so I store:
VideoProviders.embedcode = "https://www.youtube.com/embed/$article->video_url"
I then output the 'embedcode' variable in my template and I want to append the $article->video_url which is the unique id of the video.
It seems I need a variable within the variable, I tried:
VideoProviders.embedcode = "https://www.youtube.com/embed/{$article->video_url}"
and
VideoProviders.embedcode = "https://www.youtube.com/embed/$$article->video_url"
But it seems these are simply treated as literal strings. If anyone has any better suggestions as to how to achieve this I am all ears. In short I want the mark-up stored in one place so that is can be edited should the embed code of the provider change.
You cannot store strings with PHP interpolation symbols. Double-quoted strings are interpolated at runtime.
I'd say you have three options...
Store the various parts in your database and construct them in your query. For example (assuming MySQL)
SELECT
CONCAT(VideoProviders.embed_prefix, Article.video_url) AS embedcode,
-- etc
with VideoProviders.embed_prefix containing 'https://www.youtube.com/embed/', 'https://player.vimeo.com/video/', etc
Store the URL with placeholders for the video id and (again assuming MySQL) use the REPLACE function. For example
VideoProviders.embedcode = 'https://www.youtube.com/embed/{VIDEO_ID}'
and
SELECT
REPLACE(VideoProviders.embedcode, '{VIDEO_ID}', Article.video_url) AS embedcode,
-- etc
This would be the preferred solution if the video id doesn't always appear at the end of the URL.
Store a printf style pattern in embedcode, eg 'https://www.youtube.com/embed/%s' and put it together with PHP, eg
$embedcode = sprintf($row['embedcode'], $row['video_url');
I think you can just do this:
$video_id = 'e5dkjwkdek';
$provider_url = 'https://www.youtube.com/embed/';
$embed_code = $provider_url . $video_id;
Or something similar to this. You can fill the video_id and provider_url anyway you like. From a database or from some other source. This way should always work.
EDIT FOR MORE INFO
I have a page in an admin area where users can write their own PHP/HTML files for adding extra functionality etc they want to use in their website. I have an array of "dangerous" words to filter out any messing with core database tables, such as being able to write a malicious code to drop the members table (for example).
The textarea/code area takes the content and uses fwrite to put it all into a PHP file which can then be included via template tags on a website.
When the file is saved, it reads all the text and checks it against the "dangerous array" of words that can't be used (eg: exec, system, delete from, drop database etc).
But I've recently found a flaw where a variable like below can be put in the file, and then a mysql command could be used like so:
$var = "DR" . "OP ". "TA" . "BL" . "E";
$sql = mysql_query($var tablename);
Checking all the file contents through a array match of words doesn't work in this scenario.
$dangerous = "/\b(exec|system|delete from|drop database)\b/i";
if (preg_match($dangerous, $code)) {
$tag_code = preg_replace($dangerous, '', $tag_code);
}
------- end edit
I have a function which checks an array of "bad words" and filters them out when saving a new custom user generated file (similar to what this question says), but I've discovered that it can easily be circumvented by splitting the invalid words with a variable.
For example, "DELETE FROM" is an invalid phrase, but if a file is made with this:
$var = "DE" . "LET". "E " . "FR" . "OM";
The array filter obviously can't detect this in the usual way. The problem is that these variable "hacks" can be written in any combination, so I'm not sure how - or if - there's a way to detect things like this in a file.
Can this be done?
Let me first give you a little background to explain what I'm trying to do. My websites use URL's that look like this: MySite/World/Isthmus_of_Panama
I'm working on a major upgrade (and may eventually upgrade further by switching to a CMS, like Drupal or WordPress), and it sounds like the general consensus is that URL's with hyphens are better than underscores. So I'm changing my URL's to MySite/World/Isthmus-of-Panama. In the meantime, I'm also trying to figure out if I should change my URL's to all lower case, and what about special symbols like accents or parentheses?
And what if someone typed in a URL that looks like MySite/World/Isthmus of Panama ? Wikipedia has a script that automatically converts the spaces to underscores. It will also default to the correct URL if you use the wrong case.
Of course, if I change my URL's, I'll also have to forward visitors from my old URL's. It's getting very confusing.
Then I realized that I could cover all of the bases with a script that accepts any URL that matches the characters in my database, 1) regardless of case, 2) and regardless of whether multiple words are separated by hyphens, underscores, spaces or %20. So imagine the following URL's:
MySite/World/Isthmus-of-Panama
MySite/World/Isthmus of Panama
MySite/World/Isthums%20of%20Panama
MySite/World/isthumus_of_panama
MySite/World/Isthmus-of_PANAMA
Where the database value is Isthmus-of-Panama.
Below is one of my queries, where $MyURL = the database value URL (e.g. Isthmus-of-Panama). Can anyone tell me how to modify it so that all of the above URL's will be accepted, with the page then defaulting to the database value?
Wikipedia has a similar feature. If you go to their article about Crazy Horse, then replace the URL Crazy_Horse with crazy_horse or Crazy Horse, it will default to Crazy_Horse. Thanks.
$sql= "SELECT COUNT(URL) AS num FROM gs_reference
WHERE URL = :MyURL";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':MyURL',$MyURL,PDO::PARAM_STR);
$stmt->execute();
$Total = $stmt->fetch();
switch($Total['num'])
{
case 1:
// DISPLAY A PAGE
break;
case 0:
// 404 NOT FOUND ERROR
break;
default:
// DUPLICATE RESULTS
break;
}
I would convert input, example Isthums%20of%20Panama, to the database value in php.
If the converted value is equal to the input one then don't do a 301 redirect to the url with the converted text else do one
EDIT
I would create in database a column slug (generally called like this) which contain the text normalized (ascii character and -) and create an unique index on it
You could use this function to generate the slug in php: PHP function to make slug (URL string)
I have a html form in php file in which there is a textbox in which a user can post multiple links . suppose
www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm
www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm
www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm
www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm
There are four links here . If i submit the form and the data is send to target page then it counts the whole textbox suppose named "links" as a string and send all of its data into database which it should . But i wanted to send these links and the data along with them such as uid , name to be submitted 4 times into database ie as many times as many links are there instead on 1 entry with all four links and the name and id in one row . How can i make this possible ?
I edited this entire post after I got more information by the author
Assuming you are using a textarea where the user can enter his information you could process that in PHP:
<form action="mytarget.php" method="post">
<textarea name="urls"></textarea>
</form>
Assuming the user should enter one URL per line, on PHP:
$data = explode("\n", $_POST['urls']);
if(count($data) > 0) {
foreach($data as $url) {
echo $url . "<br />";
}
}
Maybe this are the droids you are looking for. :P
Sorry I've been trying to figure how a technique with just the textarea:
This does use jQuery, I'm not sure if that is something you want to do or not. You can easily convert it to javascript if you like.
<script>
$(document).ready(function() {
$('textarea').on('focusout', function() {
var text = $('textarea').val();
var delimiter = ",";
$('textarea').val(text + delimiter);
});
});
</script>
What that does is appends a comma to the end of each url when the user focuses out of the textarea (pick whichever event you want, i don't expect you to use focusout), so that when your form is submitted, you can then explode the textareas text and get the urls and store them in separate variables.
The regular expression will expect the url to always end in .htm, so if you are wanting other url endings then add to the regex.
This will add a delimiter after every focusout event, even if its just plain text (i.e. not a valid url). But you can check against this once you've exploded (the text I mean :D), and it can be a good way to sanitize your data to make sure you're getting valid urls.
Hope this helps in some way
PS, the delimiter can be anything, i.e. a new line would be best \n, just remember to use the same delimiter in explode() i.e. explode("\n", $_POST[urls]);
I'm implementing a php interface to process a .php file containing a bunch of define sentences defining constants with text values to translate by somebody.
The input is parsed sentence by sentence and shown in the interface to the translator who will input the translation in a html textarea and send it to the server
By the end of the process an output file would be generated, identical to the input .php file, only with the define values translated.
E.g. processing an input file 'eng.php' like this:
<?php
define ("SENTENCE_1", "A sentence to translate");
?>
would give the translated output file 'spa.php' like this:
<?php
define ("SENTENCE_1", "The same sentence translated to spanish");
?>
For this I would like to know:
What is the best way to parse the input file to get the constant names and values in an array? (Something like $var[0]['name'] would be "SENTENCE_1" and $var[0]['value'] would be "A sentence to translate")
Would it be possible to get the translation from google translator shown in the input textarea as a suggestion to edit for the person who is translating it? How? (I read google translator api v1 is no longer available and v2 is only available as a paid service. Are there any free alternatives?)
http://php.net/manual/es/function.get-defined-constants.php
What about that?
get_defined_constants doesn't give you exactly the structure you asked for, but it should be sufficient.
define('MY_CONSTANT', 'something');
define('MY_CONSTANT_2', 'another');
$constants = get_defined_constants(true);
$constants = $constants['user'];
print_r($constants);
/**
* array(
* 'MY_CONSTANT' => 'something',
* 'MY_CONSTANT_2' => 'another'
* )
*/
Note that this will be all constants defined in the current scope, which in PHP is gonna be anything defined this request.
Use get_defined_constants() to get the list of all the defined constants.
To get userdefined constant specially
$allconstants = get_defined_constants(true);
print_r($allconstants['user']);
In case anybody needs to read constants' names and values defined in a given .php file into an array of variables without actually defining those constants (E.g. if some different constant with the same name was previously defined, thus giving an error when processing the file with include or require), here is how I did it (Warning: I haven't had any trouble yet, but it's not thoroughly tested, so it can be buggy).
if (file_exists($filename)){
$outf=fopen($filename,'r');
while (($line=fgets($outf))!==false){
if (strpos($line, 'define')!==false){
$parts=explode("\"",implode("\"",explode("'",implode("\\q",explode("\\\"",implode("\\s",explode("\\'",$line)))))));
$name=implode("\\'",explode("\\s",implode("\\\"",explode("\\q",$parts[1]))));
$value=implode("\\'",explode("\\s",implode("\\\"",explode("\\q",$parts[3]))));
$outconstants[$name]=$value;
}
}
}
You can see I assume there's no more than 1 define sentence per line, and that the names and values of the constants are specified as string values using PHP notation (between single (') or double (") quotes.)
Also, escaped quotes (\" or \') are temporarily escaped as \q (\") or \s (\') instead, to properly match the non-escaped ones, and then escaped back as usual once what's in between the non escaped ones is assigned to $name and $value.
The google api problem was solved using microsoft translation api instead (free up to 2.000.000 chars/month): http://msdn.microsoft.com/en-us/library/ff512421.aspx#phpexample