Posts Tagged ‘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 »

Advertisements
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.

 

This tutorial about Hide and Seek with jQuery and PHP. This script helps you to present all modules in single page. Take a look at live demo click buttons

 


Download Script     Live Demo

Javascript Code

// <![CDATA[
javascript” src=”http://ajax.googleapis.com/ajax/
// ]]>
libs/jquery/1.3.0/jquery.min.js”>
<script type=”text/javascript”>
$(function()
{

$(“.button”).click(function()
{
var button_id = $(this).attr(“id”);

//Add Record button

if(button_id==”add”)
{
$(“#results”).slideUp(“slow”);
$(“#save_form”).slideDown(“slow”);
}

//Cancel button

else if(button_id==”cancel”)
{
$(“#save_form”).slideUp(“slow”);
$(“#results”).slideDown(“slow”);
}

// save button
else

{

// insert record
// more details Submit form with jQuery

}

return false;

});
});
</script>

HTML Code
Contains javascipt code. $(“.button”).click(function(){}- button is the class name of buttons(Add, Save and Cancel). Using $(this).attr(“id”) calling button id value.

<div id=”results” >

<a href=”#”color: blue;”>button” id=”add” >Add Record </a>
</div>

<div id=”save_form” style=”display:none” >

<a href=”#”color: blue;”>button” id=”save” >Save </a>
<a href=”#”color: blue;”>button” id=”cancel” >Cancel </a>
</div>

<div id=”update” >

</div>
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>

 

 

 

Since its release in 1995, MySQL has became one of the most commonly used database in Internet world. A lot of small and medium businesses uses MySQL as their backend db.  Its popularity for use with web applications is closely tied to the popularity of PHP, which is often combined with MySQL. Wikipedia runs on MediaWiki software, which is written in PHP and uses a MySQL database. Several high-traffic web sites use MySQL for its data storage and logging of user data, including Flickr, Facebook, Wikipedia, Google, Nokia and YouTube.

MySQL provide a great command line utility to take backup of your MySQL database and restore it. mysqldump command line utility is available with MySQL installation (bin directory) that can be used to achieve this.

1. Getting backup of a MySQL database using mysqldump.

Use following command line for taking backup of your MySQL database using mysqldump utility.

mysqldump –-user [user name] –-password=[password] [database name] > [dump file]

or

mysqldump –u[user name] –p[password] [database name] > [dump file]

Example:

mysqldump –-user root –-password=myrootpassword db_test > db_test.sql

or

mysqldump –uroot –pmyrootpassword db_test > db_test.sql

2. Backup multiple databases in MySQL.

mysqldump –u[user name] –p[password] [database name 1] [database name 2] .. > [dump file]

Example:

mysqldump –-user root –-password=myrootpassword db_test db_second db_third > db_test.sql

3. Backup all databases in MySQL.

shell> mysqldump –u[user name] –p[password] –all-databases > [dump file]

4. Backup a specific table in MySQL.

shell> mysqldump --user [username] --password=[password] [database name] [table name] 
> /tmp/sugarcrm_accounts_contacts.sql

Example:

shell> mysqldump --user root --password=myrootpassword db_test customers 
> db_test_customers.sql

5. Restoring MySQL database.

The mysqldump utility is used only to take the MySQL dump. To restore the database from the dump file that you created in previous step, use mysql command.

shell> mysql --u [username] --password=[password] [database name] < [dump file]

Example:

shell> mysql --user root --password=myrootpassword new_db < db_test.sql
Enhanced by Zemanta

Intelligent PHP Editor

PhpStorm provides rich and intelligent code editor for PHP with syntax highlighting, extended code formatting configuration, on-the-fly error checking, and smart code completion.

PHP 5.4 Language Features Support

PHP 5.4 is now fully supported, including traits and all the new syntax improvements: class member access on instantiation, short array syntax, array dereferencing on function call, binary literals, expressions in static calls, etc.:

PHP code completion

Automatic code completion (invoked on typing) finalizes classes, methods, variable names, and PHP keywords, plus commonly used names for fields and variables depending on their type.

Code completion

 

Code completion supports array indexes in PHP code.

Code completion

PHPDoc support

PhpStorm editor respects PHPDoc in your code and provides appropriate code completion suggestions based on @property, @method and @var annotations.

When you edit PHPDoc for your code, variable names and types are auto-completed from the corresponding code blocks.

PHP code refactorings also consider PHPDocs to keep them up to date.

PHPDoc

Smart Duplicated Code Detector

Added for all major supported languages including even CSS and HTML. Go to Code|Locate Duplicates to start your quest against copy/paste coding. You’ll be presented with a list of candidates for refactoring — and with the help of Refactor | Extract Method it’s easy to keep your code DRY.

PHP Code Sniffer

PhpStorm 4.0 allows you to check your code on the fly with PHP Code Sniffer (phpcs), just by opening a PHP file. The check is triggered every time you change something in the file, so it’s extremely easy to fix problems reported by PHP Code Sniffer.

 

Read more in our blog »

PHP refactoring

The Rename refactoring works for files, functions, constants, classes, properties, methods, parameters, and local and global variables.

Also following refactorings are available:

  • Introduce Variable
  • Introduce Constant
  • Introduce Field
  • Inline variable

Make global project changes easily and safely. Local changes are made instantly in-place.

Smarty templates editing

With the PhpStorm IDE, you can use the Smarty template engine and take advantage of these productivity features when working with .tpl files:

  • configurable syntax highlighting for keywords, strings, variables and braces
  • syntax errors highlighting
  • Smarty functions and attributes completion
  • automatic insertion of paired braces, quotes and closing tags
  • commenting of the selected block with a single hotkey
  • custom Smarty delimiters support
Smarty templates editing

 

More on Smarty support in PhpStorm.

Efficient project analysis and navigation

Its thorough source code analysis allows PhpStorm to provide sophisticated code completion even for unannotated code, for example:

  • the function return type is deducted from its body and return statements
  • class property types (and declarations) are extracted from the constructor code
Class fields from constructor
Function type

 

File structure view and class, method and call hierarchy views allow for faster code review and navigation.

More on Hierarchy View in our blog: Hierarchies view support for PHP & Hierarchy View actions

to the top

Smart Environment

PHP UML

PhpStorm helps developers to understand and change their code by providing editable UML class diagrams for PHP code. You can quickly examine your application structure, create and edit classes and their relationships. Look for “Diagrams…” in context menus. Many refactorings can be applied directly from the diagram, via the shortcut menu.

 

Note that a diagram built from a source control change list or history provides a semantic view of changes – added classes, changed hierarchy, and changed properties.

Drupal & Symfony2 Coding Style Support

PhpStorm contains a bundled predefined coding styles for the popular Drupal content management platform and Symfony2 framework. Currently just reformatting your code in PhpStorm removes 99% of errors reported by Drupal coder-review and helps your code meet Drupal coding standards.

Version control systems integration

PhpStorm supports most popular Version Control Systems:

  • Subversion
  • Mercurial
  • Git
  • Perforce
  • CVS
  • TFS

All the tedious tasks (adding, removing, deleting files) are performed automatically. A built-in visual merge tool resolves all conflicts in a quick and intuitive manner. The changes made locally are highlighted as you type in the editor gutter, providing intuitive navigation and a 2-click rollback for individual changes.

IDE changes

 

For Git VCS IDE shows revisions graph.

Git VCS IDE

 

The following features are available no matter which VCS you use:

  • Integrated changelists — group your changes into multiple change lists for better organization
  • Shelved changes — set aside some changes to restore them later
  • Repository changes view — see what has been committed by other team members
  • UML view of changessee UML section
  • Incoming changes view — see the code changes not yet integrated into your local copy
  • Outdated changes notification — get warned that a file you are working with has been changed after your last sync

Local history

PhpStorm tracks any changes made to your source files, protecting you from any accidental losses or modifications, even if made by other applications. At any time, you can inspect the history of either a particular file or directory and rollback to any of its previous versions. You can also set version labels.

Phing Support

PhpStorm automatically completes and checks standard tags, properties, target names, path attribute values in build files:

to the top

PHPUnit, Debugger & Profiler

PHPUnit

Develop PHPUnit tests in PhpStorm and run them instantly from a directory, file or class using the context menu options.

Dedicated Run/Debug configurations allow you to run the appropriate set of tests at a later time.

Tests are executed in a dedicated Test Runner UI, displaying results overview and detailed stats for the whole suite and every particular test.

 

If a test fails, you can instantly jump from the stacktrace to the line of code where the error occurred.

More on using PhpUnit with PhpStorm.

Visual Debugger

PhpStorm provides numerous options for debugging your PHP code, so you can:

  • Inspect context-relevant local variables and user-defined watches, including arrays and complex objects, and edit values on the fly.
  • Setup remote debugging for your server.
  • Evaluate an expression in runtime.
  • Debug a page in multiple sessions simultaneously.
  • Keep a debugging session alive while moving between pages.

You can use our browser bookmarklets, Zend Toolbar or XDebug toolbar to initiate debugging directly from any page in a modern browser such as Firefox, IE, Google Chrome or Safari.

PHP Debugger in PhpStorm
PHP debugging: Set value and watch

Read more about zero-configuration debugging with PhpStorm.

And when (in some cases) you still need to configure debugging manually read this article: How to configure debugging in PhpStorm

Watch our video on how to configure remote debugging:

Profiler integration

You can profile your scripts right from PHPStorm with either xDebug and Zend Debugger. You can see an aggregate report and jump from the execution statistics directly to the function in your PHP code.

to the top

Lightweight IDE

Use the same environment on Windows, Mac OS and Linux

Windows. Batch code inspection for CSS
Mac OS X. smart and customizable editor
Linux. Project-wide usages search and spellchecker

Open code from anywhere and start working in no time

Open an existing folder, check out the code from a VCS, or even specify your FTP to download and auto-sync your files with. You’re up and running in mere moments.

Edit project files locally and deploy back to remote server using automatic synchronization, either on file save or on demand.

Web resource folders are quickly configured via Settings|Directories — note the “Resource Root” marker button. Just mark your JS/CSS/other folders to get proper completion and code analysis.

to the top

JavaScript & HTML/XHTML/CSS

Note: PhpStorm includes all the features of WebStorm related to javascript and html editing.

 

DOM-Based, browser-specific completion

JavaScript, HTML & CSS code completion for tags, keywords, labels, variables, parameters and functions is DOM-based and supports popular browsers’ specifics (IE, Firefox, etc.) Completion is available for both standard and user-defined functions in *.js files, HTML event handlers and everywhere else where appropriate.

Javascript completion
Go to symbol
  • Go to declaration — navigates to where the function, variable or label in question is declared with a simple hotkey or Ctrl+Click⌘Click.
  • Go to symbol — navigates to any symbol in project code using search patterns, including asterisk (*) and/or CamelHump abbreviations.
  • Find/Highlight Usages — locates other places in your entire project where a JavaScript symbol, label or file is used, with quick preview and instant navigation to the actual usages.

ECMAScript Harmony Support

For those who prefer to stay one step ahead, WebStorm presents experimental support of a new ongoing ECMAScript version code-named Harmony. To try out the new features, set ECMAScript Harmony to be the JavaScript language version in the IDE settings.

Note: each JavaScript engine implementation adds some nice features that others don’t have. When you use a language feature that isn’t supported by the currently selected JavaScript version, WebStorm will notify you and suggest a Quick-Fix:

 

 

Read more in our blog »

JavaScript refactoring

Refactoring capabilities provided for JavaScript allow you to easily modify the code structure as well as undo the modifications. Some refactorings available for JavaScript code and *.js files are:

  • Rename
  • Extract Variable/Function
  • Inline Variable/Function
  • Move/Copy
  • Safe Delete
  • Extract embedded script into file

JavaScript debugger

With JetBrains PhpStorm you can debug JavaScript code utilizing the complete range of features:

  • Breakpoints in HTML and JavaScript
  • Customizable breakpoint properties: suspend mode, conditions, pass count and more
  • Frames, variables and watches views in JavaScript debugger UI
  • Runtime evaluation of JavaScript expressions
JavaScript breakpoint

 

More on JavaScript Editor features

to the top

Validation and quick-fixes

PhpStorm detects and suggests auto-fixes for such problems as:

  • missing required attributes
  • invalid attributes or illegal values
  • wrong references to files in links
  • duplicate attributes
  • invalid CSS selector format
  • invalid CSS properties
  • unused CSS class definitions
  • invalid local anchors and more…

More front-end features…

You can find more front-end features on JavaScript Editor and HTML/XHTML/CSS Editor pages

to the top

Enhanced by Zemanta