php movie search bar using variables - php

I am trying to create a page that when someone types a specific movie in the search bar it goes to a page on my server with an embedded vlc player and plays that movie. I tried by storing the userinput as a variable in an array using php but i either get one of two errors array to string conversion or undefined index!
I'm using pregmatch to scan a txt file containing my movies and want it to
take the file name that most matches the user input and add it to the src = $variable of my embeded player so i nly have to have one page to play 100 or more movies.
heres the php source and the embeded video player html
html video embed :
' />
and the source code for pregmatch!
<div class="search" align = "center">
<form action="MovieMatch.php" method ="post">
<input type="text" name="userget" />
<input type="submit"name="submit" value="<?php$pick ?>" />
</form>
</div>
<h1 align = "center" class="text-primary">Search our Movies!</h1>
<div class="images" >
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
if(isset($_POST['submit'])){
$submit = $_POST ["userget"];//storing input
$file = 'movielist.txt';
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = $submit;
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
$handle = fopen("movielist.txt", "r");
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$pick = implode("\n", $matches[0]);
echo $pick[1];
echo "Found matches:\n";
echo 'click me!'; // this is my fix bu
}
else{
echo "No matches ";
}
}
?>

Related

PHP RSS Feed Reader Data filtering problem

So, I wrote an RSS feed Reader in PHP and I am almost done(I think) but I haven't quite got around the part where I can filter keywords. When I tried to fix it, it said that there is an "}" missing at the end of the file. I am not sure what to do with this problem, hence why I am here. I use Visual Studio Code and any help would be much appreciated.
Here is the code I wrote:
<?php
/*
* To access the localhost for this program type in the address bar: "localhost/feedreader" then
* click on RSSFeedReader.php when you install the two files by the names of "RSSFeedReader.php" and "RSSConfig.json" into the Sites
* folder in the Users section.
*/
?>
<div class="content">
<form method="post" action="">
<input type="text" name="feedurl" placeholder="Enter website RSS Link"> <input type="submit" value="Submit" name="submit">
</form>
<div class="content">
<form method="post" action="">
<input type="text" name="keyword" placeholder="Enter keyword here"> <input type="submit" value="Submit" name="submit">
</form>
<?php
/*
The piece of code above will create the box that says "Enter Website RSS Link" and the submit
button that will process through the code to search the inputted RSS link.
Line 1 will create the div class in which the content of the client side of things(Front-End),and the form POST method is a way of
retrieving information and data that is being inputted through the sumbit section
*/
if(isset($_POST['submit'])){
if($_POST['feedurl'] != ''){
$url = $_POST['feedurl'];
}
}
$invalidurl = false;
if(#simplexml_load_file($url)){
$feeds = (simplexml_load_file($url));
}
else{
$invalidurl = true;
echo "<h2>Invalid RSS Feed Link.
Please try a valid RSS Feed Link.
</h2>";
}
/*
This block of code above generally allows the screen to output "Invalid RSS Feed Link. Please try a valid RSS Feed Link."
when typing out a URL/XML link which is not an RSS Feed Link.
First, the program will assign the variable: $invalidurl to false and will load the simple xml file, however if the url turned out
to be invalid, the program will output "Invalid RSS Feed Link" to the user's screen.
The first line will assume that the is no invalid url link so it is assigned to be false, then the simplexml_load_file will load
up the xml files and if the url is a feed link, it will store the the link into the variable "$feeds". However, if the url is
not a feed link, then it will make the program assign the variable "$invalidurl" as true which will the return the string "Invalid
RSS Feed Link. Please try a valid RSS Feed Link" with a level 2 headline.
*/
$i=0;
if(!empty($feeds)){
$site = $feeds->channel->title;
$sitelink = $feeds->channel->link;
if(isset($_POST['submit'])){
if($_POST['keyword'] != ''){
string == $_POST['keyword'];
}
}
function parse($xml)
{
return [
'title' => (string) $xml->channel->title
];
}
}
echo "<h1>".$site."</h1>";
foreach ($feeds->channel->item as $item) {
$title = $item->title;
$link = $item->link;
$description = $item->description;
$postDate = $item->pubDate;
$pubDate = date('D, d M Y',strtotime($postDate));
/*
The block of code from line 67 to line 71 represent how the program will extract the dtaa from the article in terms
of the title, a hyperlink, the description of the article, and the date that that the article was published(Day, Month and Year)
The first line sets the variable "$i" is set to zero which identifies future into the code how many results the program will output
onto the results page.
Then the next two lines of code will represents how the program will extract the title of the artcile by going though the page
source and into the feed area where the title is stored. It then gets the link to the article to make make the title a hyperlink.
the next piece of code from line 75 to 79 will store the title of the articel into the variable "$title" as an item. It will also
store the link of the article into the variable "$link" as an item. It will also store what the page source identitifies as the
description of the article into the variale "$description" as an item. It wil also the extract the date that the article was
published from the "pubDate" in the page source as the variable "$postDate". the $pubDate will store the postDate in terms of
days, months and years.
*/
if($i>=15) break;
?>
<div class="post">
<div class="post-head">
<h2><a class="feed_title" href="<?php echo $link; ?>"><?php echo $title; ?></a></h2>
<span><?php echo $pubDate; ?></span>
</div>
<div class="post-content">
<?php echo implode(' ', array_slice(explode(' ', $description), 0, 20)) . "..."; ?> Read more
</div>
</div>
<?php
$i++;
if(!$invalidurl){
echo "<h2>No item found</h2>";
}}
?>

