I want to check if my current URL contains "/demo" at the end of the url, for example mysite.com/test/somelink/demo to do something.
Here is my attempt :
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'mysite.com/test/somelink/demo')
{
// Do something
}
else
{
// Do something
}
This seems to work fine, but the problem is that /somelink needs to by dynamic.
Any suggestion on how can I do this ?
Thank you !
Edit:
<?php
/* An abstract class for providing form types */
abstract class ECF_Field_Type {
private static $types = array();
protected $name;
/* Constructor */
public function __construct() {
self::register_type( $this->name, $this );
}
if(basename($_SERVER['REQUEST_URI']) == 'stats'){
echo "Hello World";
}
/* Display form field */
public abstract function form_field( $name, $field );
/* Display the field's content */
public function display_field( $id, $name, $value ) {
return "<span class='ecf-field ecf-field-$id'>"
. "<strong class='ecf-question'>$name:</strong>"
. " <span class='ecf-answer'>$value</span></span>\n";
}
/* Display field plain text suitable for email display */
public function display_plaintext_field( $name, $value ) {
return "$name: $value";
}
/* Get the description */
abstract public function get_description();
}
?>
Just use,
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
// Do something
}
<?php
if (preg_match("/\/demo$/", $_SERVER['REQUEST_URI'])) {
// Do something
} else {
// Do something else
}
?>
This post has PHP code for simple startsWidth() and endsWith() functions in PHP that you could use. Your code would end up looking like:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith($host, '/demo'))
{
// Do something
}
else
{
// Do something
}
But one thing you might want to do in addition to that is convert $host to lowercase so the case of the URL wouldn't matter. EDIT: That would end up looking like this:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(endsWith(strtolower($host), '/demo'))
you can use strpos
$host = 'mysite.com/test/somelink/demo';
if(strpos($host,'demo'))
{
// Do something
echo "in Demo";
}
else
{
// Do something
echo "not in Demo";
}
$str = 'demo';
if (substr($url, (-1 * strlen($str))) === $str) { /**/ }
Related
I am using a translator class i found online. It works phenomenally when I use it to directly echo the message. The problem occurs when I do conditional checks at the beginning of the page and I need to have the translated text in the variable to then send it to other places on the page to be displayed.
My code:
if ($condition_1){
$message = $translate->__('Text 1');
}
elseif ($condition_2){
$message = $translate->__('Text 2');
}
elseif ($condition_3){
$message = $translate->__('Text 3');
}
This code echos the text in the place where this condition is put, not used as the variable $message and then echos when I need it to. Can you help me to figure out how to use the text as a variable.
If I use the text with no translator class. I can easily use it as a variable.
This is the class i use:
class Translator {
private $language = 'sl';
private $lang = array();
public function __construct($language){
$this->language = $language;
}
private function findString($str) {
if (array_key_exists($str, $this->lang[$this->language])) {
echo $this->lang[$this->language][$str];
return;
}
echo $str;
}
private function splitStrings($str) {
return explode('=',trim($str));
}
public function __($str) {
if (!array_key_exists($this->language, $this->lang)) {
if (file_exists($this->language.'.txt')) {
$strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
foreach ($strings as $k => $v) {
$this->lang[$this->language][$v[0]] = $v[1];
}
return $this->findString($str);
}
else {
echo $str;
}
}
else {
return $this->findString($str);
}
}
}
The translated text is in the a *.txt file, looking like this:
text 1=text 1 translated
text 2=text 2 translated
text 3=text 3 translated
The problem was in the "echo" in the class. I changed the "echo" with "return" and it works like a charm!
Studying some code from a codeigniter tut, the following preg_match pattern has me baffled:
preg_match('/js$/', $include)
What is the purpose of the $ after the js?
Thanks for the always thoughtful replies!
-----Complete Code-----
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Layouts Class. PHP5 only.
*
*/
class Layouts {
// Will hold a CodeIgniter instance
private $CI;
// Will hold a title for the page, NULL by default
private $title_for_layout = NULL;
// The title separator, ' | ' by default
private $title_separator = ' | ';
public function __construct()
{
$this->CI =& get_instance();
}
public function set_title($title)
{
$this->title_for_layout = $title;
}
public function view($view_name, $params = array(), $layout = 'default')
{
// Handle the site's title. If NULL, don't add anything. If not, add a
// separator and append the title.
if ($this->title_for_layout !== NULL)
{
$separated_title_for_layout = $this->title_separator . $this->title_for_layout;
}
// Load the view's content, with the params passed
$view_content = $this->CI->load->view($view_name, $params, TRUE);
// Now load the layout, and pass the view we just rendered
$this->CI->load->view('laytous/' . $layout, array(
'content_for_layout' => $view_content,
'title_for_layout' => $separated_title_for_layout
));
}
public function add_include($path, $prepend_base_url = TRUE)
{
if ($prepend_base_url)
{
$this->CI->load->helper('url'); // Load this just to be sure
$this->file_includes[] = base_url() . $path;
}
else
{
$this->file_includes[] = $path;
}
return $this; // This allows chain-methods
}
public function print_includes()
{
// Initialize a string that will hold all includes
$final_includes = '';
foreach ($this->includes as $include)
{
// Check if it's a JS or a CSS file
if (preg_match('/js$/', $include))
{
// It's a JS file
$final_includes .= '<script type="text/javascript" src="' . $include . '"></script>';
}
elseif (preg_match('/css$/', $include))
{
// It's a CSS file
$final_includes .= '<link href="' . $include . '" rel="stylesheet" type="text/css" />';
}
return $final_includes;
}
}
}
The dollar is an "end of string" anchor. The match will only succeed if "js" is at the end of the string.
Dollar sign means an end of line in regular expressions.
I implemented a multilanguage feature for my web application. I get the values by this
echo $lang['the key here'];
and i keep the values in a separate fiels like this
$lang['confirm'] = 'COnfirm the message';
$lang['deny'] = 'Deny the invitation';
so i want if somebody calls a undefined key like $lang['sdefscfef'] , insted of printing white space, I want to print the key name i.e 'sdefscfef'
I want to make it as a function
function translate($string) {
if(! isset($string)) {
echo THE KEY;
}
else {
echo $string;
}
}
translate($lang['asdadad']);
and to print the key
Instead of printing the array directly I would create a function (_() is common) and use it like so:
echo _('Welcome');
And the _() function would then look in the $language array:
function _ ($str) {
global $language;
return isset($language[$str]) ? $language[$str] : $str;
}
Something like that.
If you want to avoid using a global variable you can wrap all of this in a class like this:
class Lang {
private $lang = array();
public static translate ($str) {
return isset(self::$lang[$str]) self::$lang[$str] : $str;
}
}
And then, to avoid having to type Lang::translate() everywhere you can do this:
function _ ($str) {
return Lang::translate($str);
}
Here's an example of a little more advanced Language class: http://code.google.com/p/sleek-php/source/browse/trunk/Core/Lang.php
Use simply:
$lang['confirm'] = 'COnfirm the message';
$lang['deny'] = 'Deny the invitation';
....
function getTranslation($key) {
global $lang;
if (isset($lang[$key])) {
return $lang[$key];
} else {
return $key;
}
}
// Usage:
echo getTranslation('confirm'); // Prints 'Confirm the message'
echo getTranslation('sjdhj'); // Prints 'sjdhj'
Let's say I have a class...
class A {
private $action;
private $includes;
public function __construct($action, $file) {
//assign fields
}
public function includeFile()
include_once($this->file);
}
$a = new A('foo.process.php', 'somefile.php');
$a->includeFile();
As you can see, includeFile() calls the include from within the function, therefore once the external file is included, it should technically be inside of the function from my understanding.
After I've done that, let's look at the file included, which is somefile.php, which calls the field like so.
<form action=<?=$this->action;?> method="post" name="someForm">
<!--moar markup here-->
</form>
When I try to do this, I receive an error. Yet, in a CMS like Joomla I see this accomplished all the time. How is this possible?
Update
Here's the error I get.
Fatal error: Using $this when not in object context in /var/www/form/form.process.php on line 8
Update 2
Here's my code:
class EditForm implements ISave{
private $formName;
private $adData;
private $photoData;
private $urlData;
private $includes;
public function __construct(AdData $adData, PhotoData $photoData, UrlData $urlData, $includes) {
$this->formName = 'pageOne';
$this->adData = $adData;
$this->photoData = $photoData;
$this->urlData = $urlData;
$this->includes = $includes;
}
public function saveData() {
$this->adData->saveData();
$this->photoData->saveData();
}
public function includeFiles() {
if (is_array($this->includes)) {
foreach($this->includes as $file) {
include_once($file);
}
} else {
include_once($this->includes);
}
}
public function populateCategories($parent) {
$categories = $this->getCategories($parent);
$this->printCategories($categories);
}
public function populateCountries() {
$countries = $this->getCountries();
$this->printCountries($countries);
}
public function populateSubCategories() {
//TODO
}
private function getCategories($parent) {
$db = patentionConnect();
$query =
"SELECT * FROM `jos_adsmanager_categories`
WHERE `parent` = :parent";
$result = $db->fetchAll(
$query,
array(
new PQO(':parent', $parent)
)
);
return $result;
}
private function getCountries() {
$db = patentionConnect();
$query =
"SELECT `fieldtitle` FROM `jos_adsmanager_field_values`
WHERE fieldid = :id";
$result = $db->fetchAll(
$query,
array(
new PQO(':id', 29)
)
);
return $result;
}
private function printCountries(array $countries) {
foreach($countries as $row) {
?>
<option value=<?=$row['fieldtitle'];?> >
<?=$row['fieldtitle'];?>
</option>
<?php
}
}
private function printCategories(array $categories) {
foreach($categories as $key => $row){
?>
<option value=<?=$row['id'];?>>
<?=$row['name'];?>
</option>
<?php
}
}
}
And the include call (which exists in the same file):
$template = new EditForm(
new AdData(),
new PhotoData(),
new UrlData($Itemid),
array(
'form.php',
'form.process.php'
)
);
$template->includeFiles();
And the main file which is included...
if ($this->formName == "pageOne") {
$this->adData->addData('category', $_POST['category']);
$this->adData->addData('subcategory', $_POST['subcategory']);
} else if ($this->formName == "pageTwo") {
$this->adData->addData('ad_Website', $_POST['ad_Website']);
$this->adData->addData('ad_Patent', $_POST['ad_Patent']);
$this->adData->addData('ad_Address', $_POST['ad_Address']);
$this->adData->addData('email', $_POST['email']);
$this->adData->addData('hide_email', $_POST['hide_email']);
$this->adData->addData('ad_phone', $_POST['ad_phone']);
$this->adData->addData('ad_Protection', $_POST['ad_Protection']);
$this->adData->addData('ad_Number', $_POST['ad_Number']);
$this->adData->addData('ad_Country', $_POST['ad_Country']);
$this->adData->addData('ad_issuedate', $_POST['issuedate'] . '/' . $_POST['issuemonth'] . '/' . $_POST['issueyear']);
} else if ($this->formName == "pageThree") {
$this->adData->addData('name', $_POST['name']);
$this->adData->addData('ad_Background', $_POST['ad_Background']);
$this->adData->addData('ad_opeartion', $_POST['ad_operation']);
$this->adData->addData('ad_advlimit', $_POST['ad_advlimit']);
$this->adData->addData('ad_status', $_POST['ad_status']);
$this->adData->addData('ad_addinfo', $_POST['ad_addinfo']);
$this->adData->addData('ad_description', $_POST['ad_description']);
$this->adData->addData('tags', $_POST['tags']);
$this->adData->addData('videolink', $_POST['videolink']);
} else if ($this->formName == "pageFour") {
foreach($_POST['jos_photos'] as $photo) {
$this->photoData->addData(
array(
'title' => $photo['title'],
'url' => $photo['url'],
'ad_id' => $this->photoData->__get('ad_id'),
'userid' => $this->photoData->__get('userid')
)
);
}
}
Update
Strange: while the error itself hadn't been quite related to what the problem was, I found that it was simply an undefined field which I hadn't implemented.
Consider this thread solved. To those who replied, I certainly appreciate it regardless.
This should work. Are you sure you're doing the include from a non-static method that's part of the class (class A in your example)? Can you post the exact code you're using?
Edit: As general advice for problems like this, see if you can trim down the code so the problem is reproducible in a short, simple example that anyone could easily copy/paste to reproduce the exact error. The majority of the time, you'll figure out the answer yourself in the process of trying to simplify. And if you don't, it will make it much easier for others to help you debug.
Alright, I'm using a page creating class I found as below but when I want to use a php page -that again includes and uses a class file- for the content it either echoes on the top or the bottom of the page... I even tried to make the page a function() and call it at the $Content string but no use, again it echoed on the top of the page... How can i use a php page as a content in this class, or what should i change to use a php file?
Please keep in mind that I'm new to classes so feel free to assume some beginner mistakes.
<?php
class Page {
var $Title;
var $Keywords;
var $Content;
function Display( ) {
echo "<HTML>\n<HEAD>\n";
$this->DisplayTitle( );
$this->DisplayKeywords( );
echo "\n</HEAD>\n<BODY>\n";
echo $this->Content;
echo "\n</BODY>\n</HTML>\n";
}
function DisplayTitle( ) {
echo "<TITLE>" . $this->Title . "</TITLE>\n";
}
function DisplayKeywords( ) {
echo '<META NAME="keywords" CONTENT="' . $this->Keywords . '">';
}
function SetContent( $Data ) {
$this->Content = $Data;
}
}
?>
Usage:
<?php
include "page.class";
$Sample = new Page;
$Content = "<P>I want my php file's contents here.</P>";
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent( $Content );
$Sample->Display( );
?>
What if I wanted to make the content something like $Content = " < ? echo 'test'; ? >"; I know this isn't valid but what i'm trying to do is something like that or something like $Content = " output of the whateversinhere.php ";. how should I object orient another page therefore getting its contents into a string here?
You should NOT echo anything inside your class, instead the class should have a method getMarkup(), which will return a string containing the whole markup. Then you can echo that string in your view.
Additional tipps:
variables and method names start with a small letter!
title and keywords should have getters and setters too
make your variables private (private $title, etc.)
let me clean this up for you, you will notice some changes:
class Page
{
private $title = 'No Title';
private $keywords = array();
private $content = '';
public function setTitle($title)
{
$this->title = (string)$title;
}
public function addKeywords($keywords)
{
$this->keywords = array_merge($this->keywords, (func_num_args() > 1) ? func_get_args() : (array)$keywords;
}
function setContent($content)
{
$this->content = $content;
}
function appendContent($content)
{
$this->content .= $content;
}
function prependContent($content)
{
$this->content = $content . $this->content;;
}
private function display()
{
/*
* Display output here
*/
echo $this->title;
echo implode(',',str_replace(',','',$this->title));
echo $this->contents;
}
}
pretty simple usage:
$Page = new Page;
$Page->setTitle("Hello World");
$page->addKeywords("keyword1","keyword2","keyword3","keyword4");
//Content
$this->setContent("World");
$this->prependContent("Hello");
$this->appendContent(".");
//Display
$this->display();
Just got to fill in the blanks, you will learn as time goes on that you should not be using html directly within your class, and that you would split the above into several class such as Head,Body,Footer,Doctype and have a page class that brings them all together.
Use Output Control Functions.
<?php
include "page.class";
$Sample = new Page;
ob_start();
include "foobar.php";//What you want to include.
$content = ob_get_contents();
ob_end_clean();
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent($content);
$Sample->Display( );
?>