SlimAPI Framework Installation

Nowadays, The internet is full of third-party and custom APIs that offer a wide range of functionalities and Features. PHP offers several frameworks for web app, mobile app api development rapidly. However, time is always the crucial part of web developers and the app needs to be pushed at an impossible deadline. In such times, frameworks are the best option for rapid application development.

In this atricle, I will introduce you to Slim framework for PHP. Slim is fast becoming the most-opted framework for API development and small web apps as well as large web apps and mobile application development backend api. Although you can create REST API in several other frameworks like CakePHP, Symfony Laravel, Codeigniter, they have a steep learning curve and are often too cumbersome to use in rapid development scenarios.

Slim Frameword is microframe work which is only created for the developer who choose to develop apis.

Understanding Slim Framework

Slim is super lightweight framework, ideal for rapid web app development. One of the important usages is in REST API development. Slim supports all HTTP method (GET,POST,PUT,DELETE). Slim contains very handy URL structure with routers, middlewares, bodyparser along with page templates, flash messages, encrypted cookies and lots more.

At this point, it is important to understand the structure of the REST API.

Understanding REST API

REST is the abbreviation of Representational State Transfer. This is a bridge or medium between data resource and application interface, whether it’s on mobile devices or desktops. REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:

GET is used for reading and retrieving data.
POST is used for inserting data.
PUT is used for updating data.
DELETE is used for deleting data.

Basically, REST phenomena works on actions and resources. Whenever any action URL is invoked, it performs an individual method (or a set of methods) on that URL. I will further discuss this below with examples.

First we will need to install Slim framework for the REST API project.

System Requirements

  • Web server with URL rewriting
  • PHP 5.5 or newer

Role of Composer

  1. Enables you to declare the libraries you depend on.
  2. Finds out which versions of which packages can and need to be installed, and installs them (meaning it downloads them into your project).

If you are working on the localhost, you need to install it. If you haven’t installed it yet, just go to the following link and follow the instructions.

Instruction and more details about Composer Here.

How to Install Slim

We recommend you install Slim with Composer. Navigate into your project’s root directory and execute the bash command shown below. This command downloads the Slim Framework and its third-party dependencies into your project’s vendor/ directory.

composer require slim/slim "^3.0"

After installing Slim, the following piece of code will require it in the index.php file to require autoload file and instantiate Slim.

<?php

require 'vendor/autoload.php';
$app = new Slim\App();

Making a .htaccess File for Clean URL Structure

To make your life easier, you should create a .htaccess file that defines clean URL structure. At the root directory, make a .htaccess file and add the below code in it. This will provide a clean URL structure for the PHP file. (this just means that you don’t want to include PHP filename in the URL calls).

RewriteEngine On
RewriteCond %{Request_Filename} !-F
RewriteCond %{Request_Filename} !-d
RewriteRule ^ index.php [QSA,L]

If your index file is located in different folder (for instance, the “public” folder), then you can insert the full path of the index file in the last line:

RewriteRule ^ public/index.php [QSA,L]

Create a Database in MySQL

Now it is time for the first API call. Let’s make it systematically.

Retrieving Data

Enter the following code in the index.php file to get all the books from the database. A GET call is used for retrieval.

$app->get('/fetch', function() {
 require_once('dbConfig.php');
 $query = "select * from table order by id";
 $result = $connection->query($query);
 while ($row = $result->fetch_assoc()){
 $data[] = $row;
 }
 echo json_encode($data);
});

To streamline working with the API calls, I recommend using Postman (available from the Chrome App Store). This plugin greatly helps in API management and usage.

In postman, make a GET call with API URL.

This is all for the basic REST API in the Slim Framework. However, this API will not work until you add this command at the end of the code.

$app->run();

Conclusion

Creating and using the REST API with Slim framework is very easy. The biggest advantage of the framework is its ease of use and lightweight. The icing on the cake is that it is very easy to learn and a good developer could pick up the framework in a matter of hour. To summarize, Slim receives HTTP requests, review them and invokes the appropriate callback routine for HTTP requests and return the appropriate response(s).

If you need clarification about this article or have any other query about the Slim Framework, do let me know through the comment section.

How to Secure Cookie in PHP using Session

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

But now you want to set permissions on these session variables or values to accessing on other folder or page.for this you want to set the session cookie parameters.

Set the session cookie parameters PHP have function:

session_set_cookie_params();

 

