Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Friday, April 15, 2016

PHP 7 with Microsoft SQL Server Driver Released



Microsoft announced on 12th April 2016 early technical preview of the Microsoft Driver 4.0.3 for PHP for SQL Server, using this driver you can connect your PHP application with Microsoft SQL Server currently this server is available only for PHP 7. This Driver enable you to access SQL Server, Azure SQL Database and Azure SQL DW from your PHP 7 apps.

Download Driver


Future Plans

Microsoft plan on a Linux port, expand SQL 16 Feature Support (example: Always Encrypted), build verification/fundamental tests, bug fixes.
This early technical preview provide some limited support on this github page here

We hope this add-on will help you in your future development.

Source: https://blogs.msdn.microsoft.com/sqlphp/2016/04/12/early-technical-preview-of-microsoft-drivers-4-0-3-for-php-for-sql-server-released/

Friday, May 29, 2015

Generate and save file in directory using PHP

4everTutorials

In this lesson we will see how to generate file and save into new directory using PHP. So we will generate a HTML, PHP or any other type of file and save it into a newly created or existed directory.

Step 1: At first we have to select an existing directory or create a new directory by using mkdir() function.


<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

$dir_path = "depth1/depth2/depth3";
 
mkdir($dir_path, 0777, true);

?>

Here, $dir_path is the path to the expected directory/folder of your hard drive.
And ’0777′ is the default permission of the folder/file (widest possible access).

So, the file will be located in this directory: current_directory/depth1/depth2/depth3

But if you want to create the folder outside the current directory, then use “../” for each level you want to go back for the new directory.

For example, if your current directory is “C:\xampp\htdocs\cd” and you want to create the new folder inside “xampp” folder then you have to write like the following-


<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

$dir_path = "../../test";
 
mkdir($dir_path, 0777, true);

?>


So, path for the new directory will be “C:\xampp\test”.

Step 2: After creating the directory simply put the generated file to the directory by using file_put_contents() function.

<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

file_put_contents($dir_path."/name-of-file.html", $content);
file_put_contents($dir_path."/name-of-file.php", $content);
file_put_contents($dir_path."/name-of-file.txt", $content);

?>

Here, name-of-file is the expected name of your file and $content is the the data that you want to save in the file.

Saturday, August 23, 2014

php capture website screenshot script

In this post we learn how to take websites screenshots very easily in PHP using Grabz.it 's API. First of all you need to create grabz.it account  to get API keys (APPLICATION KEY and APPLICATION SECRET) . Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account. The best way to put website screenshots into your PHP application is by using our simple PHP API.
<?php

/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/
include("GrabzItClient.class.php");

$grabzIt = new GrabzItClient("APPLICATION KEY", "APPLICATION SECRET");// Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account!

// To take a image screenshot
$grabzIt->SetImageOptions("http://www.google.com");     
// Or to take a PDF screenshot
$grabzIt->SetPDFOptions("http://www.google.com");
// Or to capture table(s)
$grabzIt->SetTableOptions("http://www.google.com");

?>

Above code is used to create class object with your account API key and secret after creating object we are calling 3 different methods SetImageOptions used to capture image of given page output, SetPDFOptions used to create PDF of given url and SetTableOptions is used to extract tables from the web page.

More Options

There are many more options including; configuring the browser height, browser width, screenshot height, screenshot width, the delay before a screenshot is taken and the image format of the screenshot. For all these options please see the Client documentation.


Wednesday, June 27, 2012

Create PHP Image Gallery with MySQL Blob Field

This is a simple example of photo-gallery script, which uses MySQL table (BLOB field) to store images. Trivial password-protection, uploading and deleting images are supported.

There are three main parts of the script:
  • main page generation --
    generates HTML code for the list of uploaded photos, forms for photo deletion and uploading
  • image uploading --
    processes POST request: checks password, uploads photo to database or deletes it
  • image showing --
    Fetches image information from MySQL database and sends image do browser. If PHP is installed as mod_php (for Apache), does If-Modified-Since HTTP header checking.

Create MySQL / SQL Table

/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

