Category: Tutorials

HTML Linking Stylesheets

There are several ways to incorporate styles to elements in your HTML and apply them throughout the document. In this we will go over three ways to include styles, and three ways to apply the styles to different elements.

Linking External Stylesheets

You can link an external stylesheet to your HTML document through the <link> tag.

[code lang=”html”] [/code]

You would place this in the <head> tag of your document. External stylesheets are to consist of only defined classes and styles, no other tags included. Here would be a basic layout of style.css:

[code lang=”css”]
.class1 {
color:#fff;
font: 11px tahoma;
}

.class2 {
color: #000;
font: 11px arial;
}

#class3 {
color: #ccc;
font: 11px verdana;
}
[/code]

Embedding Styles

You can embed styles into the <head> of a HTML document without creating an external stylesheet. Here is an example of styles embedded:

[code lang=”html”]


HTML Document

Text.


[/code]

These styles would be defined just as in an external stylesheet and should not include any other tags inside the <style> tags.

Importing a Stylesheet

In CSS there is an import statement you can use to import a stylesheet to the document. This the CSS @import statement. Here is an example:

[code lang=”html”]


HTML Document

Text.


[/code]

You can still define other styles in these <style> tags under the @import statement just as in the previous example. This will basically include the defined path to a CSS stylesheet to the document just as using the external linking example.

Now we will go over how to apply these styles to elements.

Class Attribute

In your HTML document you can apply styles using the class attribute to almost any element. Styles that are applied with the class attribute are defined with a period before their name. In the previous examples of defining styles you may see a period (.) before the titles. Ex: .class1; .class2. Here is how to apply them:

[code lang=”html”]

White text in Tahoma.
Black text in Arial.

[/code]

ID Attribute

Styles can also be defined and applied by the ID attribute. To define a style using this attribute you would add a number symbol (#) in front of the title. In the previous examples you see that “class3” is defined with one like #class3. This works the same way was the class attribute except now we apply it with the ID attribute in the element. Here is how to apply them:

[code lang=”html”]

Grey text in Verdana.

[/code]

In-Line Styling

Without the use of any defined styles in a stylesheet or embedded styles you can apply styles to elements with in-line styling. This is done using the style attribute in an element. Here is how to apply them:

[code lang=”html”]

White text in Tahoma.
Black text in Arial.
Grey text in Verdana.

[/code]

Styles can also be defined within each other. So you can define a class under the <p> tag that can only be defined to paragraphs. Like so:

[code lang=”css”]
p .small {
font-size: 11px;
}
[/code]

Now we can apply the small class to paragraphs in the document like so:

[code lang=”html”]

Regular text.

Small text.

[/code]

Filed under: TutorialsTagged with: , ,

Javascript Snowing Effect Script

Here is a nice feature to add to your web pages during the holiday season. Falling snowflakes are very simple and yet a great eye catcher to new visitors to your website.

Here is the snowflake gif I made for this:

Falling Snowflake

Now, to make  the effect of the snowflake falling on the webpage we will just use javascript. You want to place this code in the <head> tags of your webpage and it will give you the pretty effect that it is snowing! You can do this with other seasons as well like autumn, you would want to use a leaf of some kind. Here is the code:

[code lang=”javascript”]

[/code]

Enjoy!

Filed under: Scripts, TutorialsTagged with: , ,

PHP Users Online with Mysql

Using PHP and Mysql you can keep track of the users online your website and display it on your page.

First thing ,we need a table in our Mysql database for the users online. So let’s make a table in our database.

[code lang=”sql”]
mysql_query(“CREATE TABLE online(
id INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
ip_address VARCHAR(25) NOT NULL,
timestamp VARCHAR(25) NOT NULL)”) or die(mysql_error());
[/code]

Now that we have the table, we need to update the users online on every page. That way it is most accurate and up to date with who is currently online. We will set a time offset so that we include all users online within the past 5 minutes.

[code lang=”php”]
0){
mysql_query(“UPDATE online SET timestamp = ‘”.time().”‘ WHERE ip_address = ‘$ip’) or die(mysql_error());
} else {
mysql_query(“INSERT INTO online (ip_address,timestamp) VALUES (‘$ip’,'”.time().”‘)”) or die(mysql_error());
}
$delete = mysql_query(“DELETE FROM online WHERE timestamp < '$time_offset'") or die(mysql_error()); ?>
[/code]

Now every time someone goes on a page with this code, mysql will check to see if the user is in the system, and if so update their current timestamp, otherwise create a row for them in the table. It will also erase any rows with old timestamps. This will keep the table clean and updated.

Now we count the users online and show it on the page.

[code lang=”php”]
‘$time_offset'”);
$online = mysql_num_rows($sql);

return ‘There are ‘.$online.’ user(s) currently online. ‘;
}
?>
[/code]

Filed under: TutorialsTagged with: , ,

PHP Display Mysql Rows with Column Limit

This little script is very useful for having a set width of a table and displaying several rows organized in that table.

It is easy to just display a table full of rows for all the data in a mysql table. Something like this:

[code lang=”php”]
0){
echo “

“;
echo “

“;
while($row = mysql_fetch_array($sql)){
echo “

“;
}
echo “

“.$row[“col1″].”

“;
}
?>
[/code]

This will grab all content of the mysql table and put the data from column 1 as a table column in this table.

Let’s say we have some images we want to display. The table is 500 pixels wide. So if your images are no larger than 100 pixels, you would want to display 5 columns per row in your table. This will give it good organization and flow in your webpage.

[code lang=”php”]
0){
echo “

“;
echo “

“;
for($i=0;$i<=mysql_num_rows($sql);$i=$i+1){ while($row = mysql_fetch_array($sql)){ $i++; if($i%5==0){ // use the operator to find the remainder of $i / 5 (%) // if the remainder is 0; it is a multiple of 5, so make a new row. echo " “;
} else {
echo “

“;
}

}
}
echo “

“;
}
?>
[/code]