Parameters :

lifetime – Lifetime of the session cookie, defined in seconds.
path – Path on the domain where the cookie will work. Use a single slash (‘/’) for all paths on the domain.
domain – Cookie domain, for example ‘www.example.com’. To make cookies visible on all subdomains then the domain must be prefixed with a dot like ‘.example.com’.
secure – If TRUE cookie will only be sent over secure connections.
httponly – If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie.

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )

 

Example :

if (ini_get("session.use_cookies")) {
    session_set_cookie_params(0, '/abc/xyz/', '', false, true);
}

In above example says now values of cookies that will be created anywhere inside the page of abc/xyz folder will be accessable only inside abc/xyz folder not in other folder present anywhere on server.

This function has not returned any value and you need to call session_set_cookie_params() for every request and before session_start() is called.

Get the session cookie parameters :

To get the session cookie parameters PHP have function

session_get_cookie_params();

Returns an array with the current session cookie information, the array contains the following items:

lifetime – The lifetime of the cookie in seconds.
path – The path where information is stored.
domain – The domain of the cookie.
secure – The cookie should only be sent over secure connections.
httponly – The cookie can only be accessed through the HTTP protocol.

Example :

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
}

$params returned array with 5 parameters as listed above.

MySQL Transactions

MySQL transactions can be used when you want to make sure all the statements you specify are executed. Only the tables of InnoDB storage engine support transactions.

In a transaction, if at least one statement fails, all the changes will be rolled back and database will be in its initial state.

In web applications, it’s common that you want to either run set of statements or do no change since success of only few statements can cause data corruption.

Think you need to add data in 2 tables

$query1 = INSERT INTO `users` (`id`, `first_name`, `last_name`) VALUES (1, 'test', 'user');

$query2 = INSERT INTO `profile` (`pid`,`id`, `gender-`, `mobile`,`email`) VALUES (1, '1', 'male','123456789','test@example.com');

Here you can see in second query gender field having speeling mistake, hence no data will be added for this operation and data from first query will be inserted successfully.When running these two statements, think that second one fails and first one succeeds.

If we ran these two statements in a MySQL transaction, if the second statement fails then the first statement will be rolled back making no changes.

In PHP, we can execute a transaction using MySQLi functions like below.

/* Change database details according to your database */
$dbConnection = mysqli_connect('localhost', 'root', 'username', 'db_name');

mysqli_autocommit($dbConnection, false);
$flag = true;

$query1 = INSERT INTO `users` (`id`, `first_name`, `last_name`) VALUES (1, 'test', 'user');

$query2 = INSERT INTO `profile` (`pid`,`id`, `gender-`, `mobile`,`email`) VALUES (1, '1', 'male','123456789','test@example.com');

$result = mysqli_query($dbConnection, $query1);

if (!$result) {
    $flag = false;
    echo "Error details: " . mysqli_error($dbConnection) . ".";
}

$result = mysqli_query($dbConnection, $query2);

if (!$result) {
    $flag = false;
    echo "Error details: " . mysqli_error($dbConnection) . ".";
}

if ($flag) {
    mysqli_commit($dbConnection);
    echo "All queries were executed successfully";
} else {
    mysqli_rollback($dbConnection);
    echo "All queries were rolled back";
}

mysqli_close($dbConnection);

When you execute mysqli_query() function, result is immediately committed to the database. Using mysqli_autocommit() function, you can turn off this behavior so that result won’t be committed to the database permanently till you command.

After that we simply execute the necessary statements and set the $flag to false if any statement fails. If there are many statements to run, consider storing the statements in an array and using a for or foreach loop.

At the end, if flag is true (no error has occurred), we commit the results to the database permanently using mysqli_commit(). Else we roll back the results using mysqli_rollback() function.

If you ran above PHP script, you would notice that no statement is executed since the field name gender having spelling mistake.While transactions will help you to eliminate data corruptions in programming level.

MULTIPLE MYSQL SERVERS FROM ONE PHPMYADMIN INSTANCE

At some point in your development career, it is likely that you will want to work on multiple MySQL servers. Personally, I like using phpMyAdmin for quick database management. However, what I don’t want to do is maintain multiple instances of phpMyAdmin. I also don’t want to install phpMyAdmin on any production web-servers.

What I would much rather do is install a local instance on my development machine, make sure it isn’t accessible to the outside world, and let it manipulate my local (test/development) environment and on occasion my production environments. Luckily, phpMyAdmin allows you to do just that.

