php

Add a remove_filter function

To stop Wordpress from putting tags around your content, you can use the following Wordpress function call:
remove_filter('the_content', 'wpautop');
To apply this function to your template, just put the function statement in a file called "functions.php" in your main directory of your wordpress template. If the functions.php does't exist, just create it.

Taggings:

PDF from Database using FPDF

First Page is a form to accept student id and course id

Create Certificate

Create Certificate

Student ID:
Course ID:

The second page (certificatereportpdf.php)

<?php
define('FPDF_FONTPATH','font/'); // so fpdf knows where the fonts are when it starts writing
require('mysql_table.php'); //on this page, the table selection was already done
$date=date(date);
class PDF extends PDF_MySQL_Table
{
function Header() // to make the certificate look nice
{
//Title
$this->SetFont('Arial','',14);

$this->Cell(0,6,'Certificate ',0,1,'C');
$this->Ln(10);

$this->Cell(0,6,'$date ',0,1,'C');// these are like text boxes
$this->Ln(10);

$this->Cell(0,6, 'This is the official Certificate.',0,1,'L');
$this->Ln(16);

//Ensure table header is output
parent::Header();
}
}

//Connect to database
mysql_connect('localhost','root','');
mysql_select_db('studentsdb');

$studentid=$_POST['studentid'];
$courseid=$_POST['courseid'];
$date=date(date);

//create a new page
$pdf=new PDF();
$pdf->Open();
$pdf->AddPage();

//table: specify columns

$pdf->AddCol('studentid',25,'Student ID','C');
$pdf->AddCol('firstname',25,'First Name','L');
$pdf->AddCol('lastname',25,'Last Name','L');
$pdf->AddCol('courseid',25,'Course ID','L');
$pdf->AddCol('result',35,'Result Type','L');
$pdf->AddCol('timestaken',30,'Organization','L');

$prop=array('HeaderColor'=>array(255,150,100),
'color1'=>array(210,245,255),
'color2'=>array(255,255,210),
'padding'=>2);

//insert the fields into the columns of the table
$pdf->Table('studentid,firstname,lastname,courseid,result,timestaken from amalgamation where studentid="$studentid" && courseid=$courseid order by ',$prop);

//show it
$pdf->Output();
?>

Taggings:

PDF from Database using FPDF

This solutions came to my mind when i was asked to allow registrar to create student certificates online when they were using the school's local website - similar to TISS certificate generator - i used the free FPDF library which is a PHP class which allows to generate PDF files with pure PHP - the aim is to allow the registrar of school to be able to take the student’s id and course id and generate the student's certificate for a course - the main aim is to show how the class is used in a simple and easy way for use in a small scale - There are two files. The first file, the user inputs the student id and course id and hits create certificate. The file points to the fpdf file that goes and creates a pdf file and displays the certificate

Problem with loading of side pages on localhost

After the installation of wordpress on my localhost I had a problem when I wanted to check my side pages on localhost.Page not found constantly popped up.Only the main page could be loaded and checked.I figured out that I did not connect localhost properly and the solutions online were mostly unadequate.For someone who just started with usage of these technologies can be very irritating since the solutions are prety simple but yet you loose a lot of time trying to solve it . Bellow the solution is attached

Taggings:

Dismantling a simple theme into more php files for easier organisation

Download the free simple theme online and copy it to your work folder.There will be only one index file in which all html is contained starting from header to footer.Doing a php programming in that file would be pretty difficult and unorganised and the code would be very untidy.So,the challenge is to dismantle the theme into more pieces using simple php. Sollution is attached bellow

Taggings:

Connecting wordpress with localhost

Setting up a wordpress on localhost to do the work offline is not difficult but for those who are starting up with web development can be pretty iritating. So the task is to install and set up the wamp or xamp server and then install and implement wordpress on your localhost. Make an adequate changes in wp_config_sample.php file in order to connect it properly. Connect the wordpress with mysql. Solution is attached on chalenge

Taggings:

Complex Query Example

In CakePHP there exist two different ways of achieving the desired goal:

1)

$techData = $this->find('all', array(
    'fields' => array('Table1.field_1', 'Table1.field_2', 'Table2.field_3'),
    'alias' => 'Table1'
    'joins' => array(
        array(
            'table' => 'table_2',
            'alias' => 'Table2',
            'type' => 'INNER',
            'conditions' => array(
                'Table2.field_1 = Table1.field_1'
            )
        )
    ),
    'conditions' => array(
        'field_1' => $cur_id,
        'language_id' => Configure::read('language_id'),
        'active' => true
     ),
    'order' => array('field_1 ASC', 'field_2 ASC'),
    'recursive' => -1
));

Here two tables are joined on a common field (e.g. the ID field), if one wants to add additional tables, these can be added easily by just appending them to the 'joins' array. This approach is the preferred one, since it uses only the native CakePHP way of creating SQL statements and thus benefits from all inbuilt security measures.

2)

The second approach would be to use the capability of CakePHP to create queries with raw SQL, however, this approach is discouraged, since it is potentially vulnerable to SQL injection, as the responsibility for handling such a case is transferred from the framework to the user. Still, it shall be shown here. It basically works like this:

$this->[ModelName]->query("SELECT ... ");

Taggings:

Complex Queries in CakePHP 2.x

With CakePHP, a MVC-based PHP framework, it is usually very easy to retrieve data from the database table underlying a specific model, as well as in case the tables are connected with each other through their respective model declarations, as these tables are then joined automatically. However, when one wants to join multiple tables within one query and they are not connected through their models (which occurs quite often), then there nevertheless has to be a way to join the desired tables to get the respective data. The goal is to find a way in CakePHP to accomplish this task.

How to implement a custom paging script for a variable number of items (incl. PHP sample script)

