Archive for the ‘Php’ Category

SQL injectionThis article explains basics of SQL Injection with an example that shows SQL Injection, and provides methods to prevent from these attacks. As the name suggests,this attack can be done with SQL queries. Many web developers are unaware of how an attacker can tamper with the SQL queries. SQL-Injection can be done on a web application…

For Example Read more…..

Advertisements

email sendingIn this Tutorial How to Send Email Using PHP we will tell you basic things before going in deep.PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].

Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.

The configuration for Windows should look something like this:

[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only
sendmail_from = webmaster@tutorialspoint.com

Linux users simply need to let PHP know the location of their sendmail application.

The path and any desired switches should be specified to the sendmail_path directive.

The configuration for Linux should look something like this:

[mail function]
; For Win32 only.
SMTP =

; For win32 only
sendmail_from =

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i

Now you are ready to go:

Sending plain text email using PHP

Sending HTML email using PHP

Sending attachments with email using PHP

DebuggingPHP a well-known scripting language used for web development or we can say PHP is the most used scripting language in today’s web industry. Even most of popular CMSs are also developed and support PHP which makes PHP more popular as well. As the users increases respectively (to use PHP language for web development) there is need of PHP debuggers also increase. Because everyone wants that their code should be fine and error free. Debugger tool helps you in debugging errors in web applications and scripts by which makes innovative web development easy. In This post I have mentioned top 10 widely used PHP debuggers by developer, have a look.

Read More »

In this post of Upload Multiple Images with Jquery code allows to user can select and upload multiple images in single shot, Quick look this live demo. Download Script     Live Demo Sample database design for Users. Users Contains user details username, password, email, profile_image and profile_image_small etc. CREATE TABLE `users` ( `user_id` int(11) AUTO_INCREMENT PRIMARY KEY, `username` varchar(255) UNIQUE KEY, `password` varchar(100), `email`…

Read More »

 

Are you looking for image upload and Resize PHP script. I had implemented a simple PHP script to re-sizing image into different dimensions. It’s very useful to your web projects to save hosting space and bandwidth to reduce the original image to compressed size.

PHP Code
This script resize an Image into two 60px and 25px. Take a look at $newwidth you have to modify size values.

Read More »

This tutorial about my favorite place Dzone like data loading while page scrolling down with jQuery and PHP. We have lots of data but can not display all. This script helps you to display little data and make faster your website.
Load Data while Scrolling Page Down with jQuery and  PHP

Read More »

MySQL

Stop all services in wamp.

Then make changes to php.ini

post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M
max_allowed_packet = 200M (in mysql  my.ini  file)

Restart all services and it should be okay,

Now  XXXMb file upload very quickly.

 

I received lot of requests from my readers that asked to me how to implement Pagination with jQuery, PHP and MySQL. so I had developed a simple tutorial. It’s looks big but very simple script. Take a look at this live demo
Pagination with jQuery, MySQL and PHP.


The tutorial contains three PHP files and two js files includes jQuery plugin.

-config.php (Database Configuration)
-pagination.php
-pagination_data.php
-jquery.js
-jquery_pagination.js

Download Script     Live Preview

Database Table

CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT
);
 

jquery_pagination.js
Contains javascript this script works like a data controller.

$(document).ready(function()
{

//Display Loading Image

function Display_Load()
{
$(“#loading”).fadeIn(900,0);
$(“#loading”).html(“<img src=”bigLoader.gif” />”);
}

//Hide Loading Image

function Hide_Load()
{
$(“#loading”).fadeOut(‘slow’);
};

//Default Starting Page Results

$(“#pagination li:first”)
.css({‘color’ : ‘#FF0084’}).css({‘border’ : ‘none’});
Display_Load();
$(“#content”).load(“pagination_data.php?page=1”, Hide_Load());

//Pagination Click

$(“#pagination li”).click(function(){
Display_Load();

//CSS Styles

$(“#pagination li”)
.css({‘border’ : ‘solid #dddddd 1px’})
.css({‘color’ : ‘#0063DC’});

$(this)
.css({‘color’ : ‘#FF0084’})
.css({‘border’ : ‘none’});

//Loading Data

var pageNum = this.id;
$(“#content”).load(“pagination_data.php?page=” + pageNum, Hide_Load());
});

});

config.php
You have to change hostname, username, password and databasename.

<!–?php

$mysql_hostname = “localhost”;
$mysql_user = “username”;
$mysql_password = “password”;
$mysql_database = “database”;
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die(“Opps some thing went wrong”);
mysql_select_db($mysql_database, $bd)
or die(“Opps some thing went wrong”);

?>

pagination.php
User interface page.

<?php

include(‘config.php’);
$per_page = 9;

//Calculating no of pages
$sql = “select * from messages”;
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)

?>

// <![CDATA[
javascript” src=”http://ajax.googleapis.com/ajax/
// ]]>
libs/jquery/1.3.0/jquery.min.js”>
// <![CDATA[
javascript” src=”jquery_pagination.js”>
// ]]>

<div id=”loading” ></div>
<div id=”content” ></div>
<ul id=”pagination”>
<?php
//Pagination Numbers

for($i=1; $i<=$pages; $i++)
{
echo ‘<li id=”‘.$i.‘”>’.$i.‘</li>’;
}

?>
</ul>

pagination_data.php
Simple php script display data from the messages table.

<?php

include(‘config.php’);
$per_page = 9;
if($_GET)
{
$page=$_GET[‘page’];
}

$start = ($page-1)*$per_page;
$sql = “select * from messages order by msg_id limit $start,$per_page”;
$result = mysql_query($sql);

?>

<table width=”800px”>

<?php

while($row = mysql_fetch_array($result))
{
$msg_id=$row[‘msg_id’];
$message=$row[‘message’];

?>

<tr>
<td><?php echo $msg_id; ?></td>
<td><?php echo $message; ?></td>
</tr>

<?php

}

?>

</table>

CSS Code
CSS code for page numbers.

#loading

{
width: 100%;
position: absolute;
}

li

{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}

li:hover

{
color:#FF0084;
cursor: pointer;
}

Reference: 9lessons.info

Are you working with multiple devices like iPhone, Android and Web then take a look at this post that explains you how to develop a RESTful API in PHP.  Representational state transfer (REST) is a software system for distributing the data to different kind of applications. The web service system produce status code response in JSON or XML format.
Create a RESTful Services API in PHP.


Download Script

Database
Sample database users table columns user_id, user_fullname, user_email, user_password and user_status.

CREATE TABLE IF NOT EXISTS `users`
(
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_fullname` varchar(25) NOT NULL,
`user_email` varchar(50) NOT NULL,
`user_password` varchar(50) NOT NULL,
`user_status` tinyint(1) NOT NULL DEFAULT ‘0’,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Rest API Class: api.php
Contains simple PHP code, here you have to modify database configuration details like database name, username and password.

<?php
require_once(“Rest.inc.php”);class API extends REST
{
public $data = “”;
const DB_SERVER = “localhost”;
const DB_USER = “Database_Username”;
const DB_PASSWORD = “Database_Password”;
const DB = “Database_Name”;private $db = NULL;

public function __construct()
{
parent::__construct();// Init parent contructor
$this->dbConnect();// Initiate Database connection
}

//Database connection
private function dbConnect()
{
$this->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
if($this->db)
mysql_select_db(self::DB,$this->db);
}

//Public method for access api.
//This method dynmically call the method based on the query string
public function processApi()
{
$func = strtolower(trim(str_replace(“/”,””,$_REQUEST[‘rquest’])));
if((int)method_exists($this,$func) > 0)
$this->$func();
else
$this->response(”,404);
// If the method not exist with in this class, response would be “Page not found”.
}

private function login()
{
…………..
}

private function users()
{
…………..
}

private function deleteUser()
{
………….
}

//Encode array into JSON
private function json($data)
{
if(is_array($data)){
return json_encode($data);
}
}
}

// Initiiate Library
$api = new API;
$api->processApi();
?>

Login POST
Displaying users records from the users table Rest API URL http://localhost/rest/login/. This Restful API login status works with status codes if status code 200 login success else status code 204 shows fail message. For more status code information check Rest.inc.php in download script.

private function login()
{
// Cross validation if the request method is POST else it will return “Not Acceptable” status
if($this->get_request_method() != “POST”)
{
$this->response(”,406);
}$email = $this->_request[’email’];
$password = $this->_request[‘pwd’];// Input validations
if(!empty($email) and !empty($password))
{
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$sql = mysql_query(“SELECT user_id, user_fullname, user_email FROM users WHERE user_email = ‘$email’ AND user_password = ‘”.md5($password).”‘ LIMIT 1″, $this->db);
if(mysql_num_rows($sql) > 0){
$result = mysql_fetch_array($sql,MYSQL_ASSOC);

// If success everythig is good send header as “OK” and user details
$this->response($this->json($result), 200);
}
$this->response(”, 204); // If no records “No Content” status
}
}

// If invalid inputs “Bad Request” status message and reason
$error = array(‘status’ => “Failed”, “msg” => “Invalid Email address or Password”);
$this->response($this->json($error), 400);
}

Users GET
Displaying users records from the users table Rest API URL http://localhost/rest/users/

private function users()
{
// Cross validation if the request method is GET else it will return “Not Acceptable” status
if($this->get_request_method() != “GET”)
{
$this->response(”,406);
}
$sql = mysql_query(“SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1”, $this->db);
if(mysql_num_rows($sql) > 0)
{
$result = array();
while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC))
{
$result[] = $rlt;
}
// If success everythig is good send header as “OK” and return list of users in JSON format
$this->response($this->json($result), 200);
}
$this->response(”,204); // If no records “No Content” status
}

DeleteUser
Delete user function based on the user_id value deleting the particular record from the users table Rest API URL http://localhost/rest/deleteUser/

private function deleteUser()
{if($this->get_request_method() != “DELETE”){
$this->response(”,406);
}
$id = (int)$this->_request[‘id’];
if($id > 0)
{
mysql_query(“DELETE FROM users WHERE user_id = $id”);
$success = array(‘status’ => “Success”, “msg” => “Successfully one record deleted.”);
$this->response($this->json($success),200);
}
else
{
$this->response(”,204); // If no records “No Content” status
}
}

Chrome Extention
A Extention for testing PHP restful API response download here Advanced REST client Application

.htaccess code
Rewriting code for friendly URLs. In the download code you just modify htaccess.txt to .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ api.php [QSA,NC,L]RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>