PHP & Web Development Blogs

Showing 1 to 5 of 43 blog articles.
14840 views · 1 years ago

![Creating a URL shortener application in PHP & MySQL](https://images.ctfassets.net/vzl5fkwyme3u/3OjKfmylv2k8eWayqeCUWG/6d8e996fc7c757135df7fdd322fd50a4/AdobeStock_65694631.jpeg?w=1000)

Hi Guys,

In this post we will learn how to create your URL shortening application in PHP and MySQL.

You may also use this app as an API by calling the URLs from another application.

## Step 1: Creating a Table

```mysql

CREATE TABLE IF NOT EXISTS `url_shorten` (

`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,

`url` tinytext NOT NULL,

`short_code` varchar(50) NOT NULL,

`hits` int(11) NOT NULL,

`added_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

```

## Step 2: Create a file `index.php` and add database credentials in it

```php

$servername = 'localhost';

$username = 'root';

$password = ''; / /on localhost by default there is no password

$dbname = 'shorten_db';

$base_url='http://localhost/myapp/'; / / it is your application url

```

## Step 3: Get the URL in querystring and return a shortened URL using following code:

```php

if(isset($_GET['url']) && $_GET['url']!="")

{

$url=urldecode($_GET['url']);

if (filter_var($url, FILTER_VALIDATE_URL))

{

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

$slug=GetShortUrl($url);

$conn->close();

echo $base_url.$slug;

}

else

{

die("$url is not a valid URL");

}

}

else

{ / /show the basic html form having element url

?>

<center>

<h1>Put Your Url Here</h1>

<form>

<p><input style="width:500px" type="url" name="url" required /></p>

<p><input type="submit" /></p>

</form>

</center>

<?php

}

```

Now we'll create a function called `GetShortUrl` for creating the short URL:

```php

function GetShortUrl($url){

global $conn;

$query = "SELECT * FROM url_shorten WHERE url = '".$url."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

return $row['short_code'];

} else {

$short_code = generateUniqueID();

$sql = "INSERT INTO url_shorten (url, short_code, hits)

VALUES ('".$url."', '".$short_code."', '0')";

if ($conn->query($sql) === TRUE) {

return $short_code;

} else {

die("Unknown Error Occured");

}

}

}

```

The above function is using the `generateUniqueID()` function to generate a unique id for long urls. We can generate and retrieve the unique ID like so:

```php

function generateUniqueID(){

global $conn;

$token = substr(md5(uniqid(rand(), true)),0,6); / / creates a 6 digit unique short id

$query = "SELECT * FROM url_shorten WHERE short_code = '".$token."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

generateUniqueID();

} else {

return $token;

}

}

```

## Step 4

Now your code is ready to generate a unique short code for long URLs, but we still need to setup the redirection. When redirecting it should also increase a pageview/ hits in the table and then redirect to the longer, original URL.

Here is the code that allows us to do this:

```php

if(isset($_GET['redirect']) && $_GET['redirect']!="")

{

$slug=urldecode($_GET['redirect']);

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

$url= GetRedirectUrl($slug);

$conn->close();

header("location:".$url);

exit;

}

```

This code uses a function called `GetRedirectUrl()` that we need to define, like so:

```php

function GetRedirectUrl($slug){

global $conn;

$query = "SELECT * FROM url_shorten WHERE short_code = '".addslashes($slug)."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

/ / increase the hit

$hits=$row['hits']+1;

$sql = "update url_shorten set hits='".$hits."' where id='".$row['id']."' ";

$conn->query($sql);

return $row['url'];

}

else

{

die("Invalid Link!");

}

}

```

## Step 5

You are almost done now! If you don't want to use the redirect parameter in url for redirection purpose you will need to create a `.htaccess` file in your project and add following code:

```php

RewriteEngine on

RewriteRule ^([a-z0-9]{6})$ index.php?redirect=$1 [L]

```

### And You Have done it!

Now if you want to convert any url to short url just pass the url in get param of index.php like following:

http://localhost/myapp/?url=http://www.google.com **or** http://localhost/myapp/index.php?url=http://www.google.com **or** just open http://localhost/myapp/ **or** http://localhost/myapp/index.php,

It will show a html form where you may input any URL and click submit.

After submitting form or hitting the url with param url then it will print a shortened URL on screen. You may use that URL in new tab and see the url will be redirect to long URL and increase a Hit/ Pageview in MySQL table.

## Please find the full code for index.php here:

```php

<?php

$servername = 'localhost';

$username = 'root';

$password = ''; / / on localhost by default there is no password

$dbname = 'shorten_db';

$base_url='http://localhost/myapp/'; / / it is your application url

if(isset($_GET['url']) && $_GET['url']!="")

{

$url=urldecode($_GET['url']);

if (filter_var($url, FILTER_VALIDATE_URL))

{

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

$slug=GetShortUrl($url);

$conn->close();

echo $base_url.$slug;

}

else

{

die("$url is not a valid URL");

}

}

else

{

?>

<center>

<h1>Put Your Url Here</h1>

<form>

<p><input style="width:500px" type="url" name="url" required /></p>

<p><input type="submit" /></p>

</form>

</center>

<?php

}

function GetShortUrl($url){

global $conn;

$query = "SELECT * FROM url_shorten WHERE url = '".$url."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

return $row['short_code'];

} else {

$short_code = generateUniqueID();

$sql = "INSERT INTO url_shorten (url, short_code, hits)

VALUES ('".$url."', '".$short_code."', '0')";

if ($conn->query($sql) === TRUE) {

return $short_code;

} else {

die("Unknown Error Occured");

}

}

}

function generateUniqueID(){

global $conn;

$token = substr(md5(uniqid(rand(), true)),0,6); / / creates a 6 digit unique short id

$query = "SELECT * FROM url_shorten WHERE short_code = '".$token."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

generateUniqueID();

} else {

return $token;

}

}

if(isset($_GET['redirect']) && $_GET['redirect']!="")

{

$slug=urldecode($_GET['redirect']);

/ / Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

/ / Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

$url= GetRedirectUrl($slug);

$conn->close();

header("location:".$url);

exit;

}

function GetRedirectUrl($slug){

global $conn;

$query = "SELECT * FROM url_shorten WHERE short_code = '".addslashes($slug)."' ";

$result = $conn->query($query);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

/ / increase the hit

$hits=$row['hits']+1;

$sql = "update url_shorten set hits='".$hits."' where id='".$row['id']."' ";

$conn->query($sql);

return $row['url'];

}

else

{

die("Invalid Link!");

}

}

```

11595 views · 1 years ago

![Generate PDF from HTML in Laravel 5.7](https://images.ctfassets.net/vzl5fkwyme3u/7BjL7ILSA84wgAUIo2K2yg/43ac850a592f4a272e910c30e06b97ba/AdobeStock_39841236.jpeg?w=1000)

Today, I will share with you how to create a PDF file from HTML blade file in Laravel 5.7. We will be using `dompdf` package for generating the PDF file.

In the below example, we will install `barryvdh/laravel-dompdf` using composer package and thereafter we will add new route url with controller. Then we will create a blade file. Then after we have to just run project with serve and we can check the PDF file is for download.

## Download Laravel 5.7

Now I am going to explain the step by step from scratch with laravel installation for `dompdf`. To get started, we need to download fresh Laravel 5.7 application using command, so open our terminal and run the below command in the command prompt:

```php

composer create-project --prefer-dist laravel/laravel blog

```

## Install laravel-dompdf Package

Now we will install barryvdh/laravel-dompdf composer package by using the following composer command in ourLlaravel 5.7 application.

```php

composer require barryvdh/laravel-dompdf

```

Then the package is successfully installed in our application, after that open config/app.php file and we need to add alias and service provider.

**config/app.php**

```php

'providers' => [

....

Barryvdh\DomPDF\ServiceProvider::class,

],

'aliases' => [

....

'PDF' => Barryvdh\DomPDF\Facade::class,

]

```

## Create Routes

Now we need to create routes for the items listing. so now open our "routes/web.php" file and we need to add following route.

**routes/web.php**

```php

Route::get('demo-generate-pdf','[email protected]');

```

## Create Controller

Here,we need to create a new controller *HomeController* (mostly it will be there, we can skip this step if we don't need to create a controller) that will manage our pdf generation using the `generatePDF()` method of route.

**app/Http/Controllers/HomeController.php**

```php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use PDF;

class HomeController extends Controller

{

public function demoGeneratePDF()

{

$data = ['title' => 'Welcome to My Blog'];

$pdf = PDF::loadView('myPDF', $data);

return $pdf->download('demo.pdf');

}

}

```

## Create Blade File

In the final step, let us create demoPDF.blade.php in the resources/views/demoPDF.blade.php for structure of pdf file and add the following code:

**resources/views/demoPDF.blade.php**

```html

<!DOCTYPE html>

<html>

<head>

<title>Hi</title>

</head>

<body>

<h1>Welcome to My BLOG - {{ $title }}</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</body>

</html>

```

Now run the below command for serve and test it:

```curl

php artisan serve

```

8671 views · 1 years ago

![Install Composer for PHP](https://images.ctfassets.net/vzl5fkwyme3u/6REkTRobXqOMgyiyCa8ioS/fb4fc03a6a5514df3522a605b981505b/composer.png?w=1000)

Composer is a must-have tool for every PHP developer these days. This page is a simple breakdown of quick-install instructions.

## How do I install composer?

1. Use PHP to download the composer installer, place it in the current directory, and name it `composer-setup.php`

2. Use PHP to check the hash of the file you downloaded and compare it to the known value of the hash. You can always find the current value of the hash for the installer on the [Composer Public Keys / Signatures](https://composer.github.io/pubkeys.html) page.

3. Run the setup program to install composer. This does more than just download the latest copy of composer, it also sets up your local ~/.composer directory. This will install composer into the current directory. You can add the --install-dir=DIR to specify where you want composer installed. You can also specify --filename=composer to chang ethe installed filename. You can use anything you like that doesn’t already exist in your specified directory, you don’t have to use the name composer. This is a great way to get rid of the .phar at the end of the name if you don’t like it.

4. Use PHP to remove the installer from the current directory.

To install composer for PHP you use PHP to download the installer, set a few options, and then actually perform the install.

1. `php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"`

2. `php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"`

3. `php composer-setup.php`

4. `php -r "unlink('composer-setup.php');"`

Below is a version you can copy ‘n paste.

Breakdown:

## Recommended Setup for Linux and macOS:

```

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php --install-dir=/usr/local/bin --filename=composer

php -r "unlink('composer-setup.php');"```

**WARNING**: Line two IS WHERE IT compares the hasH of the installer you just downloaded to a hard-coded value. The value specified in the script is the value for the current version of the installer as of this writing. If it fails, check the [Composer Public Keys / Signatures](https://composer.github.io/pubkeys.html) page and get the latest version. Plug it into the script below and try again.

Windows user, change the `--installdir=` to a directory in your path.

## Recommended Setup for Windows

If you are running Microsoft Windows, the instructions above will work for you as long as you use the proper install paths. You can however download ComposerSetup.exe from the [Composer Introduction](https://getcomposer.org/doc/00-intro.md) page. Execute this and it will install composer and set your path so that you can run composer from anywhere. You will have to close your terminal window and open a new one after the install for the path to be updated.

That’s it, you should now have Composer installed.

## Composer installation Resources

* [Composer Homepage](https://getcomposer.org/)

* [Composer Introduction](https://getcomposer.org/doc/00-intro.md)

* [Download Composer](https://getcomposer.org/download/)

* [Composer Public Keys / Signatures](https://composer.github.io/pubkeys.html)

8154 views · 1 years ago

![Create Simple RESTful APIs using PHP & MySQL](https://images.ctfassets.net/vzl5fkwyme3u/5s6X92LpF8dGGVZEnXGRK0/387bfe60541987d308e8201ca5bb5d3f/api_blog_post.png?w=1000)

Hi Guys,

I am sharing you the way to create simple resful apis using php and mysql. We are creating 2 apis here

First is to Loggin a existing user and second is to get list of written blogs by logged in user.

#### Create any database, i am taking ```news``` as the database name here, After it create following 2 tables inside it.

```

CREATE TABLE `users` (

`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

`name` varchar(100),

`email` varchar(100),

`password` varchar(100),

`createdAt` datetime NOT NULL,

`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

CREATE TABLE `blogs` (

`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

`user_id` int(11),

`title` varchar(255),

`summary` Tinytext,

`body` Text,

`createdAt` datetime NOT NULL,

`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

```

#### Now putting some dummy data to read via the api

```

--create 2 entries in users table--

INSERT INTO `news`.`users` (`id`, `name`, `email`, `password`, `createdAt`, `updatedAt`) VALUES (1, 'jeetendra singh', '[email protected]', MD5('123456'), '2018-12-28 02:05:12', CURRENT_TIMESTAMP), (2, 'Manvik Singh chaudhary', '[email protected]', MD5('654321'), '2018-12-28 03:08:11', CURRENT_TIMESTAMP);

-- create 2 blogs by userid 1--

INSERT INTO `news`.`blogs` (`id`, `user_id`, `title`, `summary`, `body`, `createdAt`, `updatedAt`) VALUES (1, '1', 'Blog title 1 by jeetendra', 'Blog summary 1 by jeetendra', 'Blog body 1 by jeetendra', '2018-12-28 02:00:00', CURRENT_TIMESTAMP), (2, '1', 'Blog Title 2 by jeetendra ', 'Blog summary 2 by jeetendra ', 'Blog body 2 by jeetendra ', '2018-12-28 05:10:21', CURRENT_TIMESTAMP);

-- create 2 blogs by userid 2

INSERT INTO `news`.`blogs` (`id`, `user_id`, `title`, `summary`, `body`, `createdAt`, `updatedAt`) VALUES (3, '2', 'Blog title 1 by manvik', 'Blog summary 1 by manvik', 'Blog body 1 by manvik', '2018-12-28 02:00:00', CURRENT_TIMESTAMP), (4, '2', 'Blog Title 2 by manvik ', 'Blog summary 2 by manvik ', 'Blog body 2 by manvik ', '2018-12-28 05:10:21', CURRENT_TIMESTAMP);

```

#### After creating this create a index.php and put this code for Db connection, login and get all blog method

```

<?php

header("Content-Type: application/json; charset=UTF-8");

class DBClass {

private $host = "localhost";

private $username = "root";

private $password = ""; / /set your passwrd here

private $database = "news";

public $connection;

/ / get the database connection

public function connect(){

$this->connection = null;

try{

$this->connection = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->username, $this->password);

$this->connection->exec("set names utf8");

}catch(PDOException $exception){

echo "Error: " . $exception->getMessage();

}

return $this->connection;

}

public function login($email,$password){

if($this->connection==null)

{

$this->connect();

}

$query = "SELECT id,name,email,createdAt,updatedAt from users where email= ? and password= ?";

$stmt = $this->connection->prepare($query);

$stmt->execute(array($email,md5($password)));

$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);

return $ret;

}

public function get_all_blogs($Uid){

if($this->connection==null)

{

$this->connect();

}

$query = "SELECT b.*,u.id as Uid,u.email as Uemail,u.name as Uname from blogs b join users u on u.id=b.user_id where b.user_id= ?";

$stmt = $this->connection->prepare($query);

$stmt->execute(array($Uid));

$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);

return $ret;

}

public function response($array)

{

echo json_encode($array);

exit;

}

}

/ /recieve the requests here / /

$return=array();

$obj = new DBClass();

if(isset($_GET['action']) && $_GET['action']!='')

{

if($_GET['action']=="login")

{

if(isset($_POST['email']) && isset($_POST['password']))

{

$UserData=$obj->login($_POST['email'],$_POST['password']);

if(count($UserData)>0)

{

$return['status']=1;

$return['_data_']=$UserData[0];

$return['message']='User Logged in Successfully.';

}

else

{

$return['status']=0;

$return['message']='Error:Invalid Email or Password!';

}

}

else

{

$return['status']=0;

$return['message']='Error:Email or Password not provided!';

}

}

elseif($_GET['action']=="UserBlogs")

{

if(isset($_POST['Uid']))

{

$blogs=$obj->get_all_blogs($_POST['Uid']);

if(count($blogs)>0)

{

$return['status']=1;

$return['_data_']=$blogs;

$return['message']='Success.';

}

else

{

$return['status']=0;

$return['message']='Error:Invalid UserId!';

}

}

else

{

$return['status']=0;

$return['message']='Error:User Id not provided!';

}

}

}

else

{

$return['status']=0;

$return['message']='Error:Action not provided!';

}

$obj->response($return);

$obj->connection=null;

?>

```

#### Now api file is set, just make the urls pretty(readable form) using .htaccess file, put following code in it

```

RewriteEngine On

RewriteRule ^api/(.*) index.php?action=$1

```

#### Now your Simple Restful Apis are ready to use, Now Let me show you the postman screenshot where i have used these apis.

**Login Api Call:**

![LOGIN API CALL](https://www.w3school.info/blogimages/login_api.png)

**User Post/Blog Api Call**

![USER BLOGS](https://www.w3school.info/blogimages/UserBlogs_api.png)

7121 views · 1 years ago

![How to install PHPUnit](https://images.ctfassets.net/vzl5fkwyme3u/3ekN0eVrp6IG48IQyYWgAe/12696dff66a9686b9ad5953643c18645/testing.png?w=1000)

PHPUnit is an essential tool for every PHP developers. It is one of those tools that every PHP developer should have installed in their development environment. The problems most first time PHPUnit developers run into are where to install it and how to install it. This quick guide will walk you through the process and answer both questions.

## How do I install PHPUnit

### The Easy Way

In your project’s root directory use this command.

`composer require --dev phpunit/phpunit ^6.0`

This command adds PHPUnit to your project as a development dependency. This is the absolute best way to install PHPUnit. It is the best way because this way the version of PHPUnit does not change unless you change it. We specified ^6.0 as the version which means we’ll get all the updates to the 6.0 branch but not 6.1. While BC breaks don’t happen often in PHPUnit, they have happened. If you have a globally installed version of PHPUnit and you upgrade it to a version that breaks BC, you have to go update all of your tests immediately. This is a lot of hassle if you have a lot of projects with a lot of tests. Keeping a copy of PHPUnit installed as a dev requirement in each project means that each project has its own copy that can be upgraded as necessary.

### The Hard Way

In a command prompt regardless of where you are in your file system, use this command.

`composer global require phpunit/phpunit ^6.0`

On MacOS and Linux machines, this will install PHPUnit in `~/.composer/vendor/bin`. If you add this directory to your path, then from any project, you can execute PHPUnit. However, as noted above, if you ever upgrade your globally installed packages then you will have problems.

`composer global update`

Run that when there is a new version of PHPUnit, it will be installed, regardless of whether this will break your existing unit tests on one or more of your projects. Windows users will need to locate the .composer/vendor/bin directory in your user’s home directory.

### The “ZOMG why would you do it this way” Way

Here is the old-school use wget and move it into the correct position manually. You can do it this way, but you will have to take care of all upgrades manually as well. If you only have a single project on the computer and you never ever plan on changing the version of PHPUnit….nope, still better to use`composer require --dev`.

`wget https://phar.phpunit.de/phpunit-6.0.phar`

`chmod +x phpunit-6.0.phar`

`sudo mv phpunit-6.0.phar /usr/local/bin/phpunit`

`phpunit --version`

These instructions are of course for MacOS or Linux. Windows user won’t need to do chmod or sudo but will need a BAT file.

That’s it. One of those commands should get you a working copy of PHPUnit on your computer.

## Resources:

* [Installing PHPUnit](https://phpunit.de/manual/current/en/installation.html)

* [Composer Introduction](https://getcomposer.org/doc/00-intro.md) (For the Global option)

SPONSORS

Faster PHP Cloud Hosting