To set this up you will want to navigate to the installation directory of phpMyAdmin (Mine is in C:\wamp\apps\phpMyAdmin-4.0.4.1) and check to see if you have a file named config.inc.php floating around in there. Follow the next steps based on whether that file exists:

If File doesn’t exist:

    • Create a file config.inc.php
    • Add the following updating for your server’s connection data and increment $i for each subsequent server added:
      <?php
       
      /* Servers configuration */
      $i = 0;
       
      $i++;
      $cfg['Servers'][$i]['verbose'] = '<Server 1>';
      $cfg['Servers'][$i]['host'] = '<127.0.0.1>';
      $cfg['Servers'][$i]['port'] = '';
      $cfg['Servers'][$i]['socket'] = '';
      $cfg['Servers'][$i]['connect_type'] = 'tcp';
      $cfg['Servers'][$i]['extension'] = 'mysqli';
      $cfg['Servers'][$i]['auth_type'] = 'config';
      $cfg['Servers'][$i]['user'] = '<username>';
      $cfg['Servers'][$i]['password'] = '<password>';
      $cfg['Servers'][$i]['AllowNoPassword'] = true;
       
      $i++;
      $cfg['Servers'][$i]['verbose'] = '<Server 2>';
      $cfg['Servers'][$i]['host'] = '<127.0.0.1>';
      $cfg['Servers'][$i]['port'] = '';
      $cfg['Servers'][$i]['socket'] = '';
      $cfg['Servers'][$i]['connect_type'] = 'tcp';
      $cfg['Servers'][$i]['extension'] = 'mysqli';
      $cfg['Servers'][$i]['auth_type'] = 'config';
      $cfg['Servers'][$i]['user'] = '<username>';
      $cfg['Servers'][$i]['password'] = '<password>';
      $cfg['Servers'][$i]['AllowNoPassword'] = true;
       
      ?>
    • Save the file
    • Navigate to your phpMyAdmin instance using a browser
    • On the left-hand navigation pane you will now see a drop-down near the top preceded by the words “Current Server:”
    • When you change this your phpMyAdmin instance will reload itself with the new server in scope

If File does exist:

  • Open the file config.inc.php in your favorite editor
  • Make sure your file has the following code in it:
    <?php
    /* Servers configuration */
    $i = 0;
  • After this code add the following updating for your server’s connection data and increment $i for each subsequent server added:
    $i++;
    $cfg['Servers'][$i]['verbose'] = '<Server 2>';
    $cfg['Servers'][$i]['host'] = '<127.0.0.1>';
    $cfg['Servers'][$i]['port'] = '';
    $cfg['Servers'][$i]['socket'] = '';
    $cfg['Servers'][$i]['connect_type'] = 'tcp';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = '<username>';
    $cfg['Servers'][$i]['password'] = '<password>';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
  • Save the file
  • Navigate to your phpMyAdmin instance using a browser
  • On the left-hand navigation pane you will now see a drop-down near the top preceded by the words “Current Server:”
  • When you change this your phpMyAdmin instance will reload itself with the new server in scope

MANAGE REMOTE MYSQL DATABASE LOCALLY USING PHPMYADMIN

In many web applications, we have to work with remote databases. It is very hard to manage those databases by accessing the remote server which our database run. Therefore, if we have a way to manage those databases locally using a UI, our task is getting easier.

Now I will show you how to manage those databases using phpMyAdmin locally. For that, we have to do some configurations.

The file config.inc.php contains the configuration settings for your phpMyAdmin installation. It uses an array to store sets of config options for every server it can connect to and by default there is only one, your own machine, or localhost. In order to connect to another server, you would have to add another set of config options to the config array.

First open config.inc.php file held in phpMyAdmin folder. In wamp server, you can find it in wamp\apps\phpmyadmin folder. Then add following part to that file.

$i++;
$cfg['Servers'][$i]['host']          = 'hostname/Ip Adress';
$cfg['Servers'][$i]['port']          = '';
$cfg['Servers'][$i]['socket']        = '';
$cfg['Servers'][$i]['connect_type']  = 'tcp';
$cfg['Servers'][$i]['extension']     = 'mysql';
$cfg['Servers'][$i]['compress']      = FALSE;
$cfg['Servers'][$i]['auth_type']     = 'config';
$cfg['Servers'][$i]['username']      = 'username';
$cfg['Servers'][$i]['password']      = 'password';