CREATE TABLE `gallery` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(64) character SET utf8 NOT NULL,
  `ext` varchar(8) character SET utf8 NOT NULL,
  `image_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `data` mediumblob NOT NULL,
  PRIMARY KEY  (`id`) 
);



You can use any name for this table, just change $table variable at the begining of the image gallery code.
We use following functions in this example:


MySQL
  • mysql_connect - connects to MySQL server
  • mysql_select_db - select database
  • mysql_query - send query
  • mysql_fetch_row - get current row from result table
  • mysql_real_escape_string - escaping string to use it in MySQL query
  • mysql_num_fields - get number of rows
PHP
  • get_magic_quotes_gpc - checking if PHP add slashes before quotes in input parameters
  • stripslashes - remove odd slashes
  • trim - remove unnecessary spaces in the beginning and ending of string
  • getimagesize - return image information as an array. Third element of array -- image type.
  • file_get_contents - loads whole file into memory
  • php_sapi_name - returns the name of PHP Server API
  • apache_request_headers - gets some special header information from Apache
  • strtotime - convert textual representation of time to integer (number of seconds since 1970)
  • header - sends HTTP header to browser
Before using following example create sql-table (execute CREATE TABLE query above) and change variables ($db_host, $db_user, $db_pwd, $database, $table) to your MySQL / database settings.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$db_host = 'localhost';  
$db_user = 'username'; 
$db_pwd = 'password';

$database = 'test';
$table = 'gallery'; // use the same name as SQL table

$password = 'pass7';
// simple upload restriction,
// to disallow uploading to everyone


if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);

    return mysql_real_escape_string($s);
}

// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // cleaning title field
    $title = trim(sql_safe($_POST['title']));

    if ($title == '') // if title is not set
        $title = '(empty title)';// use (empty title) string

    if ($_POST['password'] != $password)  // cheking passwors
        $msg = 'Error: wrong upload password';
    else
    {
        if (isset($_FILES['photo']))
        {
            @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
            // Get image type.
            // We use @ to omit errors

            if ($imtype == 3) // cheking image type
                $ext="png";   // to use it later in HTTP headers
            elseif ($imtype == 2)
                $ext="jpeg";
            elseif ($imtype == 1)
                $ext="gif";
            else
                $msg = 'Error: unknown file format';

            if (!isset($msg)) // If there was no error
            {
                $data = file_get_contents($_FILES['photo']['tmp_name']);
                $data = mysql_real_escape_string($data);
                // Preparing data to be used in MySQL query

                mysql_query("INSERT INTO {$table}
                                SET ext='$ext', title='$title',
                                    data='$data'");

                $msg = 'Success: image uploaded';
            }
        }
        elseif (isset($_GET['title']))      // isset(..title) needed
            $msg = 'Error: file not loaded';// to make sure we've using
                                            // upload form, not form
                                            // for deletion


        if (isset($_POST['del'])) // If used selected some photo to delete
        {                         // in 'uploaded images form';
            $id = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE id=$id");
            $msg = 'Photo deleted';
        }
    }
}
elseif (isset($_GET['show']))
{
    $id = intval($_GET['show']);

    $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data
                             FROM {$table}
                            WHERE id=$id LIMIT 1");

    if (mysql_num_rows($result) == 0)
        die('no image');

    list($ext, $image_time, $data) = mysql_fetch_row($result);

    $send_304 = false;
    if (php_sapi_name() == 'apache') {
        // if our web server is apache
        // we get check HTTP
        // If-Modified-Since header
        // and do not send image
        // if there is a cached version

        $ar = apache_request_headers();
        if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
            ($ar['If-Modified-Since'] != '') && // not empty
            (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than
            $send_304 = true;                                     // image_time
    }


    if ($send_304)
    {
        // Sending 304 response to browser
        // "Browser, your cached version of image is OK
        // we're not sending anything new to you"
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);

        exit(); // bye-bye
    }

    // outputing Last-Modified header
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT',
            true, 200);

    // Set expiration time +1 year
    // We do not have any photo re-uploading
    // so, browser may cache this photo for quite a long time
    header('Expires: '.gmdate('D, d M Y H:i:s',  $image_time + 86400*365).' GMT',
            true, 200);

    // outputing HTTP headers
    header('Content-Length: '.strlen($data));
    header("Content-type: image/{$ext}");

    // outputing image
    echo $data;
    exit();
}
?>
<html><head>
<title>Create PHP Image Gallery with MySQL Blob Field</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for
                 // outputing message
{
?>
<p style="font-weight: bold;"><?=$msg?>
<br>
<a href="<?=$PHP_SELF?>">reload page</a>
<!-- I've added reloading link, because
     refreshing POST queries is not good idea -->
</p>
<?php
}
?>
<h1>PHP-MySQL Image Gallery</h1>
<h2>Uploaded images:</h2>
<form action="<?=$PHP_SELF?>" method="post">
<!-- This form is used for image deletion -->

<?php
$result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC");
if (mysql_num_rows($result) == 0) // table is empty
    echo '<ul><li>No images loaded</li></ul>';
else
{
    echo '<ul>';
    while(list($id, $image_time, $title) = mysql_fetch_row($result))
    {
        // outputing list
        echo "<li><input type='radio' name='del' value='{$id}'>";
        echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – ";
        echo "<small>{$image_time}</small></li>";
    }

    echo '</ul>';

    echo '<label for="password">Password:</label><br>';
    echo '<input type="password" name="password" id="password"><br><br>';

    echo '<input type="submit" value="Delete selected">';
}
?>

</form>
<h2>Upload new image:</h2>
<form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
<label for="title">Title:</label><br>
<input type="text" name="title" id="title" size="64"><br><br>

<label for="photo">Photo:</label><br>
<input type="file" name="photo" id="photo"><br><br>

<label for="password">Password:</label><br>
<input type="password" name="password" id="password"><br><br>

<input type="submit" value="upload">
</form>
</body>
</html>


 

© 2014 4everTutorials. All rights resevered.

Back To Top