Will explain the solution to this problem with using a code written in PHP (you should be able to adapt this for other programming languages quite easily).

// first of all, we need the total number of all items to display (in the example this would be 23), usually a database count statement will give this number
$resultsOverall = 0;

// enter the maximum number of items per page here
$resultsPerPage = 10;

// the number of the current page (e.g. page 2 display items 9-16 in the example)
$pageNumber = 1;

// the current number is usually determined dynamically, that means we have to check which page we need to display
if(isset($_REQUEST["pageNumber"]) && $_REQUEST["pageNumber"] > 1) {
$pageNumber = $_REQUEST["pageNumber"];
}

/**** The logic ****/

// determine the first result to show (on example page 2 this will be 9)
$resultsFrom = ($pageNumber*$resultsPerPage-$resultsPerPage+1);

// determine the last result to show (on example page 2 this will be 16)
$resultsTo = ($resultsFrom-1)+$resultsPerPage;

// if the number of results to is bigger than the number of results overall, cut it (e.g. on example page three $resultsTo would be 24, but $resultsOverall would be 23, therefore it is cut)
if($resultsTo > $resultsOverall) {
$resultsTo = $resultsOverall;
}

// as a last step we have to determine the number of pages
$allPages = ceil($resultsOverall / $resultsPerPage);

// now we could proceed with some query ("SELECT * FROM items LIMIT $resultsFrom, $resultsTo") and display anything we need

Taggings:

Implementing secure a secure session management system: A solution approach (implemented in PHP)

The following four problems can be identifiyed when using native PHP sessions (and these can be partly solved):

Problem 1: The session ID is the only thing, which is being used to identify a client
Solution 1: Use additional information about your client, to improve chances, that the identifiyed client is honestly the correct one (e.g. Client IP Adresss (be aware of proxies), Client User Agent, ...)

Problem 2: The process of generating client IPs can be reproduced by an attacker
Solution 2: Use a secure mechanism to generate your session IDs, which is not reproducible

Problem 3: Sessions exist longer than they should (which makes attackes easier)
Solution 3: Instant destruction of session ID if the server suspects that there might be something going wrong

Problem 4: Sessions IDs may be stolen using malicious JavaScript
Solution 4: Use only session cookies and make your cookie HTTP-only

The following PHP is a solution approach to make a secure session management in PHP:

/*
* This file is for generating save sessions.
*/
final class Session {

/**
* Secure start of a session.
*
* @return type
*/
public static function startSession() {

session_name("unique_session_id_name");

// try to start the session
$ok = @session_start();

// no session existing, make a new session
if (!$ok) {
// replace the Session ID
self::session_regenerate_save_id();
// start session
session_start();
}

// make the session cookie secure: HTTPonly and if possible HTTPS
$force_ssl_cookie = false;

$currentCookieParams = session_get_cookie_params();
$sidvalue = session_id();
setcookie(
"sess-aphk-".APP_ID,//name
$sidvalue,//value
0,//expires at end of session
$currentCookieParams['path'],//path
$currentCookieParams['domain'],//domain
$force_ssl_cookie,
true
);

// If the session was already existing, we must have set the client ip
if (isset($_SESSION["client_ip"])) {

// If this client ip does not match the ip of the current client, this might be an attack --> destroy session
if (self::getSessionClientIP() === $_SESSION["client_ip"] && self::getSessionClientAgent() === $_SESSION['client_agent']) {
if(self::checkStillActive()) {
return true;
}
} else {
self::destroy_session_absolute();
header('Location: '.$_SERVER['REQUEST_URI']);
die;
}

} else {
// if we have to create a new session, we do it in a secure, self-defined way
self::destroy_session_absolute();
self::session_regenerate_save_id();
session_start();
self::setSessionClientIP();
self::setSessionClientAgent();
$_SESSION['last_activity'] = time();
}
}

// creates a new, secure session id (MUST be called BEFORE session_start())
public static function session_regenerate_save_id() {
$hash_time = md5(microtime());
$hash_ip = md5($_SERVER["REMOTE_ADDR"]);
$hash_space = sha1(disk_free_space(getcwd()));
$session_id = sha1($hash_time . $hash_ip . $hash_space);
session_id($session_id);
}

// sets the session IP of the current client
private static function setSessionClientIP() {

if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$_SESSION["client_ip"] = md5($_SERVER["HTTP_X_FORWARDED_FOR"]);
} else {
$_SESSION["client_ip"] = md5($_SERVER["REMOTE_ADDR"]);
}
}

// retrieves the client IP of the session owner
private static function getSessionClientIP() {
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
return md5($_SERVER["HTTP_X_FORWARDED_FOR"]);
} else {
return md5($_SERVER["REMOTE_ADDR"]);
}
}

private static function setSessionClientAgent() {
$_SESSION['client_agent'] = md5($_SERVER['HTTP_USER_AGENT']);
}

private static function getSessionClientAgent() {
return md5($_SERVER['HTTP_USER_AGENT']);
}

// secure, instant session destruction
public static function destroy_session_absolute() {
session_name("sess-aphk-".APP_ID);
if(session_id()) {
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), "", time() - 42000, "/");
}
session_destroy();
}
}

// retrieve the current session id
public static function get_current_session_id() {
session_name("sess-aphk-".APP_ID);
return session_id();
}

public static function checkStillActive() {
// make sure that a user was not inactive for too long
if(intval($_SESSION['last_activity']) < time()-1200) { //have we expired?
self::destroy_session_absolute();
header('Location: '.$_SERVER['REQUEST_URI']);
die;
} else { //if we haven't expired:
$_SESSION['last_activity'] = time(); //this was the moment of last activity.
return true;
}
}
}

Pages

Subscribe to php