So, right now I'm trying to generate dynamic URLs as well as their paths without using .htaccess or the use of modules. Basically, I'm trying to rewrite and output URL paths that work statelessly on different localhosts served by Apache.
I would like to have an index.php that gets URIs through a query string like this (obviously not code):
-> index.php (echos dynamically generated URL hyperlinks)
-> index.php?q=/ (echos every URI in JSON)
-> index.php?q=/some_id (outputs table some_id info w/ links to reviews)
-> index.php?q=/some_id/reviews (outputs table column of reviews w/ link to review_ids)
-> index.php?q=/some_id/reviews/review_id (output related column info)
Could someone walk me through how I'd go about doing this? I figure I'm going to have to write the URL using $_SERVER methods and explode while iterating through an array of table IDs..?
Any help is greatly appreciated!
EDIT:
Here's the code I was trying to write :/
<?php
$db = $user = $pw = 'logininfo';
try {
$dbconn = new PDO('mysql:host=localhost;db='.$db, $user, $pw;
}
catch (Exception $e) {
echo "Error: ";
echo $e->getMessage();
}
?>
<!DOCTYPE HTML>
<head>
<title>Product Reviews</title>
</head>
<body>
<h1>Product List:</h1>
<h2>
<ul>
<?php
try {
$sql = "SELECT somename, some_id FROM products";
$stmt = $dbconn->query($sql);
if($stmt !== false) {
foreach($stmt as $row) { //output just name
echo "<li>";
echo htmlentities($row['somename'])."<br />";
if($stmt !== false) {
$url = "<a href=index.php?q=".
htmlentities($row['some_id'])."/>".
htmlentities($row['somename'])."'s Review</a>";
echo $url; //output URL
echo "</li>"."<br />";
}
else {
echo "Unnecessary";
}
}
if($_GET['url']) { //don't really know what to put here
header("Location: $url"); //can't use headers anyway
}
}
$stmt = null;
}
catch (PDOEXCEPTION $e) {
echo $e->getMessge();
}
?>
</ul>
</h2>
</body>
</html>
You can write URLs as :
http://example.org/index.php/reviews/id/ [where id can be your review id]
and use $_SERVER['PATH_INFO'] in index.php to get part of URL which is after index.php, then explode the text and get desired data out of it.
<?php
$query_string = explode('/', $_SERVER['PATH_INFO']);
switch(count($query_string)) {
case 2:
$some_id = (int) $query_string[1];
if ($some_id === 0) {
//(echos every URI in JSON)
}
else {
// (outputs table some_id info w/ links to reviews)
}
break;
case 3:
//(outputs table column of reviews w/ link to review_ids)
$some_id = (int) $query_string[1];
$table_name = $query_string[2];
break;
case 4:
//(output related column info)
$some_id = (int) $query_string[1];
$table_name = $query_string[2];
$review_id = (int) $query_string[3];
break;
default:
// Error case
}
?>
Try this for size
if (isset($_GET['q']) && !empty($_GET['q']))
{
$params = explode("/",$_GET['q']);
if (isset($params[3]) && !empty($params[3]))
echo "(output {$params[2]} {$params[3]} info)";
else if (isset($params[2]) && !empty($params[2]))
echo "(outputs table column of {$params[2]} w/ link to review_ids)";
else if (isset($params[1]) && !empty($params[1]))
echo "(outputs table {$params[1]} info w/ links to reviews)";
else
echo "(echos every URI in JSON) ";
}
else
echo "(echos dynamically generated URL hyperlinks)";
Related
I am trying to get dynamic $_SESSION[$id] on the second page shown below, but its not working (as per the printout):
First page url
https://example.com/test.php?id=1548393
First page code
<?php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
?>
Second page url
https://example.com/test2.php?id=1548393
Second page code
<?php
session_start();
$id = $_GET['id'];
if(isset($_SESSION[$id])){
echo "working";
}else{
echo "not working";
}
?>
i found problem we can not use numeric index for $_SESSION
but we can use number in $_SESSION by convert number to roman numerals
first page url
https://example.com/test.php?id=1548393
first page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
$_SESSION[$roman_id] = "mysecretstringline";
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
second page url
https://example.com/test2.php?id=1548393
second page code
<?php
session_start();
$roman_id = romanic_number($_GET['id']);
if(isset($_SESSION[$roman_id])){
echo "working";
}else{
echo "not working";
}
function romanic_number($integer, $upcase = true)
{
$table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1);
$return = '';
while($integer > 0)
{
foreach($table as $rom=>$arb)
{
if($integer >= $arb)
{
$integer -= $arb;
$return .= $rom;
break;
}
}
}
return $return;
}
?>
output
working
thanks #gre_gor and #Katie
Could be that in your normal code (this just looks like a quick mockup), you have a space after ?> somewhere. That could cause issues.
<?php
// start.php
session_start();
$id = $_GET['id'];
$_SESSION[$id] = "mysecretstringline";
and
<?php
// next.php
session_start();
$id = $_GET['id'];
if (isset($_SESSION[$id])) {
echo "working";
} else {
echo "not working";
}
works for me. Notice no ?> characters.
UPDATE:
The following might be of interest regarding session name constraints (can a php $_SESSION variable have numeric id thus : $_SESSION['1234’])
You have that issue in your example you could just add an id_ and then do the same check when validating/getting the session.
I have been working on this issue for what feels like endless hours, but I feel like I'm really close to solving it.
I have stripped my site down to the bare minimum code to troubleshoot this, and I think I have found the line that is causing me trouble, but I just don't know WHY it is causing me trouble. Here is my code as it is now:
//display all products
if (!isset($_GET['id'])) {
$result = mysqli_query($link, "SELECT products.*, company.company-name FROM products INNER JOIN company ON products.company-id=company.id");
if (!$result) {
echo 'Error';
exit();
}
}
//display one product
if (isset($_GET['id'])) {
$id = $_GET['id'];
$get_item_info = mysqli_query($link, "SELECT products.*, company.company-name FROM products INNER JOIN company ON products.company-id=company.id WHERE products.id='$id'");
$row = mysqli_fetch_assoc($get_item_info);
if (!$row) {
echo 'Error';
exit();
}
$company_name = $row['company-name'];
$model_abbreviation = $row['model-abbreviation'];
if ($row['model-version'] == NULL) { $image_directory_name = "$company_name/$model_abbreviation/"; } else $image_directory_name = "$company_name/$model_abbreviation (" . $row['model-version'] . ")/";
}
if (!isset($_GET['id'])) {
$group = array();
while ($row = mysqli_fetch_assoc($result)) {
$group[ $row['company-name'] ][] = $row;
}
foreach ($group as $company_name => $models) {
foreach ($models as $model) {
echo "<a href='$model[id]/'>$model[model-abbreviation]</a>";
}
}
}
if (isset($_GET['id'])) {
$top_thumb = "$image_directory_name" . "top.jpg";
echo "<img src='$top_thumb'>"; echo '</br>';
$images = glob($image_directory_name."*_thumb*");
if (!$images) {
echo 'No images to display.';
}
else {
foreach ($images as $image) {
$full = str_replace('thumb','full',$image);
echo '<img src="'.$image.'">';
}
}
}
So if I use this code in combination with my rewriterule:
RewriteRule ^products/(.*)/$ /products/index.php?id=$1
And I go to a product page, such as localhost/products/30/
No images display, HOWEVER, in the page source I can see that it is TRYING to display the images (though I get no error from my script, just a blank page), just with the wrong path - it looks like this:
<img src='Company Name/Model Name (Model Version)/top.jpg'></br><img src="Company Name/Model Name (Model Version)/A_thumb.jpg">
So the code is working, but the path is wrong. OK.
So I added /products/ to the $image_directory_name variable in this line:
if ($row['model-version'] == NULL) { $image_directory_name = "/products/$company_name/$model_abbreviation/"; } else $image_directory_name = "/products/$company_name/$model_abbreviation (" . $row['model-version'] . ")/";
This is where it breaks.
The top thumb is fixed and displays, but I get my error when trying to glob() the bottom thumbs - 'No images to display'. And the source doesn't even show as trying to load them anymore.
So. I have gotten really close, I've spent countless hours on this. Anyone got any idea what's going on? Something to do with my $image_directory_name path or the glob() code I'm guessing...I am so mentally desperate to solve this.
edit: additional info: When I go to localhost/products/companyname/productname/ in my browser, I get the Error from the if (!$row) line in my code. But I go to localhost/products/companyname/productname/imagename.jpg, the image loads.
update: I even tried moving all of my images from /products/companyname/productname/
to /images/companyname/productname/
The bottom thumbs still don't show up. Argh.
I am using DOMDocument() to load the text of html page.
It takes much time to load the page. Does that means it downloads images also ?
Any alternatives or solution to load a html page from url faster ?
I am using DOMDocument() to basically extract meta description, title text, body text etc.
Solution with working code will be highly appreciated.
<?php
set_time_limit(0);
include "connection.php";
error_reporting(E_ERROR | E_PARSE);
// Create a document instance
$doc = new DOMDocument();
if(!isset($_GET['url'])){
$_GET['url']=$urlfromdaemon;
$silentcrawl="set";
}
$doc->loadHTMLFile($_GET['url']);
$base_url=$_GET['url'];
$base_url = parse_url($base_url);
$base_url = 'http://'.$base_url['host'].'/';
//Searches for all elements with the "a" tag name
$tit = $doc->getElementsByTagName( "a" );
$urlarray=array();
$t=0;
foreach($tit AS $x){
$urlarray[$t]=$x->getAttribute('href');
$urlanchor[$t]=$x->nodeValue;
$t++;
}
//This makes the URL with spaces work correctly
for($i=0;$i<count($urlarray);$i++){
$urlarray[$i]= str_ireplace(" ","%20",$urlarray[$i]);
}
//
for($i=0;$i<count($urlarray);$i++){
$result=stristr(substr($urlarray[$i], 0, 7),"http://");
if($result==''){
if(stristr(substr($urlarray[$i], 0, 8),"https://")!=''){
}
else if(stristr(substr($urlarray[$i], 0, 2),"//")!=''){
$urlarray[$i]= 'http:'.$urlarray[$i];
}
else if(stristr(substr($urlarray[$i], 0, 4),"www.")==''){
//critical code section
$urlcheck='http://'.$urlarray[$i];
$headers = #get_headers($urlcheck, 1);
if ($headers === FALSE) { //Test for differentiate example.com with example .
if(substr($_GET['url'],-1)=='/'){
$urlarray[$i]= $_GET['url'].$urlarray[$i];
}
else{
if(parse_url($_GET['url'], PHP_URL_PATH)=='/'){
$trim=basename(parse_url($_GET['url'], PHP_URL_PATH));
$urlarray[$i]= str_ireplace($trim,"",$_GET['url']).$urlarray[$i];
}
else if(substr(str_ireplace(basename($_GET['url']),"",$_GET['url']),-1)=='/'){
if(substr(str_ireplace(basename($_GET['url']),"",$_GET['url']),-7)=='http://'){
$trim=basename(parse_url($_GET['url'], PHP_URL_PATH));
$urlarray[$i]= str_ireplace($trim,"",$_GET['url']).'/'.$urlarray[$i];
}
else{
$trim=basename(parse_url($_GET['url'], PHP_URL_PATH));
$urlarray[$i]= str_ireplace($trim,"",$_GET['url']).$urlarray[$i];
}
}
else{
$trim=basename(parse_url($_GET['url'], PHP_URL_PATH));
$urlarray[$i]= str_ireplace($trim,"",$_GET['url']).'/'.$urlarray[$i];
}
}
}
else {
$urlarray[$i]= 'http://'.$urlarray[$i];
}
//
}
else{
$urlarray[$i]='http://'.$urlarray[$i];
}
}
}
for($i=0;$i<count($urlarray);$i++){
$file = $urlarray[$i];
$file_headers = #get_headers($file);
if($file_headers[0] =='HTTP/1.1 404 Not Found') {
if(!isset($silentcrawl)){
//print_r($file_headers);
echo '<img style="width:20px;height:20px;float:left;" src="cross.png" > '.$urlarray[$i].'<br><Br>';
}
}
else {
if(!isset($silentcrawl)){
echo '<img style="width:20px;height:20px;float:left;" src="tick.png" > '.$urlarray[$i].'<br><br>';
}
//Insert Active Links into the database
$res=mysqli_query($con,"SELECT * from links where url='$urlarray[$i]' ");
$count=mysqli_num_rows($res);
if($count==0){
$sql="INSERT INTO links (url,referer,anchor_pool)
VALUES ('$urlarray[$i]','$_GET[url]','$urlanchor[$i]')";
mysqli_query($con,$sql);
}
else{
$res=mysqli_query($con,"SELECT * from links where url='$urlarray[$i]' ");
while($row=mysqli_fetch_array($res)){
$referers=explode(" ",$row['referer']);
$refcount=0;
for($j=0;$j<count($referers);$j++){
if($_GET['url']==$referers[$j]){
$refcount++;
//echo "same referer";
}
if($_GET['url']==$urlarray[$i]){
$refcount++;
//echo "same referer";
}
}
if($refcount<1){
$newreferer=$row['referer']." ".$_GET['url'];
$sql="update links set referer='$newreferer' where url='$urlarray[$i]' ";
mysqli_query($con,$sql);
$anchor=$row['anchor_pool'].' '.$urlanchor[$i];
$anchors=explode(" ",$anchor);
$anchors=array_unique($anchors);
$anchors=array_values($anchors);
$final_anchor=implode(' ',$anchors);
$sql="update links set anchor_pool='$final_anchor' where url='$urlarray[$i]' ";
mysqli_query($con,$sql);
}
}
}
}
}
$errors = array_filter($urlarray);
if (!empty($errors)) {
}
else{
echo "Either the URL is down or page contains no Links !, Try entering URL along with protocol used.";
}
$prime=$_GET['url'];
$res=mysqli_query($con,"SELECT * from links where url='$prime' ");
$count=mysqli_num_rows($res);
if($count==0){
$sql="INSERT INTO links (url,referer,anchor_pool,backlinks,status)
VALUES ('$_GET[url]','','','0','1')";
mysqli_query($con,$sql);
}
else{
$file_headers = #get_headers($prime);
if($file_headers[0] == 'HTTP/1.1 200 OK') {
$sql="update links set status='1' where url='$prime' ";
mysqli_query($con,$sql);
}
}
$res=mysqli_query($con,"SELECT * from links ");
while($row=mysqli_fetch_array($res)){
$bkarray=array_filter(explode(" ",$row['referer']));
for($i=0;$i<count($bkarray);$i++){
$base_url=parse_url($bkarray[$i]);
$bkarray[$i]=$base_url['host'];
}
$bkarray=array_unique($bkarray);
$bkarray=array_values($bkarray);
$bkarray=array_filter($bkarray);
$bk=count($bkarray);
$sql="update links set backlinks='$bk' where url='$row[url]' ";
mysqli_query($con,$sql);
}
?>
The DOMDocument class is an HTML/XML parser. Period.
The code you haven't shared probably makes use of PHP stream wrappers to transparently download a remote resource via HTTP using the same syntax as loading local files. That's an entirely different task. As far as I know, PHP does not bundle a full-featured web crawler as part of its builtin libraries.
Edit: Here's where the complete download takes place:
$doc->loadHTMLFile($_GET['url']);
Everything after this line is not caused by download issues.
In order to generate a XML i am using following Code currently.
.<?php
require ('../dbconfig/dbconfig.php');
$appId = $_GET['id'];
$sqlTabs = "Select _id,tab_title,position from tab_info where app_id=$appId order by position ";
$resultTabs=mysql_query($sqlTabs );
$countTabs=mysql_num_rows($resultTabs);
if($countTabs>0)
{
echo '<application applicationName="sample app">';
echo '<tabs>';
while ($rowTab = mysql_fetch_array($resultTabs) ) {
echo '<tab id="t'.$rowTab['_id'].'" tabtitle="'.$rowTab['tab_title'].'" position="'.$rowTab['position'].'" data="somedata">';
$sqlTabItems = "Select _id as tabitemId,item_type,item_title,item_data from items_info where tab_id=".$rowTab['_id']." and parent_id=0 order by _id ";
$resultTabItems=mysql_query($sqlTabItems);
$countTabItems=mysql_num_rows($resultTabItems);
if($countTabItems>0)
{
$level = 1;
echo '<listItems>';
while ($rowTabItem = mysql_fetch_array($resultTabItems) ) {
echo '<listItem id="'.$rowTabItem['tabitemId'].'" parentId="t'.$rowTab['_id'].'" itemtype="'.$rowTabItem['item_type'].'" itemtitle="'.$rowTabItem['item_title'].'" itemdata="'.$rowTabItem['item_data'].'" level="'.$level.'">';
giveitems($rowTabItem['tabitemId'],$rowTab['_id'],$level);
echo '</listItem>';
}
echo '</listItems>';
}
else
echo 'No Data';
echo '</tab>';
}
echo '</tabs></application>';
}
else
{
echo 'No Data';// no tabs found
}
function giveitems($pitemId,$tabId,$level)
{
$sqlItems = "Select _id,item_type,item_title,item_data from items_info where parent_id=".$pitemId." order by _id ";
$resultItems=mysql_query($sqlItems);
$countItems=mysql_num_rows($resultItems);
$numbers = 0;
if($countItems>0)
{
$level = $level +1;
echo '<listItems>';
while ($rowItem = mysql_fetch_array($resultItems) ) {
echo '<listItem id="'.$rowItem[0].'" parentId="'.$pitemId.'" itemtype="'.$rowItem[1].'" itemtitle="'.$rowItem[2].'" itemdata="'.$rowItem[3].'" level="'.$level.'">';
/*********** Recursive Logic ************/
if(giveitems($rowItem[0],$tabId,$level)==1)
{
echo '</listItem></listItems>';
return 1;
}
else
{
echo '</listItem></listItems>';
return -1;
}
}
}
else
{
echo 'No Data';// no tabs found
return -1;
}
}
?>
Now in this code i want to replace all echo statements with a String variable and then i want to write that String variable content into a file , the porblem is if i define the string variable at the top of the file even then also that string variable cannot accessible from the giveItems functions below.
Pls suggest some solution
To access a global variable from within a function you need to write global $varname; at the top of that function's definition. Example:
function giveitems($pitemId,$tabId,$level) {
global $xmlstring;
// ....
}
However, this is pretty bad practice nowadays and you'd be better off writing a class that will both produce the XML and write it to a file.
How do i validate $_GET thats the number coming from correct source.
My url look like : index.php?page=items&catID=5
When users put something like 3 which is doesn't exist on catID. I want it to display error message.
$catID = intval($_GET["catID"]);
if($catID) {
$checkSQL = mysql_query("SELECT * FROM category WHERE category_type='2'");
while($checkROW = mysql_fetch_array($checkSQL)) {
$checkCAT != $checkROW["categoryID"];
echo "err msg";
}
This i can come up so far but it doesn't working as it fire error msg even in correct page.
Thank you
wallk makes a good point, there is a missing if. but if i read this correctly, wouldn't something along the lines of this be more what you are going for? Right now the line:
if($catID) {
is actually only checking if catID (or, catID from the $_GET) is non-zero (not false). My guess if you are looking to check if catID is the categoryID returned from SQL?
$catID = intval($_GET["catID"]);
checkcat($catID);
function checkcat($check_category) {
$checkSQL = mysql_query("SELECT * FROM category WHERE category_type='2'");
while($checkROW = mysql_fetch_array($checkSQL)) {
if ( $check_category != $checkROW["categoryID"] ) {
echo "err msg";
} else {
echo "not an error message";
}
}
}
Expounding on what you are looking for, how about something like this then?
$catID = ($_GET["catID");
if ( !is_numeric($catID) ) {
echo "Not a numeric category!"
} else {
$checkSQLQuery = "SELECT * FROM category WHERE categoryID = '{$catID}' AND category_type='2'"
$resultSQL = mysql_query($checkSQLQuery, $db);
/* NOTE!: Guessing on what your database resouce
pointer is - it isn't included in the origin snippet.
Although, the last opened should be used by default if
this is left out. */
if ( mysql_num_rows($resultSQL) < 1 ) {
echo "Error message, category ID not found"
} else {
echo "Found it!"
}
}
Oh, I see. The first line inside the while loop should have an "if":
while ($checkROW = mysql_fetch_array($checkSQL)) {
if ($checkCAT != $checkROW["categoryID"])
echo "err msg";
It looks like you'll be wanting to use mysql_fetch_assoc(), rather than mysql_fetch_array().