The two codes will appear like so:

Before Column Limit:

Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7 Image 8 Image 9 Image 10

After Column Limit:

Image 1 Image 2 Image 3 Image 4 Image 5
Image 6 Image 7 Image 8 Image 9 Image 10
Filed under: TutorialsTagged with: , , ,

PHP Get File Size of Remote File

Previously in a post I made for uploading a file from URL we wanted to include a file size check to make sure the file wasn’t too big before we upload it. Here I’ll show you how to get the remote file’s size and other information before doing other functions with it.

We’ll do this through a simple form. By default a form will encode all characters and convert spaces to “+” so we will leave the enctype undefined.

Then we just need the text input named “url” which I gave a default value “Enter URL Here…” and the Javascript-related attribute – onfocus. So when you focus on the text input it will change from the default value to blank.

Finally of course, we include the submit input named “submit” with the value “Submit.” We will use this value to check that the  form was submitted.

[codesyntax lang=”html4strict” title=”HTML Form”]
<form action=”getinfo.php” method=”post”>
<input type=”text” name=”url” size=”40″ value=”Enter URL Here…” onfocus=”if(this.value == ‘Enter URL Here…’) this.value = ”;” /> <input type=”submit” name=”submit” value=”Submit” />
</form>
[/codesyntax]

This HTML form will submit the entered url to getinfo.php.

We are going to the function fopen() to get the information we need from the remote file. There is one thing to be aware of using fopen() to retrieve this data. You need to be sure the fopen wrappers is enabled in your php.ini. This can not be changed using ini_set().

We are going to create a variable “contents” and add each line of the file to it as we read it. Then we will use the function mb_strlen() to get the file size of the variable. Normally we would use strlen(), however that will only read one character as one byte. That doesn’t really give you the most accurate reading if you have special characters in the file which are more than one byte.

By default the function fgets() reads each line of a file 1024 bytes at a time. The function runs until either the specified length is reached (1024 bytes) or to the end of the file. It is more resource efficient to specify a read length:

“Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.”php.net

getinfo.php

[codesyntax lang=”php” title=”getinfo.php Source Code”]
<?php
// getinfo.php

if($_POST[“submit”]){
// Form is submitted.

// Check the fopen wrapper settings in php.ini
if (ini_get(“allow_url_fopen”) == 1) {

// Open the file.
$file = fopen(trim($_POST[“url”]), “r”);

if($file){
// We got the file.

$contents = “”;
while($line = fgets($file,1024)){
// Write each line to the string contents a kilobyte at a time.
$contents .= $line;
}

$filesize = mb_strlen($contents,”8bit”);
$kb = $filesize / 1024; // Returns the file size in kilobytes
echo “<strong>File Size</strong>:  “.$filesize.” bytes or “.$kb.” kilobytes.”;

} else {

echo “Remote file not found.”;

}

} else {

echo “Fopen wrappers not enabled.”;

}

}

