Tag: script

PHP Upload Multiple Files From URL

In a previous post I made I showed you how to upload a file from a URL using a PHP script. You can view this post here.

Now I will show you how to take this a step further and upload multiple files from multiple URLs or uploaded from the user’s computer.

Because we will have multiple files to upload we are going to want to make an array of these files that include all their attributes. Then we’ll process each file at a time and based on whether it is coming from a URL or the user’s hard drive, we will upload it accordingly.

Here is a preview of what our form will look like:

Here is our HTML for this form on index.php:

<form action="./index.php?do=upload" method="post" enctype="multipart/form-data" name="upload_files_form">
<div id="upload_files">
<div id="upload_file_1">
<div>
<button id="1_computer_button" name="upload_type_computer" type="button" onclick="hideElement('1_upload_url'); showElement('1_upload_computer')">Upload From Computer</button>
<button id="1_url_button" name="upload_type_url" type="button" onclick="hideElement('1_upload_computer'); showElement('1_upload_url')">Upload From URL</button>
</div>
<div>
<div id="1_upload_computer">
<input type="file" name="files_hdd[]" size="30" />
</div>
<div id="1_upload_url" style="display:none">
<input type="text" name="files_url[]" size="30" maxlength="100" value="http://" onfocus="if(this.value == 'http://') this.value = '';" id="1_input_url" />
</div>
</div>
</div>
<div id="upload_file_2">
<div>
<button id="2_computer_button" name="upload_type_computer" type="button" onclick="hideElement('2_upload_url'); showElement('2_upload_computer')">Upload From Computer</button>
<button id="2_url_button" name="upload_type_url" type="button" onclick="hideElement('2_upload_computer'); showElement('2_upload_url')">Upload From URL</button>
</div>
<div>
<div id="2_upload_computer">
<input type="file" name="files_hdd[]" size="30" />
</div>
<div id="2_upload_url" style="display:none">
<input type="text" name="files_url[]" size="30" maxlength="100" value="http://" onfocus="if(this.value == 'http://') this.value = '';" id="2_input_url" />
</div>
</div>
</div>
<div id="upload_file_3">
<div>
<button id="3_computer_button" name="upload_type_computer" type="button" onclick="hideElement('3_upload_url'); showElement('3_upload_computer')">Upload From Computer</button>
<button id="3_url_button" name="upload_type_url" type="button" onclick="hideElement('3_upload_computer'); showElement('3_upload_url')">Upload From URL</button>
</div>
<div>
<div id="3_upload_computer">
<input type="file" name="files_hdd[]" size="30" />
</div>
<div id="3_upload_url" style="display:none">
<input type="text" name="files_url[]" size="30" maxlength="100" value="http://" onfocus="if(this.value == 'http://') this.value = '';" id="3_input_url" />
</div>
</div>
</div>
</div>
<input type="submit" name="submit" value="Upload Files Now" onclick="showUploadDiv()" />  <input type="reset" name="reset" value="Reset Fields" />
<p> </p>
<div id="uploading" style="display:none">
</div>
</form>

This form contains three file inputs, either uploaded from the user’s computer, or given by a URL to a file. There are two buttons for each input which enable and disable the HDD or URL upload options. Now, I haven’t made the script to completely disable the URL input once a file has been selected from the user’s computer, so when the form is submitted it will check for uploaded files first over files being gathered from a URL. So you will want to include that on your main page so users know you can only upload three files at a time here, not six.

The form includes the animated loading gif feature which I posted here:
https://bgallz.dev/1140/how-to-make-animated-loading-gif/

You’ll notice on the submit button it activates the Javascript function “showUploadDiv().” This function changes the display style setting on the uploading div and then fills it with some text and the animated loading image.

I also have used some jQuery for the buttons to be used effectively:

<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var clickedClass = "selected";
var buttons = "#upload_files button";
$(buttons).click(function() {
$(this).addClass(clickedClass).siblings().removeClass(clickedClass);
});
});
</script>