Pay attention that the config array is called cfg and it’s a multidimensional array and that all servers, have to be part of the $cfg[“Servers”] inner array. The way this works is by using an increment variable $i that sets a different inner array for each server inside the $cfg[“Servers”] array. For this to work you need to make sure each new set of config options starts with an incremented $i by using $i++.

Let’s see what is the meaning of this variables.

  • $i++ :- Incrementing variable for each server
  • $cfg[‘Servers’][$i][‘host’] :- Server host name or IP adress
  • $cfg[‘Servers’][$i][‘port’] :- MySQL port (Leave a blank for default port. Default MySQL port is 3306)
  • $cfg[‘Servers’][$i][‘socket’] :- Path to the socket (Leave a blank for default socket)
  • $cfg[‘Servers’][$i][‘connect_type’] :- How to connect to MySQL server (‘tcp’ or ‘socket’)
  • $cfg[‘Servers’][$i][‘extension’] :- php MySQL extension to use (‘mysql’ or ‘msqli’)
  • $cfg[‘Servers’][$i][‘compress’] :- Use compressed protocol for the MySQL connection (requires PHP >= 4.3.0)
  • $cfg[‘Servers’][$i][‘auth_type’] :- Method of Authentication
  • $cfg[‘Servers’][$i][‘username’] :- Username to the MySQL database in remote server
  • $cfg[‘Servers’][$i][‘password’] :- Password to the MySQL database int he remote server

After adding this part to the config.inc.php file, restart your local server. Now your phpMyAdmin home page will display like follow.

phpmyadmin_home

Now in server choice field, there will be a localhost and new server that you configured. Choose that remote server and enter username and password of that remote database. Then click ‘Go’ button and it will connect to your remote database and now you can manage it locally.

Ajax Upload and Resize an Image with PHP.

Today I am presenting the most important social networking feature called ajax upload and resize an image without refreshing the page using jquery and PHP. This tutorial a continuation of my previous post, I just included image re-sizing function for different dimensions. It is very useful for your web project that saves lots of hosting space and bandwidth limit. Take a quick look at the live demo.

admin-ajax

The tutorial contains three folders called js,includes and uploads with PHP files.
includes
— getExtension.php
— compressImage.php
js
— jquery.min.js
— jquery.form.js
uploads
index.php
ajaximageupload.php
db.php

Javascript Code

$(“#photoimg”).live(‘change’,function(){})- photoimg is the ID name of INPUT FILE tag and $(‘#imageform’).ajaxForm() – imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag.

<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() 
{ 

$('#photoimg').live('change', function() 
 {
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");

$("#imageform").ajaxForm({target: '#preview', 
beforeSubmit:function(){
A.show();
B.hide();
}, 
success:function(){
A.hide();
B.show();
}, 
error:function(){
A.hide();
B.show();
} }).submit();
});

}); 
</script>

Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.

index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value. 

<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image: 
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />

</div>
</form>

Sample database design for Users.

Users
Contains user details username, password, email and profile_image  etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200)
)

ajaximage.php

Contains PHP code. This script helps you to upload images into uploads folder. Image file name rename into timestamp+session_id.extention

<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
include_once 'includes/getExtension.php';
$imagename = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($imagename))
{
$ext = strtolower(getExtension($imagename));
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$uploadedfile = $_FILES['photoimg']['tmp_name'];

//Re-sizing image. 
include 'includes/compressImage.php';
$widthArray = array(200,100,50); //You can change dimension here.
foreach($widthArray as $newwidth)
{
$filename=compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth);
echo "<img src='".$filename."' class='img'/>";
}

//Original Image
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{
//Insert upload image files names into user_uploads table
mysqli_query($db,"UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id';");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB"; 
}
else
echo "Invalid file format.."; 
}
else
echo "Please select image..!";
exit;
}
?>

compressImage.php
Re-sizing image into different pixel dimensions. 

<?php
function compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth)
{

if($ext=="jpg" || $ext=="jpeg" )
{
$src = imagecreatefromjpeg($uploadedfile);
}
else if($ext=="png")
{
$src = imagecreatefrompng($uploadedfile);
}
else if($ext=="gif")
{
$src = imagecreatefromgif($uploadedfile);
}
else
{
$src = imagecreatefrombmp($uploadedfile);
}

list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $path.$newwidth.'_'.$actual_image_name; //PixelSize_TimeStamp.jpg
imagejpeg($tmp,$filename,100);
imagedestroy($tmp);
return $filename;
}
?>