?>
[/codesyntax]

The page will display the file size in bytes and kilobytes, as so:
File Size: 1024 bytes or 1 kilobytes.

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , , ,

Making a Background Pattern

Here is how to make a very basic background pattern to use on your webpage. We’ll be using Photoshop to make this.

First, open up a new document, with dimensions 5 pixels by 5 pixels.

Create new document.
Create new document.

Then pick a good solid background color, something not too dark that will match the colors of your website. I went with a medium blue color (#004491).

Background color.
Background color.

Now we choose a darker color to make the pattern on top of the blue background color. You can make any pattern you want. I’m gunna show you two different patterns. One will be just a dotted pattern and the other will be diagonal line. Here are the two patterns:

Dotted Pattern
Dotted Pattern
Diagonal Line Pattern
Diagonal Line Pattern

I used the dark blue color (#001c3b) for the pattern. Just take the pencil tool:

Pencil Tool
Pencil Tool

and click on the center of the 5×5 canvas to make the dot pattern. For the diagonal pattern just click along a diagonal line with the pencil tool. Then just save the image as a gif file “background.gif.”

Now we can insert it into our webpage as the background:

[code lang=”html”]

[/code]

Click here to see examples of these background patterns.

Filed under: TutorialsTagged with: , ,

PHP Image Verification in Forms

One of the most common ways to stop bots and spammers from generating spam in people’s websites is using some form of image verification. This can be done very easily with just PHP and Sessions. Using image verification acts as a human detector, to make sure the viewer of that page is not a bot of some kind. Bots can cause damage to your server by overloading it with spammed content and flooding your boards with unwanted links and text.

Let’s say we have a form that submits a few fields and possibly a file:

[code lang=”html”]

Field 1:
Field 2:
File:

[/code]

Now, this form will submit three variables: field1, field2, and the file.

This form does not have any image verification added in. So any bot could simply process this page over and over to flood the server with crap. 🙁 So we are going to add a simple image verification to the form. To do this we make image.php:

[code lang=”php”]

[/code]

Now we must add the field to our form:

[code lang=”html”]
Verification: &amp;nbsp;

[/code]

Notice I used the class “imgverification.” We must add this to our <head> tags of the page:

[code lang=”html”]

[/code]

We must also make sure we include our session_start() on all pages we use session variables on. So on our form page, the image page, and submit page.

Now when the form is submitted to submit.php we check the submitted input for $_POST[“verification”] to $_SESSION[“md5_image_verification”].

[code lang=”php”]

[/code]

function simple_image($width,$height){
$image = imagecreate($width,$height);

$alphanum = “ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”;
$rand = strtoupper(substr(str_shuffle($alphanum),0,6));
$_SESSION[‘simp_image_verification’] = $rand;
$_SESSION[‘md5_simp_image_verification’] = md5($rand);

$bgColor = imagecolorallocate($image, 231,231,231);
$textColor = imagecolorallocate($image, 0,0,0);
$textSize = imagefontheight(1);
imagestring ($image, 5, 8, 2, $_SESSION[‘simp_image_verification’], $textColor);
header(“Expires: Mon, 26 Jul 1997 05:00:00 GMT”);
header(“Last-Modified: ” . gmdate(“D, d M Y H:i:s”) . ” GMT”);
header(“Cache-Control: no-store, no-cache, must-revalidate”);
header(“Cache-Control: post-check=0, pre-check=0”, false);
header(“Pragma: no-cache”);
header(‘Content-type: image/jpeg’);
imagejpeg($image);
imagedestroy($image);
return true;
}

Filed under: TutorialsTagged with: , , ,

PHP Upload file from URL

Let’s say you have a form on a page with the input for URL to a file so you can upload it to your server. You can do this using PHP functions.

Here is an example of a form to upload:

[code lang=”html”]

Enter URL:

[/code]

Now on upload.php we need to have PHP run an upload of the file based on the entered URL. Here is how it will look.

The form above submitted two variables, the url text, and the submit button (value “submit”). So when we start the PHP code, we check it was submitted with the submit button.

We trim the url submitted through the form using the function trim() for the url to be accessed then create a filename using the function basename(). We then check that the url exists after having these functions applied to it. This is what we are going to submit to upload.

$file = Opening the url submitted with read-only permissions. This is defined with the “rb.”

[code lang=”php”]
$file = fopen($url,”rb”);
[/code]

Once we have opened the file we create a random number. This is going to be added to the file’s name when we upload it so that no two files have the same name. This is done very simply with the function rand(). Simply set the minimum and maximum for random numbers.

$newfile = Open the new file we are creating on our server. This actually creates the file on the server in the folder $directory with the random number ($rand) and the file’s name ($filename). This is done with writing permissions so that we can write the data from the url file to this one.

[code lang=”php”]
$rand = rand(1000,9999); // random number 4 digits long
$filename = $rand . basename($url); // places random number in front of the url’s base name
$newfile = fopen($directory . $filename, “wb”);
[/code]

If this new file can be created, we start writing the data to the file. To do this we use the function feof(). So if the new file exists now, while we haven’t reached the end of the url file, we write this content to the one on our server. This sounds a little confusing but it is quite easy.

Code:

[code lang=”php”]
if($newfile){
while(!feof($file)){

// Write the url file to the directory.
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}

}
[/code]

This script basically says write the data of the url file up until we reach 8kb, to the new file we created on the server. You can adjust the maximum size in kb by changing the “8” to whatever you wish. Once it reaches the end of the file, it will stop writing.

Now let’s say we want to check for filetypes. No one wants people uploading unsafe filetypes to their server. This is a serious problem if you do not check the filetypes being uploaded. So once we establish that the file exists through the URL we are going to check its extension to match ones we allow.

$valid_exts = An array of the valid extensions we allow the user to upload. (i.e. image files).

[code lang=”php”]
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”);
[/code]

$ext = We find the extension of the file by using the function explode(). This function splits the url into an array based on a seperator, in this case the seperator is a period “.” to find the trailing extension. We then set this to all lowercase because that is what our valid extensions are in. Also, we use the end() function to this array because it is possible the url has more than one period in it. We want to make sure we get JUST the extension on the end.

[code lang=”php”]
$ext = end(explode(“.”,strtolower(basename($url))));
[/code]

Here is the complete code:

Upload.php

[codesyntax lang=”php” title=”upload.php PHP Source Code”]<?php
// UPLOAD.PHP
if($_POST[“submit”]){
$url = trim($_POST[“url”]);
if($url){
$file = fopen($url,”rb”);
if($file){
$directory = “./downloads/”; // Directory to upload files to.
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”); // default image only extensions
$ext = end(explode(“.”,strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$rand = rand(1000,9999);
$filename = $rand . basename($url);
$newfile = fopen($directory . $filename, “wb”); // creating new file on local server
if($newfile){
while(!feof($file)){
// Write the url file to the directory.
fwrite($newfile,fread($file,1024 * 8),1024 * 8); // write the file to the new directory at a rate of 8kb/sec. until we reach the end.
}
echo ‘File uploaded successfully! You can access the file here:’.”\n”;
echo ”.$directory.$filename.”;
} else { echo ‘Could not establish new file (‘.$directory.$filename.’) on local server. Be sure to CHMOD your directory to 777.’; }
} else { echo ‘Invalid file type. Please try another file.’; }
} else { echo ‘Could not locate the file: ‘.$url.”; }
} else { echo ‘Invalid URL entered. Please try again.’; }
}
?>

[/codesyntax]

When the form is submitted, PHP uploads the file to the directory – $directory – which is set to “./downloads/” by default. The function !feof() reads as – before reaching the end of a file. So while it hasn’t reached the end, write to $directory. Once the function returns false (when we have reached the end of the file) it will stop. The path to the file is given as “$directory.$filename.”

I have made a script for uploading multiple files from a URL or your computer’s HDD viewable here:

https://bgallz.dev/1345/php-upload-multiple-files-url/

Enjoy!

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , , , , ,

Uploading Files with PHP

With many forms you may want to include some sort of upload of a file. There are many functions for files in PHP that you can use to do this.

Some things you may want to consider when uploading a file to your server:

  • File extension – what type of file is being uploaded.
  • File size – How big is the file, should the be a limit?
  • What to do on a successful upload.

Here is a basic form uploading to the file “upload.php”.

[code lang=”html”]


[/code]

Now on upload.php we need to have code that reacts to this form being submitted, other wise nothing will happen obviously.

[code lang=”php”][/code]

That would be our code for upload.php. When the form is submitted it will execute that code and perform the upload as long as it passes the tests.

You  can specify any directory, extensions, filesize limit you want of course. Enjoy.

Filed under: Scripts, TutorialsTagged with: , ,