Get products from e-shop using simple dom parser and pagination

I want to parse some products link, name and price. Here's my code: Having some trouble parsing, because I don't know how to get product link's and name's.Price is ok, I get it. And pagination not working as well
<h2>Telefonai Pigu</h2>
</br>
<?php
include_once('simple_html_dom.php');
$url = "http://pigu.lt/foto_gsm_mp3/mobilieji_telefonai/";
// Start from the main page
$nextLink = $url;
// Loop on each next Link as long as it exsists
while ($nextLink) {
echo "<hr>nextLink: $nextLink<br>";
//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a url
$html->load_file($nextLink);
$phones = $html->find('div#productList span.product');
foreach($phones as $phone) {
// Get the link
$linkas = $phone->href;
// Get the name
$pavadinimas = $phone->find('a[alt]', 0)->plaintext;
// Get the name price and extract the useful part using regex
$kaina = $phone->find('strong[class=nw]', 0)->plaintext;
// This captures the integer part of decimal numbers: In "123,45" will capture "123"... Use #([\d,]+),?# to capture the decimal part too
echo $pavadinimas, " #----# ", $kaina, " #----# ", $linkas, "<br>";
//$query = "insert into telefonai (pavadinimas,kaina,linkas) VALUES (?,?,?)";
// $this->db->query($query, array($pavadinimas,$kaina, $linkas));
}
// Extract the next link, if not found return NULL
$nextLink = ( ($temp = $html->find('div.pagination a[="rel"]', 0)) ? "https://www.pigu.lt".$temp->href : NULL );
// Clear DOM object
$html->clear();
unset($html);
}
?>
Output:
nextLink: http://pigu.lt/foto_gsm_mp3/mobilieji_telefonai/
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/pigu_view.php
Line Number: 26
#----# 999,00 Lt #----#
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/pigu_view.php
Line Number: 26
Please Inspect carefully the source code you're working on, then, based on that, you can retrive the nodes you want... It's normal that the compatible code with another website wont work here, since the two websites dont have the same source code/structure !
Lets proceed, again, step by step...
$phones = $html->find('div#productList span.product'); will give you all "phones containers", or what I called "blocks"... Each block has the following structure:
<span class="product">
<div class="fakeProductContainer">
<p class="productPhoto">
<span class="">
<span class="flags flag-disc-value" title="Akcija"><strong>500<br><span class="currencySymbol">Lt</span></strong></span>
<span class="flags freeShipping" title="Nemokamas prekių atsiemimas į POST24 paštomatus. Pasiūlymas galioja iki sausio 31 d."></span>
</span>
<img src="http://lt1.pigugroup.eu//colours/48355/16/4835516/c503caf69ad97d889842a5fd5b3ff372_medium.jpg" title="Telefonas Sony Xperia acro S" alt="Telefonas Sony Xperia acro S">
</p>
<div class="price">
<strong class="nw">999,00 Lt</strong>
<del class="nw">1.499,00 Lt *</del>
</div>
<h3>Sony Xperia acro S</h3>
<p class="descFields">
3G: <em>HSDPA 14.4 Mbps, HSUPA 5.76 Mbps</em><br>
GPS: <em>Taip</em><br>
NFC: <em>Taip</em><br>
Operacinė sistema: <em>Android OS</em><br>
</p>
</div>
</span>
The anchor containing the product link an is included within <p class="productPhoto">, and it is the only anchor in there, so, to retrieve it simply use $linkas = $phone->find('p.productPhoto a', 0)->href; (then complete it since it's only the relative link)
The product name is located into <h3> tag, again, we use simply $pavadinimas = $phone->find('h3 a', 0)->plaintext; to retrieve it
The price is included within <div class="price"><strong>, and again we use $kaina = $phone->find('div[class=price] strong', 0)->plaintext to retrieve it
Hoever, not all phones have their price displayed, therefore, we must check if the price has been retrieved correctly or not
And finally, the HTML code containing the next link is the following:
<div id="ListFootPannel">
<div class="pages-list">
<strong>1</strong>
2
3
4
5
6
<a rel="next" href="/foto_gsm_mp3/mobilieji_telefonai?page=2">Toliau</a>
</div>
<div class="pages-info">
Prekių
</div>
</div>
So, we are interested in <a rel="next"> tag, wich can be retrieved using $html->find('div#ListFootPannel a[rel="next"]', 0)
So, if we make add these modifications to your original code, we'll get:
$url = "http://pigu.lt/foto_gsm_mp3/mobilieji_telefonai/";
// Start from the main page
$nextLink = $url;
// Loop on each next Link as long as it exsists
while ($nextLink) {
echo "nextLink: $nextLink<br>";
//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a url
$html->load_file($nextLink);
////////////////////////////////////////////////
/// Get phone blocks and extract useful info ///
////////////////////////////////////////////////
$phones = $html->find('div#productList span.product');
foreach($phones as $phone) {
// Get the link
$linkas = "http://pigu.lt" . $phone->find('p.productPhoto a', 0)->href;
// Get the name
$pavadinimas = $phone->find('h3 a', 0)->plaintext;
// If price not found, find() returns FALSE, then return 000
if ( $tempPrice = $phone->find('div[class=price] strong', 0) ) {
// Get the name price and extract the useful part using regex
$kaina = $tempPrice->plaintext;
// This captures the integer part of decimal numbers: In "123,45" will capture "123"... Use #([\d,]+),?# to capture the decimal part too
preg_match('#(\d+),?#', $kaina, $matches);
$kaina = $matches[1];
}
else
$kaina = "000";
echo $pavadinimas, " #----# ", $kaina, " #----# ", $linkas, "<br>";
}
////////////////////////////////////////////////
////////////////////////////////////////////////
// Extract the next link, if not found return NULL
$nextLink = ( ($temp = $html->find('div#ListFootPannel a[rel="next"]', 0)) ? "http://pigu.lt".$temp->href : NULL );
// Clear DOM object
$html->clear();
unset($html);
echo "<hr>";
}
Working DEMO

php variable actual value not being inserted into table

html form
<html><body>
<form action="process.php" method="post">
Headline:<input type="text" name="head"><br>
Content:<Textarea rows="4" cols="50" name="cont"></textarea>
</form>
</html>
my table structure
two fields are headline,content.
Filling the form:
Headline- "this is crazy"
Content- "here i want to put image like this..
<img src="$image" /> "
Process.php
in this i get Headline and content from form in two php variable
$headline=$_POST['head'];
$content=$_POST['cont'];
here i have one variable $image which contains address of image like: $image contains "img\thumb\2.jpg"
i've to insert $headline and $content into table.
problem
whenever i insert headline and content into table... headline goes fine into table..but in content it shows: "here i want to put image like this..
<img src="$image" /> "
why $image actual value is not getting parsed?
any solution?
You're not actually "in PHP" when you're attempting to output it.
In other words, you have to open a PHP section to echo the variable:
<?php echo $image; ?>
or, with your image tag:
<img src="<?php echo $image; ?>" />
It's because when you write $image into HTML textarea, it's treated as a string not as variable.
So, you should write the full image URL to your database, something like img\thumb\2.jpg and then read it to the browser.
Use html_entity_decode Convert all HTML entities to their applicable characters
html_entity_decode($content);
Example
$b = html_entity_decode("I'll "walk" the <b>dog</b> now");
echo $b; // I'll "walk" the <b>dog</b> now
See when you are trying to input special characters like <, >, & etc. they are converted into their HTML formats like < is converted into <, similarly > is converted into >. Thats why when you are trying to insert < or > symbol in database it is inserting it like < and >. You shouldn't use them like this. But if you really need them you can replace < with < and > with > just before Insert query.
$qry = "INSERT INTO TEST (HEAD, CONTENT) VALUES (" . $head . ", " . $content . ")";
$qry = str_replace("<", "<", $qry);
$qry = str_replace(">", ">", $qry);
and then you can use $qry for insertion.

Which regular expression should I use for getting image link from text?

I have following code:
<center><img src="http://trustedyouautocorrect.com/wp-content/uploads/2012/02/ixxx66134057.jpg" alt="daniel7531sarah" /></center><input id="gwProxy" type="hidden" />
<!--Session data--><input id="jsProxy" onclick="if(typeof(jsCall)=='function'){jsCall();}else{setTimeout('jsCall()',500);}" type="hidden" />
<div id="refHTML"></div>
I need to make script that will get link from image-src. How can I do it? I hope you help me. Thank you.
I'm assuming with Javascript. Easiest way would be to put an id attribute on the img, then you can extract the src easily.
<script type="text/javascript">
function getSRC()
{
var imgID = document.getElementById("imgID");
alert( imgID.getAttribute('src') );
}
</script>
<img id="imgID" src="someIMG.png" /><br />
get
Using regex to extract the img src...
<?php
$str = '<center><img src="http://trustedyouautocorrect.com/wp-content/uploads/2012/02/ixxx66134057.jpg" alt="daniel7531sarah" /></center><input id="gwProxy" type="hidden" />
<!--Session data--><input id="jsProxy" onclick="if(typeof(jsCall)==\'function\'){jsCall();}else{setTimeout(\'jsCall()\',500);}" type="hidden" />
<div id="refHTML"></div>';
// regex to match all src attributes of image tags
preg_match_all("/<img[^>]+src=(['\"])(.+?)\\1/",$str,$matches);
// $matches{
// [0] -> the whole matched string
// [1] -> the quotation char (could be ' or ") captured so it can be used
// to match the closing quote (of the same type)
// [2] -> the src attr value
// }
// loop through each src attr value we captured
foreach($matches[2] as $m){
echo "This is what you are after ~~> " . $m;
}
?>
Regex means...
<img followed by
one or more not > ([^>]+) followed by
src= followed by
' or " captured for later use and escaped ((['\"]))
followed by a bunch of stuff un-greedily (.+?)
followed by same quote as captured before escaped (\\1)
This is however a bad way to approach the problem, and comes with a few issues. My regex does not capture src attributes that are unquoted. There might also be unusual circumstances where it matches false positives, or does not match real url's.
Regex, although great for many circumstances, as a swiss army knife of matching patterns, it makes a poor parser. Whe you need to parse HTML, you should use the appropriate methods.
A much much better (less error prone, faster, easier to understand and maintain) way to do it...
<?php
$str = '<center><img src="http://trustedyouautocorrect.com/wp-content/uploads/2012/02/ixxx66134057.jpg" alt="daniel7531sarah" /></center><input id="gwProxy" type="hidden" />
<!--Session data--><input id="jsProxy" onclick="if(typeof(jsCall)==\'function\'){jsCall();}else{setTimeout(\'jsCall()\',500);}" type="hidden" />
<div id="refHTML"></div>';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get img tags
$items = $DOM->getElementsByTagName('img');
//loop through found image tags
for ($i = 0; $i < $items->length; $i++){
$node = $items->item($i);
if ($node->hasAttributes()){
// attach all attributes of tag to array
foreach ($node->attributes as $attr){
$array[$attr->nodeName] = $attr->nodeValue;
}
}
// print out just the src attribute
echo "This is what you want ~~> " . $array['src'];
}
?>

create anchors in a page with the content of <h2></h2> in PHP

Well I have a html text string in a variable:
$html = "<h1>title</h1><h2>subtitle 1</h2> <h2>subtitle 2</h2>";
so I want to create anchors in each subtitle that has with the same name and then print the html code to browser and also get the subtitles as an array.
I think is using regex.. please help.
I think this will do the trick for you:
$pattern = "|<h2>(.*)</h2>|U";
preg_match_all($pattern,$html,$matches);
foreach($matches[1] as $match)
$html = str_replace($match, "<a name='".$match."' />".$match, $html);
$array_of_elements = $matches[1];
Just make sure that $html has the existing html before this code starts. Then it will have an <a name='foo' /> added after this completes, and $array_of_elements will have the array of matching text values.

Categories