Click Here!

Wednesday, 16 August 2017

Give CSS style out link in HTML

How we give style in HTML through link.
      HTML coding

    <html>
<head>      
      // t is the link of the CSS file  
<link href="styles.css" rel="stylesheet">
     // t is the link of the CSS file
</head>
<body>  
<div id='pagewrapper'>    
<h1>We are now under way</h1>  
  <p><a href="http://www.online-web-courses.com">Visit the online course portal</a></p>
<p>This is a paragraph of text. This is a paragraph of text. This is a paragraph of text. This is a paragraph of text. This is a paragraph of text. </p>  
<h2>This is a level-two head</h2>  
<p>This is a paragraph of text. This is a paragraph of text. This is a paragraph of text. This is a paragraph of text. This is a paragraph of text.
</p>    
<div class='mydiv'>    
<ul>      
<li>Unordered list item 1</li>        
<li>Unordered list item 2</li>        
<li>Unordered list item 3</li>      
</ul>      
<ol>        
<li>Ordered list item 1</li>        
<li>Ordered list item 2</li>
<li>Ordered list item 3</li>
</ol>
     </div>
     </div>
   </body>
</html>

This is CSS file which save in name of "style.css"


{
background: #00d;
}


a:link {
text-decoration: none;
color: #009;
}

a:hover {
text-decoration: underline;
}

a:visited {
color: #900;
}

body {
font-family: helvetica, arial, sans-serif;
}


h1, h2, h3, h4, h5, h6 {
font-family: Georgia, Times, "Times New Roman", serif;
}


h1 {
font-size: 30px;
margin-bottom: 20px;
}

h2 {
font-size: 20px;
margin-bottom: 15px;
}

h3 {
font-size: 16px;
margin-bottom: 10px;
}


p, ul, ol {
font-size: 14px;
}

p {
margin: 0 0 10px 0;
line-height: 22px;
}


ul {
list-style-type: disc;
padding-left: 30px;
margin-bottom: 10px;
line-height: 14px;
}

ol {
list-style-type: decimal;
padding-left: 30px;
margin-bottom: 10px;
line-height: 16px;
}


#pagewrapper {
width: 560px;
margin: 20px auto;
border: 1px solid #666;
padding: 20px;
background: #eee;
}

.mydiv {
background: #999;
padding: 30px;
margin: 20px;
border: 1px solid #777;
border-radius: 10px;
}

Thursday, 2 March 2017

Web Designing and Development: PHP MySQL example: image gallery

Web Designing and Development: PHP MySQL example: image gallery: This is a basic case of photograph display script, which utilizes MySQL table (BLOB field) to store pictures. Unimportant secret word securi...

PHP MySQL example: image gallery

This is a basic case of photograph display script, which utilizes MySQL table (BLOB field) to store pictures. Unimportant secret word security, transferring and erasing pictures are upheld. For Apache-adaptation of PHP there is propelled program reserving support (utilizing If-Modified-Since header).

There are three outstanding parts of the script:

principle page era -

creates HTML code for the rundown of transferred photographs, frames for photograph cancellation and transferring

picture transferring -

forms POST ask for: checks watchword, transfers photograph to database or erases it

picture indicating -

Brings picture data from MySQL database and sends picture do program. In the event that PHP is introduced as mod_php (for Apache), does If-Modified-Since HTTP header checking.

Picture display illustration utilizes taking after table to store the greater part of its information:

source code: MySQL / SQL