What this jQuery says is to add the class “selected” – from clickedClass – to the current button that is being clicked, and remove that class name from all other buttons within the current parent’s sibilings. Sounds a little complicated, but it’s very simple. The buttons are loaded from “#upload_files button” – so thats all the button elements within the div ID “upload_files.”

Now finally for the PHP of the script. On index.php we include the following in the header:

$valid_exts = array(
"gif","png","jpeg","jpg",
"image/gif","image/jpeg","image/png","image/jpg"
); // array of valid file extensions
$max_file_size = 32; // file size in kb
$upload_dir = "files/"; // directory to upload to with trailing slash

$upload_result = "";

if(isset($_GET['do']) && $_GET['do'] == "upload"){
$upload_result = run_upload_form();
}

So when the form is submitted – which is sent to “index.php?do=upload” – we run the function run_upload_form() and set the $upload_result to its returned value.

The key variables defined at the beginning of the script are there for you to modify as you need them. Of course you can modify the function itself to output different values as you need them to be. Currently the script checks against the following before uploading:

  • Valid extension type (image files by default)
  • File size limit (32KB by default)
  • Upload directory exists and is writable
  • URL validation for remote file size and type

To view the rest of the PHP as well as the Javascript and CSS styles you must download the script.

Download the script free here.

Use the demo here.

Multiple File Upload with HTML5

A new feature of HTML 5 is the ability to use a multiple file upload field. This is extremely simple with HTML 5. You basically create an input tag with type = file and the multiple attribute applied.

Here is an example:

<form action="upload.php" method="post" enctype="multipart/form-data">
Upload Files: <input type="file" name="upload_files[]" multiple="multiple" />
<input type="submit" value="Submit" name="submit" />
</form>

This will create the following:

This may look like a regular file upload input from standard HTML however when you click the “Browse…” button to look for files on your computer, you can select multiple files by Shift+Clicking on the desired files grouped together, or alternatively Ctrl+Clicking to select individual scattered files. This only works for files coming from your computer of course, so to upload multiple files from URL, you will need a script like the one above.

Here is a screenshot of the browse window. You can select multiple files as you can see they are highlighted, and listed in order in the “File name:” input.

Browse for multiple files using HTML 5
Browse for multiple files using HTML 5

For this multiple file upload, the PHP is much simpler. We simply run the upload like we would for the first example, only we don’t have to worry about URL files or checking an array of files. The HTML already loads the files into an array for us when PHP checks the $_FILES[‘upload_files’].

Here is how it looks…

<?php
// upload multiple files from HTML5 multiple files input

if(isset($_POST['submit']))
{
$valid_exts = array("image/gif","image/jpeg","image/png","image/jpg"); // image files
$max_size = 20480; // max size in kb (2kb default)
$directory = "./files/"; // upload directory

$upload_files = $_FILES['upload_files'];
$files_uploaded = array(); // successful uploads

if(is_array($upload_files))
{

foreach($upload_files as $file)
{

if(in_array($file["type"],$valid_exts))
{

if($file["size"] <= $max_size)
{

// file is valid type and size, let's upload
if(move_uploaded_file($file["tmp_name"],$directory . $file["name"]))
{

$files_uploaded[] = '<a href="'.$directory.$file["name"].'" target="_blank">'.$file["name"].'</a>';

}

} else { return "File size too large. Max file size is: ". ($max_size / 1024) . " KB."; }

} else { return "Only image file types may be uploaded."; }

}

return "". count($files_uploaded) ." files out of ". count($upload_files) ." total have successfully been uploaded. Here are the uploaded files: <br/><br/>" . print_r($files_uploaded) . "";

} else { return "Please a file or multiple files to upload."; }

}
?>

Enjoy!

Filed under: CSS, Featured, Javascript, PHP, Scripts, Web ProgrammingTagged with: , , , , , , , , , , , , ,

Javascript & PHP Star Rating Script

