XML as an alternative to if else - php

My site has a large number of products in the database. I want to add a product sheet for each product but the database has no set "slot" for it. So I was thinking of writing a php code into the template which checks the part number and use this to load the correct url for the product sheet as a link. For Example
<?php
if (strpos($product_sku,'KE15000/12') !== false) {
$factsheetimage_urlZ='/images/FactsheetBTN.png';
$factsheetweblink_url="images/factSheetKE15000/12.pdf";
} else if (strpos($product_sku,'KE2000/12') !== false) {
$factsheetimage_urlZ='/images/FactsheetBTN.png';
$factsheetweblink_url="images/factSheetKE20000/12.pdf";
} else {
$factsheetimage_urlZ='/images/blank.png';
}
?>
<div>
<a href="<?php echo $factsheetweblink_url;?>">
<img src="<?php echo $factsheetimage_urlZ;?>"></a>
</div>
At moment I'm using if else statements (I'm pretty new to PHP) and I was wondering if there's a way to check the $product_SKU against an XML document to auto load the correct link rather than doing around 300 if else statements. ($product_SKU is the unique product code loaded on each page)

There are a few ways to go about it.
If the $factsheetweblink_url can be generated base on the $product_sku in some programatic way, that would probably be my first preference. eg. $factsheetweblink_url = "images/factSheet{$product_sku}.pdf";
Secondly, adding this column to the database would be a the best option if possible.
Otherwise, the lookup table you mention is certainly possible, XML is one option. If you're writing it by hand, or it needs to be written by a non-technical person would be some considerations for choosing a format. If it's just you, I'd probably use a simpler format (even a plain PHP array).
A simple example of this type of mapping as a PHP array might look like:
sku_url_map.php:
<?php
return [
'KE15000/12' => 'images/factSheetKE15000/12.pdf',
'KE20000/12' => 'images/factSheetKE20000/12.pdf',
];
product_page.php:
<?php
$sku_url_map = require 'sku_url_map.php';
// ...
if (isset($sku_url_map[$product_sku])) {
$factsheetweblink_url = $sku_url_map[$product_sku];
}
of course, more complex structures can be used if it's more that a simple 1:1 mapping.

Related

query string in php url which fetches values from files in directories

