wrap text in php

php-sniplets 1 Comment »

How to force text to wrap after a certain number of characters

A function that almost developers find really convenient is word-wrap. If you’ve a long string of text that carries
no specific formatting, you will be able to use word-wrap to insert a character, specified newline character (\n),
at a defined interval. word-wrap attends not to separate words unless you specific say it to. This function may
be specially valuable once it touches on building well-laid-out e-mail messages.

To utilize word-wrap, we barely pass it a string. word-wrap’s default behaviour is to enclose the text as just
about 75 characters as conceivable (it will not break words), entering a newline character (\n) at all breakpoint.

In this case, we mean to output HTML, so we provide 2 additional arguments to modify this default behaviour:

<?php $string = “Here is a long sentence that will be abbreviate at seventy
. characters automatically. Do not care,
. no words will follow broken up.”; echo wordwrap($string, 70, “<br />”); ?>

On this call, word-wrap encloses the text at 70 characters, and insets <br /> tags rather than new line
characters. Hera what it turnouts:

This is a long sentence that will be cut at seventy characters<br />
automatically. Do not care, none word will follow broken up.

Therefore, we have wrangled this clumsy sentence into something long more controllable without breaking
some of the words.

simple mail form in php

php-sniplets 1 Comment »

Form to mail

A very simple form mail PHP script that shows a contact form to provide visitors to your web site to send you a message via e-mail. Built in security keeps spammers hijacking it from additional URL.

<?php

/**

* Change the e-mail address to your own.
*
* $empty_fields and $thankyou_messages can be modified
* if you like.
*/

// Modify to your own e-mail address

$your_email = “your@sitenasme.com”;

// This is what is showed in the e-mail subject line

// Modify it if you wish

$subject = “Message thru your contact form”;

// This is showed if all the fields are not fulfilled in

$empty_fields_message = “<p>Opps… get back and fill in all the form.</p>”;

// This is showed when the e-mail was sent

$thankyou_message = “<p>Thank’s  ! Your e-mail has been sent.</p>”;

// You don’t need to edit the code anymore.Thats it :) !!

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

$email = stripslashes($_POST['txtemail']);

$message = stripslashes($_POST['txt.Message']);

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

?>

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

<p><label for=”txtName”>Name:</label><br />

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

<p><label for=”txtEmail”>e-mail:</label><br />

<input type=”text” title=”Put your e-mail address here” name=”txtEmail” /></p>

<p><label for=”txt.Message”>Put the message here:</label><br />

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

<p><label title=”Send “>

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

</form>

<?php
}

elseif (empty($name) || empty($e-mail) || empty($messag)) {

echo $empty_fields_message;

}

else {

// Stop the form being exploited from an outside domain

// Get the referring URL

$referer = $_SERVER['HTTP_REFERER'];

// Get the domain name of this page

$this_url = “https://”.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];

// When the referring domain and the URL of this page do not check then

// Show a message and do not send the e-mail.

if ($referer != $this_url) {

echo ” You don’t have license to utilize this script from a different domain.”;

exit;

}

// The URLs checked then send the e-mail

mail($your_email, $subject, $message, “From: $name <$email>”);

// Show the thank you message

echo $thankyou_message;

}

?>

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.

Sample

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”>

<?php
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>
“;
} ?>

</select>

*************************************

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”>

<?php
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>
“; } ?>

</select>

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
******************
*************

<?php
/* 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);
fclose($fp);
$fp = fopen($stored,w);
$stuff += 1;
print “$stuff”;
fput($fp, $stuff);
fclose($fp);
}

/* Now, just show it on your site somewhere
with the script below */
?>
Page hit: <?php displayHitThing($stored); ?>
<?php
/* 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 1 Comment »

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
******************
<?php

/**

* 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>

<?php
}

?>

<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>

</form>

<?php

}

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

$ref = $_SERVER['HTTP_REFERER'];

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.
*
* @ARGUMENTS: 2
*                         – $image: This is the path to the image to be resized
*                         – $target: This is the target width/height
* @RETURNS:
*                            – 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];
}
else
{
$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.

<?php
/**
* 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);
?>

php Random Password Generator

php-sniplets No Comments »

Random Password Generator (based on word list)

This is a random password generator that creates understandable passwords supported word lists. I have just
enclosed a three entry world list since you had better selected a list based on your password requisites and your
users. Whenever you want to get passwords that are fourteen characters long, you’ll require different list than
if you are getting in eight character passwords. And dependant on your users, you may prefer to apply certain
lists. The list I use is almost 4000 words that are 5-7 characters long, all known words that have accepted
potentially offensive content removed. For security grounds I do not want to let in this list.

A mention on security: although this returns relatively solid passwords for the ordinary user, they’re particularly
subject to brute-force attempts. This is even more a matter if someway your word list finds compromised. I’d
not recommend applying this function for anything where an extremely secure password is required.

A mention on selecting your list: you will as well see that I have improved the system to avoid returning
passwords with zeros and ones in them. This is because zero and capital “o” can be mixed-up equally can one,
lowercase “L” and uppercase “i.” When selecting my word list I was as well certain to clean away all words that
begin on the letter “i” or “o” (to keep the optional ucfirst() from making 0 / O and 1 / I mix-up) and words that
carry the letter “L” (to keep l/1 mix-up). I feel that this greatly helps on preventing mix-up, but once more
breaks the protection of the passwords a few. It is your option.

<?php
function generatePassword($maxLen = 8)
{
$words = array(’alaska’, ‘aline’, ‘alone’,); // Use your personal list here!!!

while (strlen($word) > $maxLen || !$word) $word = $words[array_rand($words, 1)];
if (rand(0,1)) $word = ucfirst($word);
for ($i = 0; $i < $maxLen – strlen($word); $i++) rand(0,1) ? $opener .= rand(2,9) : $closer .=
rand(2,9);

return “{$opener}{$word}{$closer}”;
}
?>

for ($i = 0; $i < 20; $i++)
{
echo generatePassword() . ” “;
}

****************************************************

Produces: 6Aline43 79Aline7 aline4 2Aline85 58alaska5 59Aline3 4aline Aline3 6alaska44 3Alone Aline587 Aline994
8Aline56 Aline259 699aline 4Aline88 alone3 alone3 Alaska322 267Alaska

use of php mail function

php-sniplets 2 Comments »

PHP supplies a function named mail that sends email from your script.

The format is as follows: mail(headers,address,message,subject);

These are the values you need to fill in:

address: The e-mail address that receives the message
subject: A string that goes on the subject line of the e-mail message
message: The content that comes in the e-mail message
headers: A string that sets values for e-mail headers

You may set and send an email message as follows:

$to = “yourname@sitename.com”;
$subj = “Testing”;
$mess = “Testing the mail function”;
$headers = bcc:help@sitename.com\r\n
$mailsend = mail($to,$subj,$mess,$headers);

The message is sent to the address in the $to variable.

You are able to send the message to more than one individual by using the following argument:

$to= “yourname@sitename.com,secondname@secondsite.com”;

The $headers string in this case as well sends a blind copy of the message to support@sitename.com. You will
be able to let in more than one header as follows:

$header = “cc:info@sitename.com\r\nbcc:sales@sitename.com”;

Headers are optional. Just the first 3 parameters are needed.

The $mailsend variable holds TRUE or FALSE. However, TRUE is no guarantee that the mail will get to wherever
it is going. It just implies that it started out O.K..

Entries RSS Comments RSS Log in