I’ve searched around the interwebs for an ajax star rater and I came across a few different possibilities, all of which looked very good. The top result from google was Nick Stakenburg’s “Starbox” for “ajax star rater”. I also found Masuga Web Design’s Ajax Star Rater and a script from MySandbox to be popular results. However I couldn’t really seem to find a PHP / Mysql script that used Javascript for the rater effects. So I decided to make one based off of a script I found:

Reign Water Design’s 5 Star Rating System

This was a very nice easy to use Javascript 5 star rating script. All I had to do was make some tweaks to my preference and add on some PHP/Mysql code to submit the rating.

See the demo or download this script.

To view the PHP source code, images, and everything together you must download this script.

Javascript

Insert the following in the <head> tags of your page:
[codesyntax lang=”html4strict” title=”Javascript Source Code”]
<script type=”text/javascript”>
function insertParam(key, value)
{
key = escape(key); value = escape(value);

var kvp = document.location.search.substr(1).split(“&”);

var i=kvp.length; var x; while(i–)
{
x = kvp[i].split(“=”);

if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join(“=”);
break;
}
}

if(i<0) {kvp[kvp.length] = [key,value].join(“=”);}

//this will reload the page, it’s likely better to store this until finished
document.location.search = kvp.join(“&”);
}
function alterDisplay(id){
var dropdown = document.getElementById(id);
if(dropdown.style.display == “none”){
dropdown.style.display = “”;
} else {
dropdown.style.display = “none”;
}
}
</script>
<script type=”text/javascript” language=”javascript” src=”./scripts/ratingsys.js”></script>
[/codesyntax]

CSS

You will need to include this in the <head> tags as well either in <style> tags or by <link>:
[codesyntax lang=”css” title=”CSS Styles”]
#rateMe #rate_overlay {
position:absolute;
display:block;
float:left;
margin:0;
padding:0;
height:30px;
width:auto;
background:#eee url(./images/star_overlay.gif) repeat-x;
z-index:2;
cursor:default;
}
#rateStatus{width:100px; height:20px;margin:4px 0 0 5px;font: 12px “Trebuchet MS”, Arial, Helvetica, sans-serif; font-weight: bold}
#rateMe{width:152px; height:50px; padding:1px; margin:0px; vertical-align:top; z-index:auto; border: 1px solid #ccc; }
#rateMe li{float:left;list-style:none;}
#rateMe li a:hover,
#rateMe .on{background:url(./images/star_on.gif) no-repeat;}
#rateMe a{float:left;background:url(./images/star_off.gif) no-repeat;width:30px; height:30px;cursor:pointer;}
#rateMe a:hover{background:url(./images/star_on.gif) no-repeat;}
#rateMe a.grey,#rateMe a.grey:hover{background:url(./images/star_off.gif) no-repeat; cursor:default;}
#rateVotes{display:block; margin-left:65px; font: 11px “Trebuchet MS”, Arial, Helvetica, sans-serif; color:#4a4a4a;}
#ratingSaved{display:none;}
.saved{color:red; }
.grey

.rate_on_button {

}
.rate_on_button a { float:left;padding:10px;margin:0 5px;border:2px solid #666; background-color:#fff; color: #000; font-size: 2em; text-align:center; display:block; color: #000; text-decoration: none; }
.rate_on_button a:hover { color: #fff; text-decoration: none; background-color: #333; }
[/codesyntax]

Basically I took the script that Water’s made and changed a few things to the css styles, added an overlay for the current rating, and wrote a php script to insert rates and determine the current rating, etc. I also added the Javascript functions insertParam() and alterDisplay(). You do not need to use this function insertParam() to create the url, you can simply set the <a> tags to something like this:

[codesyntax lang=”html4strict”]
<a href=”./index.php?r=1″ id=”_1″ title=”Terrible” onmouseover=”rating(this)” onmouseout=”off(this)”></a>
[/codesyntax]

The Javascript function alterDisplay() is used to hide and show the overlay <div> that holds the current rating (if there is one). So when you mouse over the rating bar holder it hides the overlay so you can rate.

The PHP script grabs the information from the Mysql table that you specify in the function. You will need to adjust the following values:

  • $var – The column to base your mysql selection off of. Grab all rows where this column equals $id.
  • $table – The table where the ratings are being held.
  • $star_width – Width of the stars, default is 30px.

You will need to be connected to a MYSQL database before calling the rating bar function.

Since the syntax of the function is the following:

[codesyntax lang=”php” title=”Rating Bar Syntax”]
function rating_bar($id);
[/codesyntax]

You will need to supply the identifier ($id) which tells the PHP script which row to grab from the Mysql table.

To display the current rating after it has been rated on – because Javascript alone is not enough – I added an overlay <div> which will hold the current rating. This is done by setting the css style of this overlay div to the following:

[codesyntax lang=”css” title=”Rate Overlay CSS Style”]
#rateMe #rate_overlay {
position:absolute;
display:block;
float:left;
margin:0;
padding:0;
height:30px;
width:auto;
background:#eee url(./images/star_overlay.gif) repeat-x;
z-index:2;
cursor:default;
}
[/codesyntax]

The position: aboslute and z-index: 2 style attributes make the div lay over top of the rateMe div which holds the rater and has a z-index: 1.

Test out this free script with the demo link at the top of the post or download it and use on your own website. Credit where due is always appreciated.

Any questions or problems please feel free to email me at brian@bgallz.org or post here.

Filed under: Featured, Javascript, PHP, Scripts, TutorialsTagged with: , , , , , , ,

PHP Prime Number Script

Here is a simple little script that will determine if a number is prime or not. Just submit the function through with the parameter number as the integer you want to determine – is prime or not.

Syntax

[code lang=”php”]
is_prime(number);
[/code]

Here is the function’s definition:

[code lang=”php”]
function is_prime($num=0)
{

$num = (int)$num; // Make sure it’s an integer.
if($num > 0)
{
$count = 0;
$half = round($num / 2);

for($i=2;$i<=$half;$i++) // Check the remainder from 2 to the half point. { if(($num % $i) == 0) // Remainder is 0, it is divisible. Not a prime number. { $count++; // Increase count of divisible numbers. } } if($count > 0)
{
return false;
} else {
return true;
}
} else {

return false;

}

}
[/code]

Examples:

[code]
is_prime(10);
is_prime(3);
is_prime(109);
[/code]

[code]
false
true
true
[/code]

Basically our script here takes a parameter, makes sure it is an integer greater  than 0, then divides it by each number from 2 to half way to that number. So if our number was 7 the script would divide 7 by 2, 3, 4. The half mark is rounded to the nearest whole number. Since a remainder exists from each of these divisions, the number is declared as prime.

Click here to demo the script!

Click here to download this script!

Filed under: ScriptsTagged with: , , ,

PHP Upload and Resize Image

Many times when you upload a image somewhere you want to resize it to different dimensions based off of a maximum width or height. Here is a simple script that does this for you, using a HTML form and a PHP script. We start with the PHP script that will run if our $_GET[‘do’] is set to “upload.” Then we include the HTML form that has three inputs (max width, max height, image file).

Use the Upload and Resize Demo Here!

Download This Script!

Here is the PHP for our function – generate_resized_image() – which will take the given image file, create a new file on our server, and then copy the uploaded image to our local image file with the new width and height:

[codesyntax lang=”php” title=”Upload and Resize PHP Code”]
<?php

// index.php

function generate_resized_image(){

$max_dimension = 800; // Max new width or height, can not exceed this value.
$dir = “./images/”; // Directory to save resized image. (Include a trailing slash – /)

// Collect the post variables.
$postvars = array(
“image”    => trim($_FILES[“image”][“name”]),
“image_tmp”    => $_FILES[“image”][“tmp_name”],
“image_size”    => (int)$_FILES[“image”][“size”],
“image_max_width”    => (int)$_POST[“image_max_width”],
“image_max_height”   => (int)$_POST[“image_max_height”]
);

// Array of valid extensions.
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”);

// Select the extension from the file.
$ext = end(explode(“.”,strtolower(trim($_FILES[“image”][“name”]))));

// Check not larger than 175kb.
if($postvars[“image_size”] <= 179200){

// Check is valid extension.
if(in_array($ext,$valid_exts)){

if($ext == “jpg” || $ext == “jpeg”){
$image = imagecreatefromjpeg($postvars[“image_tmp”]);
}
else if($ext == “gif”){
$image = imagecreatefromgif($postvars[“image_tmp”]);
}
else if($ext == “png”){
$image = imagecreatefrompng($postvars[“image_tmp”]);
}
// Grab the width and height of the image.
list($width,$height) = getimagesize($postvars[“image_tmp”]);

// If the max width input is greater than max height we base the new image off of that, otherwise we
// use the max height input.
// We get the other dimension by multiplying the quotient of the new width or height divided by
// the old width or height.

if($postvars[“image_max_width”] > $postvars[“image_max_height”]){

if($postvars[“image_max_width”] > $max_dimension){
$newwidth = $max_dimension;
} else {
$newwidth = $postvars[“image_max_width”];
}
$newheight = ($newwidth / $width) * $height;

} else {

if($postvars[“image_max_height”] > $max_dimension){
$newheight = $max_dimension;
} else {
$newheight = $postvars[“image_max_height”];
}
$newwidth = ($newheight / $height) * $width;
}

// Create temporary image file.
$tmp = imagecreatetruecolor($newwidth,$newheight);

// Copy the image to one with the new width and height.
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);

// Create random 4 digit number for filename.
$rand = rand(1000,9999);
$filename = $dir.$rand.$postvars[“image”];
// Create image file with 100% quality.
imagejpeg($tmp,$filename,100);
return “<strong>Image Preview:</strong><br/>
<img src=\””.$filename.”\” border=\”0\” title=\”Resized  Image Preview\” style=\”padding: 4px 0px 4px 0px;background-color:#e0e0e0\” /><br/>
Resized image successfully generated. <a href=\””.$filename.”\” target=\”_blank\” name=\”Download your resized image now!\”>Click here to download your image.</a>”;

imagedestroy($image);
imagedestroy($tmp);
} else {
return “File size too large. Max allowed file size is 175kb.”;
}
} else {
return “Invalid file type. You must upload an image file. (jpg, jpeg, gif, png).”;
}
}

?>
[/codesyntax]

This function you can define in your header PHP files along with other functions or where ever you would like, so long as it is defined before the call of the function itself.

Here is the HTML for our form to submit the image file and the new dimensions:

[codesyntax lang=”html4strict” title=”HTML Form”]
<form action=”./index.php?do=upload” method=”post” enctype=”multipart/form-data”>
<table width=”100%” align=”center” border=”0″ cellpadding=”2″ cellspacing=”0″>
<tr>
<td align=”left” width=”100″>
New Width:</td>
<td align=”left”><input name=”image_max_width” style=”width: 120px” type=”text” maxlength=”4″ /> px.</td>
</tr>
<tr><td colspan=”2″><strong>OR</strong></td></tr>
<tr>
<td align=”left”>
New Height:</td>
<td align=”left”><input type=”text” name=”image_max_height” style=”width: 120px” maxlength=”4″ /> px.</td>
</tr>
<tr>
<td align=”left”>
Image:</td>

<td align=”left”><input type=”file” name=”image” size=”40″ /></td></tr>
<tr>
<td align=”left” colspan=”2″>
<ol style=”margin:0;padding:3px 0px 3px 15px”>
<li>Max file size: 175 KB.</li>
<li>Allowed extensions: jpg, jpeg, gif, png.</li>
<li>Max Dimension: <em>800</em>px.</li>
</ol>
</tr>
<tr>
<td align=”left” colspan=”2″>
<input type=”submit” name=”submit” value=”Submit!” style=”font: 10pt verdana” />
</td>
</tr>
</table>
</form>
[/codesyntax]

This will create a form that looks like this:

Max Width: px.
Max Height: px.
Image:
  1. Max file size: 175 KB
  2. Allowed extensions: jpg, jpeg, gif, png.
  3. Max Dimension: 800px.

 

Okay, so now we have our PHP function defined, included and our HTML contains this form submitting the image file and its new dimensions. All we need now is a short code of PHP to check our GET values, particularly do for the value upload. This tells us the form was submitted and we can start checking it for values, and creating our re-sized image.

Here is the PHP which will appear below the HTML form to show our re-sized image once the form is submitted:

<?php

if(isset($_GET['do']) && $_GET['do'] == "upload")
{

$upload_and_resize = generate_resized_image();
echo '<div id="upload">'. $upload_and_resize. '</div>';

}

?>

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

PHP Favicon Generator Script

I decided to make a free easy to use favicon generating script that uses PHP. The script has a few features and requirements when uploading your image to be converted to a favicon. First the script checks for a few things such as file type, file size, if the directory is writable, and the specified dimensions. You can create a 16×16 icon or a 32×32 icon.

This PHP Favicon Generator Script first checks the form submitted for the following:

  • Valid file size. (Default: Max 75kb)
  • Valid file types. (Valid extensions are defaulted to image files)
  • Writable directory for favicons.

Then, once verifying these variables, we create a temporary image file on our server with the new dimensions gathered from the form (16×16 or 32×32). We then copy the uploaded image file’s contents over to the temporary file, while resizing it. Once the temporary image file has the new width, height, and copied graphical output, we can transfer this temporary data to a file on our server. Finally, we rename this image file to have a favicon file extension (.ico). Wallah!

Click here to check out the demo for this script!

Just select the image file you want converted to a 16×16 or 32×32 icon and hit submit! It’s that easy.

Here’s the PHP function we want to include in our header, prior to loading the HTML:

[codesyntax lang=”php” title=”Favicon Generator Script”]
<?php
// bgallz.org – Web coding and design tutorials, scripts, resources and more.
// favicon Generator Script
function generate_favicon(){
// Create favicon.
$postvars = array(“image” => trim($_FILES[“image”][“name”]),
“image_tmp”        => $_FILES[“image”][“tmp_name”],
“image_size”    => (int)$_FILES[“image”][“size”],
“image_dimensions”    => (int)$_POST[“image_dimensions”]);
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”);
$ext = end(explode(“.”,strtolower(trim($_FILES[“image”][“name”]))));
$directory = “./favicon/”; // Directory to save favicons. Include trailing slash.
$rand = rand(1000,9999);
$filename = $rand.$postvars[“image”];

// Check not larger than 175kb.
if($postvars[“image_size”] <= 179200){
// Check is valid extension.
if(in_array($ext,$valid_exts)){
if($ext == “jpg” || $ext == “jpeg”){
$image = imagecreatefromjpeg($postvars[“image_tmp”]);
}
else if($ext == “gif”){
$image = imagecreatefromgif($postvars[“image_tmp”]);
}
else if($ext == “png”){
$image = imagecreatefrompng($postvars[“image_tmp”]);
}
if($image){
list($width,$height) = getimagesize($postvars[“image_tmp”]);
$newwidth = $postvars[“image_dimensions”];
$newheight = $postvars[“image_dimensions”];
$tmp = imagecreatetruecolor($newwidth,$newheight);

// Copy the image to one with the new width and height.
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);

// Create image file with 100% quality.
if(is_dir($directory)){
if(is_writable($directory)){
imagejpeg($tmp,$directory.$filename,100) or die(‘Could not make image file’);
if(file_exists($directory.$filename)){
// Image created, now rename it to its
$ext_pos = strpos($rand.$postvars[“image”],”.” . $ext);
$strip_ext = substr($rand.$postvars[“image”],0,$ext_pos);
// Rename image to .ico file
rename($directory.$filename,$directory.$strip_ext.”.ico”);
return ‘<strong>Icon Preview:</strong><br/>
<img src=”‘.$directory.$strip_ext.’.ico” border=”0″ title=”Favicon  Image Preview” style=”padding: 4px 0px 4px 0px;background-color:#e0e0e0″ /><br/>
Favicon successfully generated. <a href=”‘.$directory.$strip_ext.’.ico” target=”_blank” name=”Download favicon.ico now!”>Click here to download your favicon.</a>’;
} else {
“File was not created.”;
}
} else {
return ‘The directory: “‘.$directory.'” is not writable.’;
}
} else {
return ‘The directory: “‘.$directory.'” is not valid.’;
}

imagedestroy($image);
imagedestroy($tmp);
} else {
return “Could not create image file.”;
}
} else {
return “File size too large. Max allowed file size is 175kb.”;
}
} else {
return “Invalid file type. You must upload an image file. (jpg, jpeg, gif, png).”;
}
}
?>
[/codesyntax]