for security reasons we need to disable a php/mysql for a non-profit site as it has a lot of vulnerabilities. It's a small site so we want to just rebuild the site without database and bypass the vulnerability of an admin page.
The website just needs to stay alive and remain dormant. We do not need to keep updating the site in future so we're looking for a static-ish design.
Our current URL structure is such that it has query strings in the url which fetches values from the database.
e.g. artist.php?id=2
I'm looking for a easy and quick way change artist.php so instead of fetching values from a database it would just include data from a flat html file so.
artist.php?id=1 = fetch data from /artist/1.html
artist.php?id=2 = fetch data from /artist/2.html
artist.php?id=3 = fetch data from /artist/3.html
artist.php?id=4 = fetch data from /artist/4.html
artist.php?id=5 = fetch data from /artist/5.html
The reason for doing it this way is that we need to preserve the URL structure for SEO purposes. So I do not want to use the html files for the public.
What basic php code would I need to achieve this?
To do it exactly as you ask would be like this:
$id = intval($_GET['id']);
$page = file_get_contents("/artist/$id.html");
In case $id === 0 there was something else besides numbers in the query parameter. You could also have the artist information in an array:
// datafile.php
return array(
1 => "Artist 1 is this and that",
2 => "Artist 2..."
)
And then in your artist.php
$data = include('datafile.php');
if (array_key_exists($_GET['id'], $data)) {
$page = $data[$_GET['id']];
} else {
// 404
}
HTML isn't your best option, but its cousin is THE BEST for static data files.
Let me introduce you to XML! (documentation to PHP parser)
XML is similar to HTML as structure, but it's made to store data rather than webpages.
If instead your html pages are already completed and you just need to serve them, you can use the url rewriting from your webserver (if you're using Apache, see mod_rewrite)
At last, a pure PHP solution (which I don't recommend)
<?php
//protect from displaying unwanted webpages or other vulnerabilities:
//we NEVER trust user input, and we NEVER use it directly without checking it up.
$valid_ids = array(1,2,3,4,5 /*etc*/);
if(in_array($_REQUEST['id'])){
$id = $_REQUEST['id'];
} else {
echo "missing artist!"; die;
}
//read the html file
$html_page = file_get_contents("/artist/$id.html");
//display the html file
echo $html_page;

Using PHP url variables/php includes

What I'm trying to do is to create a URL, example:
article.php?00001
Then using the following code this will include 00001 as an article within article.php
if(isset($_GET['00001'])){
include('00001.php');
}else if(isset($_GET['00002'])){
include('00002.php');
} else {
include('noarticle.php');
}
Now, this works, and would be suitable for several articles if I just keep adding 00003-00010 etc, but if I intend to add MANY more articles, is there a better way of coding this without having to manually insert article numbers?
Use a database to store your articles. Have a look at http://www.freewebmasterhelp.com/tutorials/phpmysql for a guide on how to use MySQL with PHP.
With regards to your URLs, use article.php?id=### then use $_GET['id'] to determine which article is being viewed.
By including files based on user-supplied data, what if the user goes to article.php?article - it tries to load article.php which tries to load article.php which tries to ... you get the idea.
Just make it dynamic!
I would do something like this:
article.php?id=id_of_my_article
if(isset($_GET['id'])) include($_GET['id'].".php");
else include('noarticle.php');
First you need to know that it's insecure to include files simply based on url. There are other better means of doing so, as #Joe and #Angelo Cavallini wrote.
But if you are well aware of the consequences and determined to do so, you man try:
$id = current( $_GET );
$id && $id=intval($id);
if( $id ){
include( $id.'php' );
}

Vaildate a Zip code against a list

I want to have a form on my intranet site... basically we are a home improvement company and have a list of bad area codes that we do not do business in ... IE list of bad zips 19020 19021 etc are bad so if they are I want it to return with a popup which says bad area ... if it is not on the list I want it to say Good Area
You haven't given too much information, so what follows is a very general solution. One way to approach this is to have two maps called badZips and goodZips:
var badZips = {
"19020": true,
"19021": true
...
};
var goodZips = {
"90210": true,
...
};
Then in your form-validation function, you can do:
if(badZips[zip]) {
alert("You entered a bad zip code");
}
else if(goodZips[zip]) {
alert("You entered a good zip code");
}
else {
alert("That zip code is not recognized");
}
Actually creating the maps depends on how your webapp is set up. How do you store the zips - is it in the database? Or have you hardcoded it?
Using apache, install geoIP. Echo their zipcode into a javascript function, which compares to a black-list you created.
http://www.maxmind.com/app/ip-location
Your functional requirements are pretty simple but you didn't really mention what setup you have. Do you want this functionality to happen on a form? What are you going to code with? Do you have a database? Based on the tags you've used I'll just assume that you don't have a database.
Basically you can have a list of area codes and a flag for each to indicate if it's a bad or a good code. You can keep this list in a multi-dimensional array in PHP as static data (http://www.webcheatsheet.com/PHP/multidimensional_arrays.php).
So it might look something like:
<?php
$areaCodes = array( array('aCode'='19020','aFlag'=>true),
array('aCode'='19021','aFlag'=>true),
array('aCode'='19022','aFlag'=>false)
);
?>
When you need an area code to be validated, just do a search in the array and check the flag to see if it's a good code or a bad code.
Store the zip codes in an array, then check if the given zip is in the array.
<?php
$BadZip = array("19020", "19021");
if (in_array($Zip, $BadZip))
{
echo "Bad Zip code!";
}
?>
If in_array returns true, then the zip code is in the list of bad zips.
Alternatively you could use the same method with a list of good zips.

php refactoring and better coding for php?

i have this process that is the heart of my app, that im creating, but for some reason i feel like its the worst way to do it(instinct) , and i wanted to see if thier is something wrong with this process, and am i approaching it in a bad way! p.s. the code works fine, just refactoring problem.
the process is:
users go to homepage, they see thier latest activities, by other site memebers(home.php),
//function to bring the latest activities from database
$results=function getUserUpdates($_SESSION['user_id'];
while($row = mysql_fetch_array($results))
{
//another function to format the activities in a social stream
echo formatUpdate($row['user_note'],$row['dt'],$row['picture'],$row['username'],$row['id'],$row['reply_id'],$row['reply_name'],$row['votes_up'],$row['votes_down']);
}
i have put the function codes in pastie.
formatUpdate function http://pastie.org/1213958
getUserUpdates function http://pastie.org/1213962
EDIT both functions are from different files they are included in home.php,
formatUpdate from functions.php
getUserUpdates from queries.php
First of all, it's good that you have separate functions for getting the data and for formatting the data. It's a good start toward refactoring your code. It makes it easier in the future: if you ever want to format your data differently, you can just expand your formatter.
Second, this is what coreyward meant by a lambda:
$results=function getUserUpdates($_SESSION['user_id'];
Remove the function keyword. You use function when you're defining a function. But here you're only calling one. (You defined it in queries.php.)
Third, I agree with webbiedave about the echo statements. A good way to avoid that: In the "heart" of your app, collect all the HTML into one place. Then, when you've collected everything you're going to display on the page, you can echo it all at once. This makes it a lot easier to keep track of what you're doing, and to remember the order of everything. It also makes it easier to add headers and footers, or do more formatting. Otherwise, if you have echo statements scattered around your code, it's a lot easier to let something slip that shouldn't be there.
Here's a very basic example of what I mean:
$html = '';
$results = getUserUpdates($_SESSION['user_id'];
while($row = mysql_fetch_array($results)) {
$fields = array(
'user_note' => $row['user_note'],
'dt' => $row['dt'],
'picture' => $row['picture'],
'username' => $row['username'],
'id' => $row['id'],
'reply_id' => $row['reply_id'],
'reply_name' => $row['reply_name'],
'votes_up' => $row['votes_up'],
'votes_down' => $row['votes_down'],
);
$html .= formatUpdate($fields);
}
// This way you can do whatever you want to $html here.
echo $html;
Also notice that I put all the fields from $row into an array and passed it to formatUpdate(). That has two advantages:
It's easier to read.
If you ever
want to change the fields that
formatUpdate deals with, you don't
have to worry about searching
through your code to change the
arguments every time you call it.
Firstly, I think you mean:
$results = getUserUpdates($_SESSION['user_id']);
In your getUserUpdates() function there is a redundant branch:
if ($username == $_SESSION['u_name']){
// return something
}
if ($username != $_SESSION['u_name']){
// return something else
}
You don't need the second if statement as any code run at that point will only be run if $username != $_SESSION['u_name'].
In my opinion, it's usually better not to have different functions directly echoing HTML up the stack (such as echoVote()). It's preferred to have functions return data and have the original caller echo it. This allows the caller to perform additional data massaging if desired.
Other than that, your code is fetching data, looping through and acting on the results which is pretty much standard fare.
I think your instinct is to be a little too harsh on yourself ;) There are improvements to be made but it's certainly not the worst way to do anything.

Fetch database information on a new page without using new documents

I'm working on a page where I've listed some entries from a database. Although, because the width of the page is too small to fit more on it (I'm one of those people that wants it to look good on all resolutions), I'm basically only going to be able to fit one row of text on the main page.
So, I've thought of one simple idea - which is to link these database entries to a new page which would contain the information about an entry. The problem is that I actually don't know how to go about doing this. What I can't figure out is how I use the PHP code to link to a new page without using any new documents, but rather just gets information from the database onto a new page. This is probably really basic stuff, but I really can't figure this out. And my explanation was probably a bit complicated.
Here is an example of what I basically want to accomplish:
http://vgmdb.net/db/collection.php?do=browse&ltr=A&field=&perpage=30
They are not using new documents for every user, they are taking it from the database. Which is exactly what I want to do. Again, this is probably a really simple process, but I'm so new to SQL and PHP coding, so go easy on me, heh.
Thanks!
<?php
// if it is a user page requested
if ($_GET['page'] == 'user') {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// db call to display user WHERE id = $_GET['id']
$t = mysql_fetch_assoc( SELECT_QUERY );
echo '<h1>' . $t['title'] . '</h1>';
echo '<p>' . $t['text'] . '</p>';
} else {
echo "There isn't such a user".
}
}
// normal page logic goes here
else {
// list entries with links to them
while ($t = mysql_fetch_assoc( SELECT_QUERY )) {
echo '<a href="/index.php?page=user&id='. $t['id'] .'">';
echo $t['title'] . '</a><br />';
}
}
?>
And your links should look like: /index.php?page=user&id=56
Note: You can place your whole user page logic into a new file, like user.php, and include it from the index.php, if it turns out that it it a user page request.
Nisto, it sounds like you have some PHP output issues to contend with first. But the link you included had some code in addition to just a query that allows it to be sorted alphabetically, etc.
This could help you accomplish that task:
www.datatables.net
In a nutshell, you use PHP to dynamically build a table in proper table format. Then you apply datatables via Jquery which will automatically style, sort, filter, and order the table according to the instructions you give it. That's how they get so much data into the screen and page it without reloading the page.
Good luck.
Are you referring to creating pagination links? E.g.:
If so, then try Pagination - what it is and how to do it for a good walkthrough of how to paginate database table rows using PHP.

Categories