CREATE TABLE `ae_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 utilize any name for this table, simply change $table variable at the begining of the picture display code.

We utilize taking after capacities in this illustration:

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


You can get help on this capacities writing "PHP function-name" in any great internet searcher

Before utilizing taking after case make sql-table (execute CREATE TABLE question above) and change factors ($db_host, $db_user, $db_pwd, $database, $table) to your MySQL/database settings.


source code: php
<?php
$db_host = 'localhost'; // don't forget to change
$db_user = 'mysql-user';
$db_pwd = 'mysql-password';

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

$password = '123';
// 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>MySQL Blob Image Gallery Example</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>Blob 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> &ndash; ";
        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>


Warning

By default, PHP does not allow uploading files larger than 2Mb. Uploading of large photos fail if you will not change upload-max-filesize and post-max-size directives.
Don't forget to change default password, or use some other authentication method.

Tested 

FreeBSD 5.2 :: PHP 5.1.4
Linux CentOS 4.0 :: PHP 4.4.4

Wednesday, 28 September 2016

Writing data to a database



When you write data to a database, you use SQL statements, specifically the INSERT command. It is straightforward, the INSERT command inserts data into the database. When you use phpMyAdmin, you use a GUI to manage your database, but it also shows you the MySQL commands that it ran when performing your requested tasks. We will use this feature to our advantge to find the correct code to use. What we will do is insert a test comment using phpMyAdmin, and then copy the INSERT command it used.
To INSERT using phpMyAdmin
  1. Log into your cPanel and click the phpMyAdmin icon
  2. In the left menu, first click your database name and then click the table to work with. If you're following our example, we'll first click on "_mysite" and then "comments".
  3. In the top menu, click "Insert"
  4. Type in a sample comment (refer to our screenshot below) and then click GO
  5. After you have run the query, phpMyAdmin will display the insert command it used (see the screenshot below). Copy this SQL statement to a temporary location, such as a text file on your computer.
Step 2 - Writing the PHP code that will execute MySQL Query
Now that we have a sample query, we need to modify it and run in once a user has submitted a comment. Below is example code that will do this. If you're not familiar with php, any line that begins with // is a comment. It is intended for programmers to leave comments about what their code is doing so that either themselves or other people who work on the code have an idea as to what the code is doing. In the example below, we've put in comments explaining what exactly certain peicies of code are doing:
<?

// When someone submits a comment, they "POST" the comment to the server.
// Therefore, we only want to insert a comment to the database if there
// is POST data. The if statement below checks to see if someone has
// posted data to the page
if( $_POST )
{
  // At this point in the code, we know someone has posted data and
  // is trying to post a comment. We therefore need to now connect
  // to the database

  // Below we are setting up our connection to the server. Because
  // the database lives on the same physical server as our php code,
  // we are connecting to "localhost". inmoti6_myuser and mypassword
  // are the username and password we setup for our database when
  // using the "MySQL Database Wizard" within cPanel
  $con = mysql_connect("localhost","inmoti6_myuser","mypassword");

  // The statement above has just tried to connect to the database.
  // If the connection failed for any reason (such as wrong username
  // and or password, we will print the error below and stop execution
  // of the rest of this php script
  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  // We now need to select the particular database that we are working with
  // In this example, we setup (using the MySQL Database Wizard in cPanel) a
  // database named inmoti6_mysite
  mysql_select_db("inmoti6_mysite", $con);

  // We now need to create our INSERT command to insert the user's
  // comment into the database.
  //
  // Let's first take a look at the sample INSERT code we received when we
  // used phpMyAdmin to create a test comment:
  //
  // INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
  // `comment`, `timestamp`, `articleid`) VALUES (NULL, 'John Smith',
  // 'johns@domain.com', 'johnsmith.com', 'This is a test comment.',
  // CURRENT_TIMESTAMP, '1');
  //
  // If we ran this command, it would insert the same exact comment from John
  // Smith every time. What we need to do is update this query so that it
  // includes all of the data that the user typed in.
  //
  // When we setup our HTML Form, some of the text boxes we used were:
  // <input type='text' name='name' id='name' />
  // <input type='text' name='email' id='email' />
  // The important information we need from this is the "id" that is set.
  // For example, to get the user's name, we can grab the 'name'. To
  // get their email address, we need to get the value of 'email'.
  //
  // Using the $_POST variable, we can get this data. This is what we're
  // doing below
  $users_name = $_POST['name'];
  $users_email = $_POST['email'];
  $users_website = $_POST['website'];
  $users_comment = $_POST['comment'];

  // We now have all of the data that the user inputed. What you don't want
  // to do is trust the user's input. Savy users / hackers may attempt to use
  // an sql injection attack in order to run sql statements that you did not
  // intend to run. For example, the following is a basic query for checking
  // someone's username and password:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='PASSWORD'
  //
  // In the above, we're assuming the user typed USERNAME as their username and
  // PASSWORD as their PASSWORD. But, what if the user typed the following as
  // their password?
  //
  // ' OR ''='
  //
  // The new query would then be the following:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='' OR ''=''
  //
  // Running the above query would allow anyone to login as any user! We can use
  // the mysql_real_escape_string function to escape the user's input. If used in
  // the above example, the new query would read:
  //
  // SELECT * FROM users WHERE user='USERNAME' AND password='\' OR \'\'=\''
  //
  // Because the single quotes are "escaped" (i.e. appended with a backslash), the
  // hackers attempt would fail.
  $users_name = mysql_real_escape_string($users_name);
  $users_email = mysql_real_escape_string($users_email);
  $users_website = mysql_real_escape_string($users_website);
  $users_comment = mysql_real_escape_string($users_comment);
 
  // We also need to get the article id, so we know if the comment belongs
  // to page 1 or if it belongs to page 2. The article id is going to be
  // passed in the URL. For example, looking at this URL:
  //
  // http://phpandmysql.inmotiontesting.com/page1.php?id=1
  //
  // The article id is 1. To get data from the url, use the $_GET variable,
  // as in:
  $articleid = $_GET['id'];

  // We also want to add a bit of security here as well. We assume that the $article_id
  // is a number, but if someone changes the URL, as in this manner:
  // http://phpandmysql.inmotiontesting.com/page2.php?id=malicious_code_goes_here
  // ... then they will have the potential to run any code they want in your
  // database. The following code will check to ensure that $article_id is a number.
  // If it is not a number (IE someone is trying to hack your website), it will tell
  // the script to stop executing the page
  if( ! is_numeric($articleid) )
    die('invalid article id');

  // At this point, we've grabbed all of the data that we need. We now need
  // to update our SQL query. For example, instead of "John Smith", we'll
  // use $users_name. Below is our updated SQL command:
  $query = "
  INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',
        '$users_email', '$users_website', '$users_comment',
        CURRENT_TIMESTAMP, '$articleid');";

  // Our SQL stated is stored in a variable called $query. To run the SQL command
  // we need to execute what is in the $query variable.
  mysql_query($query);

  // We can inform the user to what's going on by printing a message to
  // the screen using php's echo function
  echo "<h2>Thank you for your Comment!</h2>";

  // At this point, we've added the user's comment to the database, and we can
  // now close our connection to the database:
  mysql_close($con);
}

?>
Don't let all of that code be intimidating! When we take out all of the comments, the code is much shorter and looks like this:
<?
if( $_POST )
{
  $con = mysql_connect("localhost","inmoti6_myuser","mypassword");

  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("inmoti6_mysite", $con);

  $users_name = $_POST['name'];
  $users_email = $_POST['email'];
  $users_website = $_POST['website'];
  $users_comment = $_POST['comment'];

  $users_name = mysql_real_escape_string($users_name);
  $users_email = mysql_real_escape_string($users_email);
  $users_website = mysql_real_escape_string($users_website);
  $users_comment = mysql_real_escape_string($users_comment);

  $articleid = $_GET['id'];
  if( ! is_numeric($articleid) )
    die('invalid article id');

  $query = "
  INSERT INTO `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`,
        `comment`, `timestamp`, `articleid`) VALUES (NULL, '$users_name',
        '$users_email', '$users_website', '$users_comment',
        CURRENT_TIMESTAMP, '$articleid');";

  mysql_query($query);

  echo "<h2>Thank you for your Comment!</h2>";

  mysql_close($con);
}
?>
Step 3 - Placing our php code in our pages
Now that we have the php code to insert the comments into the database, we need to put the code into our pages (page1.php and page2.php). In our previous article, we showed you how to use php's include function to help manage blocks of code effeciently, and we will again use the include function.
To incorporate our php code:
  1. Create a file named manage_comments.php
  2. Paste in the sample code above
  3. Update both page1.php and page2.php to include manage_comments.php by using
<? include("manage_comments.php"); ?>
at the top of the file
At this time, we are now working with 4 different files, and they are all in the same directory:
Also, after incorporating <? include("manage_comments.php"); ?>, our page1.php file now looks like this:
<? include("manage_comments.php"); ?>

<h1>This is page1.php</h1>

<div><a href='page2.php?id=2'>Click here</a> to go to page2.php</div>

<div style='margin:20px; width:100px; height:100px; background:blue;'></div>

<? include("formcode.php"); ?>