Then we must include the HTML form that will submit the image and dimensions to PHP:

[codesyntax lang=”html4strict” title=”HTML Form”]
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>PHP Favicon Generator Script from bgallz.org</title>
</head>

<body>
<h2>Create Your Favicon</h2>
<form action=”index.php?do=create”  enctype=”multipart/form-data” method=”post”>Image Dimensions:<br />
<select style=”width: 170px;” name=”image_dimensions”>
<option selected=”selected” value=”16″>16px x 16px</option>
<option value=”32″>32px x 32px</option>
</select>
<p><span style=”font-size: 14pt;”>Favicon Image:</span></p>
<input name=”image” size=”40″ type=”file” />
<input style=”font: 14pt verdana;” name=”submit” type=”submit” value=”Submit!” />
</form>
<p><a href=”https://bgallz.dev/488/php-favicon-generator-script/” target=”_blank”>PHP Favicon Generator Script</a> from <strong>bgallz.org</strong></p>
[/codesyntax]

So we have the function included in our header, and the form is presented by the code above. Now we just need to call the function when our GET value for “do” is set to “create” – which the form does for us.

Here is the PHP to include after the HTML form:

[codesyntax lang=”php” title=”After Form PHP”]
<?php
if(isset($_GET[“do”])){
if($_GET[“do”] == “create”){
if(isset($_POST[“submit”])){

// Call the generate favicon function and echo its returned value
$gen_favicon = generate_favicon();
echo $gen_favicon;
echo “Place your download instructions and anything else you want here to follow the download link after upload.”;

}
}
}
?>
[/codesyntax]

 

Also be sure to follow this PHP with the closing tags for HTML:

[code lang=”html4strict”]
</body>
</html>
[/code]

Be sure to include the HTML head tags in your HTML pages that use the favicon. These are given on the script’s index and on the demo.

This header HTML looks like this:

<link rel="shortcut icon" type="image/x-icon" href="./favicon.ico">

 

How to Force Download for .ico Files

Open a new text document in notepad. Paste the following code within the document:

[code lang=”htaccess”]
<FilesMatch “\.(?i:ico|gif|png|jpg|jpeg)$”>
Header set Content-Disposition attachment
</FilesMatch>
[/code]

Now save this file as “.htaccess” exactly like that. Place this file in the directory you are saving your .ico files to for download. This will force the access of these files (ico, png, gif, jpeg) to be a download only type.

Thanks for reading!

Click here to download the script!

Filed under: PHP, Scripts, 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: , ,

Simple File Hosting Script

I’ve made an easy to use file hosting script that is free for download.

It has some nice features such as:

  • Allowed file extensions.
  • File size limit.
  • Generated file names.
  • BBcode, IMG code, Url, etc.
  • Terms of Conditions

Generated file names on the server are created using the functions rand() and the md5() hash generator. Here is the code:

[code lang=”php”]

[/code]

The script also uses javascript to check for the Terms and Conditions checkbox being checked to make the submit button enabled.

I will be updating this script with more features, but this is meant to be a simple file hosting script. I will later include a download file page.

Here is what the upload form looks like:

filehostingscript

Check out the demo here!

Click here to download the script!

Filed under: ScriptsTagged 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: , , , , ,