get html content with paging stored in cookies - php

I have a page where i need to go to www.site.com/search/all and then i can use www.site.com/page/2 3 4 ...etc. If i go directly to www.site.com/page/2 i don't have anything because it's no stored in cookies by the first url (www.site.com/search/all).
I want to run all pages and get the content, but i only can get content from the first page, that's given to me by (www.site.com/search/all).
i've made a $context and used session_start() to check if it works, but no success.
Theres my code:
<?php
require 'simple_html_dom.php';
$opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"));
$context = stream_context_create($opts);
session_write_close(); // unlock the file
$f=10;
for($i=1;$i<=$f;$i++) {
if($i==1) {
$html = file_get_html('http://www.site.com/search/all',false,$context);
session_start();
}
else {
$html = file_get_html('http://www.site.com/page/$i',false,$context);
}
echo $i;
echo $html;
?>
The $html result it's always from the first page, it wont go to the next, i think because of the cookies.

Related

PHP file_get_contents not showing url link

I'm having an issue with php file_get_content(), I have a txt file with links where I created a foreach loop that display multiple links in the same webpage but it's not working, please take a look at the code:
<?php
$urls = file("links.txt");
foreach($urls as $url) {
file_get_contents($url);
echo $url;
}
The content of links.txt is: https://www.google.com
Result: Only a String displaying "https://www.google.com"
Another code that works is :
$url1 = file_get_contents('https://google.com');
echo $url1;
This code returns google's homepage, but I need to use first method with loops to provide multiple links.
Any idea?
Here's one way of combining the things you already had implemented:
$urls = file("links.txt");
foreach($urls as $url) {
$contents = file_get_contents($url);
echo $contents;
}
Both file and file_get_contents are functions that return some value; what you had to do is putting return value of the latter one inside a variable, then outputting that variable with echo.
In fact, you didn't even need to use variable: this...
$urls = file("links.txt");
foreach($urls as $url) {
echo file_get_contents($url);
}
... should have been sufficient too.

PHP - Redirect to another page after getting node values from current page

I want to redirect user to another page after getting node values from current page and passing them into the URL's parameter, here is my code:
<?php
$dom = new DOMDocument;
$html = file_get_contents(home_url(). $_SERVER['REQUEST_URI']);
$dom->loadHTML($html);
$addresses = $dom->getElementsByTagName('address');
foreach ($addresses as $key => $address) {
$add[$key] = $address->nodeValue;
}
$fields['address'] = urlencode($add[0]);
$qry = http_build_query($fields);
if(!empty($qry)){
header( 'Location: http://example.com/subscription-form/?' . $qry) ;
}
?>
It does redirect successfully, but http_build_query values are empty. Here's an example of redirect: http://example.com/subscription-form/?address= , the URL is without the value of $_GET['address'] .
PHP redirect didn't work, so I tried it with JavaScript and it worked:
$redir = '<script type="text/javascript">';
$redir.= 'window.location.href="http://example.com/subscription-form/?';
$redir.= $qry .'"';
$redir.= '</script>';
echo $redir;
and yes, there's no need to urlencode as it's already done by http_build_query.

parse a url, get hash value, append to and redirect URL

I have a PHP foreach loop which is getting an array of data. One particular array is a href. In my echo statement, I'm appending the particular href onto my next page like this:
echo 'Stats'
It redirects to my next page and I can get the URL by $_GET. Problem is I want to get the value after the # in the appended URL. For example, the URL on the next page looks like this:
stats.php?url=basket-planet.com/ru/results/ukraine/?date=2013-03-17#game-2919
What I want to do is to be able to get the #game-2919 in javascript or jQuery on the first page, append it to the URL and go to the stats.php page. Is this even possible? I know I can't get the value after # in PHP because it's not sent server side. Is there a workaround for this?
Here's what I'm thinking:
echo 'Stats';
<script type="text/javascript">
function stats(url){
var hash = window.location.hash.replace("#", "");
alert (hash);
}
But that's not working, I get no alert so I can't even try to AJAX and redirect to the next page. Thanks in advance.
Update: This is my entire index.php page.
<?php
include_once ('simple_html_dom.php');
$html = file_get_html('http://basket-planet.com/ru/');
foreach ($html->find('div[class=games] div[class=games-1] div[class=game]') as $games){
$stats = $games->children(5)->href;
echo '<table?
<tr><td>
Stats
</td></tr>
</table>';
}
?>
My stats.php page:
<?php include_once ('simple_html_dom.php');
$url = $_GET['url'];
//$hash = $_GET['hash'];
$html = file_get_html(''.$url.'');
$stats = $html->find('div[class=fullStats]', 3);
//$stats = $html->find('div[class='.$hash.']');
echo $stats;
?>
What I want to be able to do is add the hash to the URL that is passed on to stats.php. There isn't much code because I'm using Simple HTML DOM parser. I want to be able to use that hash from the stats.php URL to look through the URL which is passed. Hope that helps...
Use urlencode in PHP when you generate the HREFs so that the hash part doesn't get discarded by the browser when the user clicks the link:
index.php:
<?php
include_once ('simple_html_dom.php');
$html = file_get_html('http://basket-planet.com/ru/');
echo '<table>';
foreach ($html->find('div[class=games] div[class=games-1] div[class=game]') as $games){
$stats = $games->children(5)->href;
echo '<tr><td>
Stats
</td></tr>';
}
echo '</table>';
?>
Then on the second page, parse the hash part out of the url.
stats.php:
<?php
include_once ('simple_html_dom.php');
$url = $_GET['url'];
$parsed_url = parse_url($url);
$hash = $parsed_url['fragment'];
$html = file_get_html(''.$url.'');
//$stats = $html->find('div[class=fullStats]', 3);
$stats = $html->find('div[class='.$hash.']');
echo $stats;
?>
Is this what you're looking for?
function stats(url)
{
window.location.hash = url.substring(url.indexOf("#") + 1)
document.location.href = window.location
}
If your current URL is index.php#test and you call stats('test.php#index') it will redirect you to index.php#index.
Or if you want to add the current URL's hash to a custom URL:
function stats(url)
{
document.location.href = url + window.location.hash
}
If your current URL is index.php#test and you call stats('stats.php') it will redirect you to stats.php#test.
To your comment:
function stats(url)
{
var parts = url.split('#')
return parts[0] + (-1 === parts[0].indexOf('?') ? '?' : '&') + 'hash=' + parts[1]
}
// stats.php?hash=test
alert(stats('stats.php#test'))
// stats.php?example&hash=test
alert(stats('stats.php?example#test'))

Posting form data to PHP script and then Posting results back again

The below script fetches meta data on a list of URL's.
The URL's are inputted on my front end, I managed to get the data to another page (this script) but now instead of echo'ing the table onto the same page the script is on I want to feed that data back to my front end and put it in a nice table for the user to see.
How would I make the php script echo the data on another page?
thanks
Ricky
<?php
ini_set('display_errors', 0);
ini_set( 'default_charset', 'UTF-8' );
error_reporting(E_ALL);
//ini_set( "display_errors", 0);
function parseUrl($url){
//Trim whitespace of the url to ensure proper checking.
$url = trim($url);
//Check if a protocol is specified at the beginning of the url. If it's not, prepend 'http://'.
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
//Check if '/' is present at the end of the url. If not, append '/'.
if (substr($url, -1)!=="/"){
$url .= "/";
}
//Return the processed url.
return $url;
}
//If the form was submitted
if(isset($_POST['siteurl'])){
//Put every new line as a new entry in the array
$urls = explode("\n",trim($_POST["siteurl"]));
//Iterate through urls
foreach ($urls as $url) {
//Parse the url to add 'http://' at the beginning or '/' at the end if not already there, to avoid errors with the get_meta_tags function
$url = parseUrl($url);
//Get the meta data for each url
$tags = get_meta_tags($url);
//Check to see if the description tag was present and adjust output accordingly
$tags = NULL;
$tags = get_meta_tags($url);
if($tags)
echo "<tr><td>$url</td><td>" .$tags['description']. "</td></tr>";
else
echo "<tr><td>$url</td><td>No Meta Description</td></tr>";
}
}
?>
I think its best to use Ajax for this right? So it doesn't refresh
i prefer the ajax method as its much cleaner..
Whats important is the $.ajax(); and the echo json_encode()
Documentation
php manual for json_encode() - http://php.net/manual/en/function.json-encode.php
jquery manual for $.ajax(); - http://api.jquery.com/jQuery.ajax/
List of Response Codes - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Example Code
Without seeing your HTML i'm guessing here.. but this should get you started in the right path for using ajax.
form html
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="siteUrl" id="siteUrl">
<input type="submit" name="submit" value="submit" class="form-submit">
</form>
example-container
In your case, this is a table, just set the table ID to example-container
ajax
This requires you to use the jquery library.. If you use another library in additon called data tables, you can streamline a lot of this jquery appending of <tr>'s
// On the click of the form-submit button.
$('.form-submit').click(function(){
$.ajax({
// What data type do we expect back?
dataType: "json",
// What do we do when we get data back
success: function(d){
alert(d);
// inject it back into a table called example-container
// go through all of the items in d and append
// them to the table.
for (var i = d.length - 1; i >= 0; i--) {
$('#example-container').append("<tr><td>"+d[i].url+"</td><td>"+d[i].description+"</td></tr>");
};
},
// What do we do when we get an error back
error: function(d){
// This will show an alert for each error message that exist
// in the $message array further down.
for (var i = d.length - 1; i >= 0; i--) {
alert(d[i].url+": "+d[i].message);
};
}
});
// make sure to have this, otherwise you'll refresh the page.
return false;
});
modified php function
<?php
//If the form was submitted
if(isset($_POST['siteurl'])){
//Put every new line as a new entry in the array
$urls = explode("\n",trim($_POST["siteurl"]));
//Iterate through urls
foreach ($urls as $url) {
//Parse the url to add 'http://' at the beginning or '/' at the end if not already there, to avoid errors with the get_meta_tags function
$url = parseUrl($url);
//Get the meta data for each url
$tags[] = get_meta_tags($url);
}
if($tags):
echo json_encode($tags);
else:
$message[] = array(
'url' => $url,
'message' => 'No Meta Description'
);
// This sets the header code to 400
// This is what tells ajax that there was an error
// See my link for a full ref of the codes avail
http_response_code(400);
echo json_encode($message);
endif;
}
You would have to either:
1 - submit to the frontend page, including this PHP code on that page instead.
2 - Use AJAX to post the form, get the output and put it somewhere on the frontend page.
Personally, I'd use the first method. It's easier to implement.

php how to scan full page for all POST variables and then echo at top of page?

I can't echo my variable above my CMS include code.. but if I echo the variable after, then it recognizes the $url variable.
Here is some code:
<?php
// here is my CMS inlcude code
$template = 'news_script';
$number = '';
$category = '';
include $cutepath.'/show_news.php';
?>
If I echo $url above the include code, it returns nothing. But below, it obviously recognizes it.
Is there a php function that scans the whole page and retrieves all the POST variables so you can use $url at the top of the php page with a header('Location:'. $url); script??
Obviously $url is being defined in your show_news.php script. PHP executes a script line-by-line, and will not magically "reach back" to set a variables value in an earlier line.
Another (ugly) way would be:
<?php
// here is my CMS inlcude code
$template = 'news_script';
$number = '';
$category = '';
ob_start();
include $cutepath.'/show_news.php';
$buffered_data=ob_get_contents();
ob_end_clean();
echo $url; // here you could place your: header('Location:'. $url);
echo $buffered_data;
?>

Categories