getExtension.php
This extracts file extension. 

function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

db.php
Database configuration file, modify username, password and database values. 

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

 

Ajax PHP Login Page with Shake Animation Effect.

how to create Ajax PHP login script, in this post I want to discuss how to create a simple Ajax PHP login with welcome page using MySQL database. This will explain you creating user tables, posting form values and storing and destroying the session values. If you are a PHP beginner take a quick look at this live demo with Username: 9lessons Password:9lessons. This post has been updated with mysqli.

Users Table
User table contains all the users registration details. 

CREATE TABLE `users` (
`uid` INT(11) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(45) ,
`password` VARCHAR(100) ,
`email` VARCHAR(45) ,
`friend_count` INT(11) ,
`profile_pic` VARCHAR(150),
PRIMARY KEY (`uid`));

Jquery Code
Contains javascipt code, $(“#login”).click(function(){}– login is the ID name of the login button. Using element.val() calling username and password input values. If id value is even number if(id(even) % 2) = If(0) false

<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() 
{

$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
$("body").load("home.php").hide().fadeIn(1500).delay(6000);
//or
window.location.href = "home.php";
}
else
{
//Shake animation effect.
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});

}
return false;
});

});
</script>

index.php
Contains PHP and HTML code, If session value exists this will  redirect to home page.

<?php
session_start();
if(!empty($_SESSION['login_user']))
{
header('Location: home.php');
}
?>
//HTML Code
<div id="box">
<form action="" method="post">
Username
<input type="text" class="input"  id="username"/>
Password
<input type="password" class="input"  id="password"/>
<input type="submit" class="button button-primary" value="Log In" id="login"/>
<div id="error"></div> 
</div>
</form> 
</div>

ajaxLogin.php
Contains PHP code, this will verify username and password values in database.

<?php
include("db.php");
session_start();
if(isset($_POST['username']) && isset($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($db,$_POST['username']); 
//Here converting passsword into MD5 encryption. 
$password=md5(mysqli_real_escape_string($db,$_POST['password'])); 

$result=mysqli_query($db,"SELECT uid FROM users WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $username and $password, table row  must be 1 row
if($count==1)
{
$_SESSION['login_user']=$row['uid']; //Storing user session value.
echo $row['uid'];
}

}
?>

home.php
If user session value is empty, this will redirect to login page.
<?php
session_start();
if(empty($_SESSION['login_user']))
{
header('Location: index.php');
}
?>
//HTML Code
Welcome to Home Page
<a href="logout.php">Logout</a>

logout.php
Cleaning the user session value.

<?php
session_start();
if(!empty($_SESSION['login_user']))
{
$_SESSION['login_user']='';
session_destroy();
}
header("Location:index.php");
?>

db.php
Database configuration file, modify username, password and database values. 

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

 

Upload and Resize an Image with PHP

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.

Untitled

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

<?php 

 define ("MAX_SIZE","400");

 $errors=0;
 
 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
        $image =$_FILES["file"]["name"];
 $uploadedfile = $_FILES['file']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['file']['name']);
        $extension = getExtension($filename);
  $extension = strtolower($extension);
 if (($extension != "jpg") && ($extension != "jpeg") 
&& ($extension != "png") && ($extension != "gif")) 
  {
echo ' Unknown Image extension ';
$errors=1;
  }
 else
{
   $size=filesize($_FILES['file']['tmp_name']);
 
if ($size > MAX_SIZE*1024)
{
 echo "You have exceeded the size limit";
 $errors=1;
}
 
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else 
{
$src = imagecreatefromgif($uploadedfile);
}
 
list($width,$height)=getimagesize($uploadedfile);

$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
 $width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, 
$width,$height);

$filename = "images/". $_FILES['file']['name'];
$filename1 = "images/small". $_FILES['file']['name'];

imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
//If no errors registred, print the success message

 if(isset($_POST['Submit']) && !$errors) 
 {
   // mysql_query("update SQL statement ");
  echo "Image Uploaded Successfully!";

 }
 ?>

Extention PHP funtion
Finds file extensions.

function getExtension($str) {

         $i = strrpos($str,".");
         if (!$i) { return ""; } 
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }