Handling Files in php

php-sniplets No Comments »

Handling Files

To apply the file functions, you just need to point them at the file they’ve to read, applying a path that is relative to the PHP script that runs the function. Even so, the absolute majority of PHP file functions use a somewhat another mechanism to get at a file–a mechanism that is really alike to that utilized to connect to a database. The process uses the fclose function to “disconnect and fopen function to “connect”. The value generated from the fopen function is a PHP file pointer, a.k.a. the handle of the file. When we get a handle on a file, we can apply it to execute an assortment of functionings on the file, admitting modifying it, reading to it, append it, etcetera.


This mere example shows how to close and open that “association” to the file:

<?php $location = ‘writeFileHandling.htm’; $fp = fopen($location, ‘rb’);  the file handle $fp is now usable fclose($fp); echo $file; ?>

Once you apply fopen to associate to a file, you must assign the route to the file and a manner in which the file is to be got at (specified r as read only). The b mode indicator shows that the file is to follow open in binary mode. The binary mode had better ever be assigned to ensure the movability of your code ‘tween OSs. For further information about the several modes that are accessible, read the manual here -> http://www.php.net/fopen/

dropdown month and year in php

php-sniplets No Comments »

Generate a dropdown with days of the month and a dropdown with months in a year

The below code will generate a form drop-down for all the days of the month, with today’s day selected.
Convenient for those date selectors!

<select name=”start_day”>

global $LOC;

$current_time_day = $LOC->decode_date(‘%d’, $LOC->now);

for ($i = 1; $i <= 31; $i++) {
echo “<option value=’$i’”;

if ($i == $current_time_day) { echo ” selected=’selected’”; }

echo “>$i</option>
} ?>



And here the code for the dropdown with months in a year

The below code will generate a dropdown for all twelve months, with the actual month selected. Convenient for
those date choosers!


<select name=”start_month”>

global $LOC;

$current_time_m = $LOC->decode_date(‘%m’, $LOC->now);

for ($i = 1; $i <= 12; $i++) {
echo “<option value=’$i-’”;

if ($i == $current_time_m) { echo ” selected=’selected’”; }

$month_text = date(“F”, mktime(0, 0, 0, $i+1, 0, 0, 0));
echo “>$month_text</option>
“; } ?>


Simple Hit counter in php

php-sniplets No Comments »

Just a very simple hit counter for your site to stores the hits in a mere document of your preferring. No involve
for a any database, MySQL or other. No elaborated scrap. Only one simple function and only one file to store
the hits count. Thats it.

Simple Hit counter php Code

/* first you’ll need to make a text file someplace and give it
evidently,a name . In this example I’ll name it hit.txt */
$stored = “hit.txt”;

/* The above function once called becomes the text file
pointed in the variable ‘$stored’, then open for
reading/writing, save the contents in variable $stuff
close, and so open once again, adds 1 to $stuff,
display the variable $stuff and so save and close the file once more. */

function displayHitThing($stored) {
$fp = fopen($stored,rw);
$stuff = fget($fp,99999);
$fp = fopen($stored,w);
$stuff += 1;
print “$stuff”;
fput($fp, $stuff);

/* Now, just show it on your site somewhere
with the script below */
Page hit: <?php displayHitThing($stored); ?>
/* Thats all. You will be able to naturally utilize it on more than just one
page, only think back to modify the documents name for all
For example. page01.txt page02.txt etc… */

Simple Hit counter php Code end

Please note !!!

This script needs PHP enable on your host to work.

When you get PHP enabled, just copy/paste this same script into the page where you need it.
You so get to name the script to become a .php extension alternatively of a html or htm
Keep in mind that any additional link to this page from your site will require to be modified to reflect the change.

simple guestbook in php

php-sniplets No Comments »

Simple guestbook

Lets visitors to your web site to read your guestbook entries and send a message of their own. Really simple
setup, just needs you to modify 4 settings. Utilizes MySQL to store the entries.

Code starts here


* Create the table in your MySQL database:
* CREATE TABLE guest (
*   id int(10) NOT NULL auto_increment,
*   name varchar(50) NOT NULL,
*   message varchar(255) NOT NULL,
*   date timestamp(14) NOT NULL,
*   PRIMARY KEY (id)
* )
* Change the database settings to your personal settings
* The script is now ready to go !!


// Change here to your personal database settings

$host = “yourlocalhost”;
$user = “yourusername”;
$pass = “yourpassword”;
$db = “yourdatabase”;

mysql_connect($host, $user, $pass) OR die (“Could not connect to the server.”);

mysql_select_db($db) OR die(“Could not connect to the database.”);

$name = stripslashes($_POST['txtYName']);

$message = stripslashes($_POST['txtYMessage']);

if (!isset($_POST['txtName'])) {

$query = “SELECT id, name, message, DATE_FORMAT(date, ‘%D %M, %Y @ %H:%i’) as newdate
FROM guests ORDER BY id DESC”;

$result = mysql_query($query);

while ($row = mysql_fetch_object($result)) {


<p><strong><?php echo $row->message; ?></strong>

<br />Posted of <?php echo $row->name; ?> on <?php echo $row->newdate; ?></p>



<p>Post your message</p>

<form method=”post” action=”<?php echo $_SERVER['REQUEST_URI']; ?>”>

<p><label for=”txtYName”>Your Name Here:</label><br />

<input type=”text” title=”Put your name here” name=”txtName” /></p>

<p><label for=”txtYMessage”>Put Your messageHere:</label><br />

<textarea title=”Enter your message” name=”txtMessage”></textarea></p>

<p><label title=”Send your message”>

<input type=”submit” value=”Send” /></label></p>




else {

// Adds the new entry to the database

$query = “INSERT INTO guest SET message=’$messag’, name=’$names’, date=NOW()”;

$result = mysql_query($query) or die(mysql_error());

// Take back to the entries


header (“Location: $ref”);


Image Resize script php

php-sniplets No Comments »

Image Resize

You will be able to use this function to generate html “width/height” for use with showing a thumbnail image
using the original image. This will help save in making duplicate images merely for display as a thumbnail.

It takes only two arguments, the path to where the image is stored and the wanted width or height.

/** resize_image()
* This functions resizes an image to any size
* defined.
*                         – $image: This is the path to the image to be resized
*                         – $target: This is the target width/height
*                            – htm width/height string for an image tag
function resize_image($image,$target)
// Get the actual image size
$image = getimagesize($image);

// Get the percent to size the image
if ($image[0] > $image[1])
$percent = $target / $image[0];
$percent = $target / $image[1];

// Get the new sizet
$w = round($image[0] * $percent);
$h = round($image[1] * $percent);

// Generate as an htm widht/height property
$htmWH = “width=\”" . $w . “\” height=\”" . $h . “\”";
return $htmWH;

This way won’t decrease download time if you’re resizing a huge image. This is just telling the web browser to
show the image at a certain size when the image is downloaded.

php Password generator script

php-sniplets No Comments »

Really Simple Password generator

This function produces comparatively secure random passwords. It is by no intends ideal, just it ought play
innermost noncrucial situations. The good matter is the generator efforts to make passwords that anyone can
suppose and selects letters that will not be incorrect for other people (specified the number “1″, an capital letter
“i” and a little “L”). To maintain the code short some of this practicality is really basic, but it is better than naught.

* Renders somewhat more human-intelligible random passwords
* @param int $len
* @return string
function makePassword($len = 8)
$vowel = array(‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘y’);
$confusing = array(‘I’, ‘l’, ’1′, ‘O’, ’0′);
$replacement = array(‘A’, ‘k’, ’3′, ‘U’, ’9′);
$choice = array(0 => rand(0, 1), 1 => rand(0, 1), 2 => rand(0, 2));
$part = array(0 => ”, 1 => ”, 2 => ”);

if ($choice[0]) $part[0] = rand(1, rand(9,99));
if ($choice[1]) $part[2] = rand(1, rand(9,99));

$len -= (strlen($part[0]) + strlen($parts[2]));
for ($i = 0; $i < $len; $i++)
if ($i % 2 == 0) $part[1] .= chr(rand(97, 122));
else $part[1] .= $vowel[array_rand($vowel)];
if ($choice[2]) $part[1] = ucfirst($part[1]);
if ($choice[2] == 2) $part[1] = strrev($part[1]);

$r = $part[0] . $part[1] . $part[2];
$r = str_replace($confusing, $replacements, $r);
return $r;

* Model:

echo makePassword(12);

Impressum Entries RSS Log in