FRIHOSTFORUMSFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a Frihost Account!

Sonam's Tips & Tricks

Created on Tue Sep 04, 2007 11:00 am with 5 blog posts
Some tips and tricks about web design, scripts, etc.

Simple contnent rotator in PHP with 2 comments on Sat Dec 29, 2007 4:58 pm
This simple content rotator will rotate your content independent of day in the week. You need to create one separate folder where you will insert all your files with content (in my script I am give to this folder name conts - second line, but you can change it). Then insert in this folder current.txt file, too. Write in current.txt file (it must have only one line) your first display (e.g. some.php ). Also, in line 5 you can define the day of change - 0 (for Sunday) through 6 (for Saturday).
Note:
Script will grab any type of files (subfolders and current.txt are excluded) what mean you can use txt, htm, html, php, asp or some other extension. You can put images in this files, too, but you cannot include images directly.

Good luck Very Happy

Here is script:

Code:
<?php
$dir = "partners"; // dir where are files
$date = date("w"); // looking for day in the week
$current = file($dir . "/current.txt"); // txt file where is writen datas
$changes = 3;  // 0 (for Sunday) through 6 (for Saturday)
$trigger = date("z"); // check the day in the year (0 through 365)


list($currentInc, $currentDay) = explode("|", $current['0']);

// read dir and create one array from files
if($date == $changes && $trigger != $currentDay) {
  $openDir  = opendir($dir);
    while (false !== ($fileNames = readdir($openDir))) {
    if($fileNames == "." || $fileNames == ".." || $fileNames == "current.txt") {
                   continue;
              } else {
                   $allfiles[] = $fileNames;
              }   
    }

// looking for position in array of current display
$key = array_search($currentInc, $allfiles);

if($key === FALSE) {
$newKey = 0;
} else {
$newKey = $key + 1;
}
$count = count($allfiles);

// count all files and define new one
if($newKey > $count-1) {
   $newCurrent = $allfiles['0'] . "|" . $trigger;
   $display = $allfiles['0'];
} else {
   $newCurrent = $allfiles[$newKey] . "|" . $trigger;
   $display = $allfiles[$newKey];
}

// write new one display in current.txt
$newData = fopen($dir . "/current.txt", "wb");
   fwrite($newData, $newCurrent);
   fclose($newData);   

// include right file
include_once($dir . "/" . $display);
exit;
} else {
// if is  not time for change include file from current.txt
include_once($dir . "/" . $currentInc);
}
?>
How to build PHP mail form with Spam protection in PHP with 1 comments on Tue Nov 13, 2007 8:28 pm
If you read my first post in PHP blog (How to build simple upload form) then you have idea how I will build this mail form. If you didn't read it then we can start from begining. First of all we need form (mailform.php) and second mail processor (mailsender.php). These two files will do all stuff for us, like (sending, checking, SPAM protect, etc.). For communications between this two files we will use sessions and post. Ok, we can start. First is mailform.php.
Code:
<?php
session_start();
?>

Then we can create Spam protection. I am using one simple system what is in correlation with session and what we can check latter in mailsender.php.
Code:
$id = session_id();
$_SESSION['check'] = session_id();
$id = str_split($id, 5);
foreach($id as $key => $numIn) {
$res = strlen($numIn);
if($res!=5) {
 unset($id[$key]);
}
}
shuffle($id);
$_SESSION['spam'] = $id['0'];

First line collect session id. Second one fill session array with one definition. Third one cut id string in small five letter strings. Now we have an array. Because we haven’t idea how many letters contain session id we must remove out all strings what have less then 5 letters. This is working for us next foreach loop.
Then shuffle this array and print out one 5 letters string for checking. After this I am fill one more definition in session array (last line) because I need this information in mailsender.php. Now we can create simple form with four fields named: subject, mail, content, spam and button "Send". We will come back on mailform.php when we create mailsender.php.

Mailsender.php process our collected data and send back to mailform.php information for user. First we need to define return path and search array. This array contains all names what will come from mailform.php with post function when user press button "Send".
Code:
<?php
session_start();
$id = session_id();
$return = "mailform.php";
$search = array("subject", "mail", "content", "spam", "sent");
?>

Script will start checking user inputs in different ways. First is it session on the mailform.php same with session in mailsender.php.
Code:
if($id != $_SESSION['check']) {
$_SESSION['message'] = 1;
header("Location:$return");
exit;
}

In next foreach loop we will check two conditions. First, is all post fields have right names, and second is it this fields empty?
Code:
foreach($_POST as $key => $val) {
if(array_search($key, $search) === FALSE) {
$_SESSION['message'] = 1;
header("Location:$return");
exit;
}
if($val == "") {
$_SESSION['message'] = 2;
header("Location:$return");
exit;
}
}

It is right time to check Spam input. I will do this in two ways; first I will check are $_SESSION['spam'] the same like input and second are input part of session id.
Code:
if($_POST['spam'] != $_SESSION['spam'] || strpos($id, $_POST['spam']) === FALSE) {
$_SESSION['message'] = 3;
header("Location:$return");
exit;
}

Like you can see any error will return user to mailform.php. After this few form and session checking we must check one very important think: e-mail! I am here using eregi function.
Code:
if(!eregi("^[a-z0-9._-]+@+[a-z0-9._-]+\.+[a-z]+$", $_POST['mail'])) {
$_SESSION['message'] = 4;
header("Location:$return");
exit;
}

Okay, now we are very near to the end of mailsender.php. But I am including here one more check.
Next check will check are button have right value (in our case "Send"). How you can see I don’t want to write the same definition for button name and value. Maybe this check is not necessary but gives me nice entrance for mail sending what is embed in else statement and in that case little bit more protected. If user passes this last check our script will start with sending mail but before sending we can clean subject and content inputs with htmlspecialchars and trim functions. On the end define your mail ($to) where you want to receive mails from your site.
Code:
$reply = $_POST['mail'];
$subject = htmlspecialchars($_POST['subject']);
$subject = trim($subject);
$content = htmlspecialchars($_POST['content']);
$content = trim($content);
$to = "some_mail@right_domain.com";
mail($to, $subject, $content, "From: $reply\r\n"."Reply-To: $reply\r\n");
$_SESSION['message'] = 5;
header("Location:$return");
exit;
}

When mail was sent script would return user on mailform.php. And we can go back to mailform.php and define messages for user. For messages we will use switch/case function.
Code:
//messages part
switch(@$_SESSION['message']) {
case "1": $message = "Sorry, some error occur! <br />"; break;
case "2": $message = "Please fill all fields. <br />"; break;
case "3": $message = "Your validation key is not correct. <br />"; break;
case "4": $message = "Your email address is not valid. <br />"; break;
case "5": $message = "Your e-mail has been sent successfully. <br />"; break;
default: "";
}
unset($_SESSION['message']);

Now you can see here full mailform.php:
Code:
<?php
session_start();

// prepare spam check
$id = session_id();
$_SESSION['check'] = session_id();
$id = str_split($id, 5);
foreach($id as $key => $numIn) {
$res = strlen($numIn);
if($res!=5) {
 unset($id[$key]);
}
}
shuffle($id);
$_SESSION['spam'] = $id['0'];

//messages part
switch(@$_SESSION['message']) {
case "1": $message = "Sorry, some error occur! <br />"; break;
case "2": $message = "Please fill all fields. <br />"; break;
case "3": $message = "Your validation key is not correct. <br />"; break;
case "4": $message = "Your email address is not valid. <br />"; break;
case "5": $message = "Your e-mail has been sent successfully. <br />"; break;
default: "";
}
unset($_SESSION['message']);
?>
<html>
<head>
<title>Mail Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<form name="form1" method="post" action="mailsender.php">
<?php
// display right message
echo @$message;
?>
Subject:<br />
<input type="text" name="subject">
<br /><br />
Your e-mail:<br />
<input type="text" name="mail">
<br /><br />Your message:<br />
<textarea name="content" rows="5"></textarea>
<br /><br />
Type:
<h2>
<?php echo $id['0']; ?>
<input type="text" name="spam" maxlength="5">
</h2>
<br />
<input type="submit" name="sent" value="Send">
</form>
</body>
</html>

And on THE END full script of mailsender.php:
Code:
<?php
session_start();
$id = session_id();
$return = "mailform.php";
$search = array("subject", "mail", "content", "spam", "sent");
if($id != $_SESSION['check']) {
$_SESSION['message'] = 1;
header("Location:$return");
exit;
}
foreach($_POST as $key => $val) {
if(array_search($key, $search) === FALSE) {
$_SESSION['message'] = 1;
header("Location:$return");
exit;
}
if($val == "") {
$_SESSION['message'] = 2;
header("Location:$return");
exit;
}
}
if($_POST['spam'] != $_SESSION['spam'] || strpos($id, $_POST['spam']) === FALSE) {
$_SESSION['message'] = 3;
header("Location:$return");
exit;
}
if(!eregi("^[a-z0-9._-]+@+[a-z0-9._-]+\.+[a-z]+$", $_POST['mail'])) {
$_SESSION['message'] = 4;
header("Location:$return");
exit;
}
if(strpos($_POST['sent'], "Send") === FALSE) {
$_SESSION['message'] = 1;
header("Location:$return");
exit;
} else {
$reply = $_POST['mail'];
$subject = htmlspecialchars($_POST['subject']);
$subject = trim($subject);
$content = htmlspecialchars($_POST['content']);
$content = trim($content);

$to = "some_mail@right_domain.com"; // type here right email

mail($to, $subject, $content, "From: $reply\r\n"."Reply-To: $reply\r\n");
$_SESSION['message'] = 5;
header("Location:$return");
exit;
}
?>


Good luck! Sonam
Including file with same definition on Win & Linux in PHP with 0 comments on Tue Oct 30, 2007 7:15 pm
Last year I am come in trouble when I create few pages with include function. Problem is quite stupid; I have Win on my computer and Linux on the host. For testing proposes I am using my computer and when I finish just FTP full site. There is not problem and everything is working perfect if is my include folder part of root folder (public_html) on the Linux host. But when I move include folder out of root folder (security reason) I must change my include definition on all pages. I do this one time, but after few days I am changing pages and I need again upload it.

In my life I am pretty lazy man and I don't like too much work, especially if I must do that again and again. That is reason why I am creating simple script what include files on both my Win localhost and Linux host. Here is script:

Code:
<?php
if($_SERVER['HTTP_HOST'] == "localhost") {
define("INC", "C:\Documents and Settings\MyComputer\Desktop\MyTestFolder\include/");
} else {
define("INC", "/home/some_domain/include/");
}
?>


First line check is what host is in use. If is ($_SERVER['HTTP_HOST'] = localhost then switch to my win folder; if is not then switch to (Linux) remote folder on my host. Define function define where PHP must looking for include files. Of course, you must change definitions for your needs. Upper script is only example.

Now, we can include files with the same definition on both servers. For example:

Code:
<?php include_once (INC . "footer.php"); ?>


Good luck! Very Happy
How to build simple PHP upload form in PHP with 6 comments on Fri Oct 19, 2007 2:36 pm
I will try to explain here some simple way to creating PHP upload form. This is only example, and you must know how I cannot guaranty how is this the best way for uploading files. I like this way because I can simple to see any part of checking and I can change and improve check in any moment. Of course, you can always to try finding out on Internet more about file uploading and security.

Now, we can start. First of all you need two files (uploadform.php, uploadfile.php). First one will give us option for uploading file from our computer, and second one will process, check and save uploaded file. I am create both in root folder of my site.

Here is simple code for uploadform.php:
Code:
<?php
session_start();
// security part
$_SESSION['name'] = session_id();
?>
<html>
<head>
<title>Upload form</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body bgcolor="#FFFFFF" text="#000000">
<form enctype="multipart/form-data" action="uploadfile.php" method="post">
<?php
// display messages
echo @$message;
?>
Upload this file: <input name="upload_file" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>

How you can see, on the top of the page is one PHP script. This script will help us in simple security check and for comunication between uploadform.php and uploadfile.php. Second PHP script, (in the form), will display messages.

Now we can go to create uploadfile.php. Here we must do few different types of process/checking before we save chosen file. In most situations I define three for me important things before I start with checking: place where I will redirect users if file is uploaded or error occur (I always use back to form), destination where I will save files and max file size.
Code:
<?php
session_start();

// redirect path
$redirect = "http://your_site.com/uploadform.php";
// saving destination (folder)
$save = "upload";
// max file size
$size = 300000;
?>

Then we can do first security check. In uploadform.php we are define $_SESSION['name'] with session_id. Now we can see is it session_id in uploadfile.php the same with session_id in uploadform.php. If is not user is redirected back to form.
Code:
if($_SESSION['name'] != session_id()){
$_SESSION['message'] = 1;
header("Location:$redirect");
exit;
}

And then we are check file size and uploading errors. For example, if user didn't chose some file.
Code:
if(@$_FILES["upload_file"]["size"] > $size || $_FILES["upload_file"]["error"] > 0){
$_SESSION['message'] = 2;
header("Location:$redirect");
exit;
}

My next checking is it file name contain two or more dots in name (e.g. somefile.exe.jpg). Maybe is this unnecessary but I like to do it. This is my second security check.
Code:
if(substr_count($_FILES["upload_file"]["name"], ".") > 1){
$_SESSION['message'] = 3;
header("Location:$redirect");
exit;
}

Ok, we are finish with first few checking but this is not all. Next we must check is any file having a same name like uploaded file.
Code:
if(file_exists($save . "/" . $_FILES["upload_file"]["name"])) {
$_SESSION['message'] = 4;
header("Location:$redirect");
exit;
}

And now we are near to the end with uploadfile.php. But here we can include one more security check and if file pass this check we can save it in chosen directory. We will check type of file in two different ways.
Code:
list($name, $ext) = explode(".", $_FILES["upload_file"]["name"]);
if($_FILES["upload_file"]["name"]  != "images/jpeg" && $ext != "jpg") {
$_SESSION['message'] = 5;
header("Location:$redirect");
exit;
} else {
move_uploaded_file($_FILES["upload_file"]["tmp_name"], $save . "/" . $_FILES["upload_file"]["name"]);
$_SESSION['message'] = 6;
header("Location:$redirect");
exit;
}

How you can see before this last (type) checking you can include more other checking. This is simplest way to improve this script for your needs. You can find full code of uploadfile.php on the end of page.

But, before the end we must little bit to improve uploadform.php. With case/switch we will change and display right messages independent what number uploadfile.php send back to uploadform.php. How you can see, we don't need to send this information with POST or GET. Sessions are working big job for us.
Code:
//messages part
switch(@$_SESSION['message']) {
case "1": $message = "Sorry, some error occur! <br />"; break;
case "2": $message = "Sorry, you can upload only files up to 300 Kb. <br />"; break;
case "3": $message = "Sorry, file cannot contain two or more dots in the name. <br />"; break;
case "4": $message = "Sorry, file with same name already exist. <br />"; break;
case "5": $message = "Sorry, your file haven't jpg extension. <br />"; break;
case "6": $message = "Your file has been submitted successfully. <br />"; break;
default: "";
}

Here is the end. Below is full code for both pages:
upladform.php
Code:
<?php
session_start();

// security part
$_SESSION['name'] = session_id();

//messages part
switch(@$_SESSION['message']) {
case "1": $message = "Sorry, some error occur! <br />"; break;
case "2": $message = "Sorry, you can upload only files up to 300 Kb. <br />"; break;
case "3": $message = "Sorry, file cannot contain two or more dots in the name. <br />"; break;
case "4": $message = "Sorry, file with same name already exist. <br />"; break;
case "5": $message = "Sorry, your file haven't jpg extension. <br />"; break;
case "6": $message = "Your file has been submitted successfully. <br />"; break;
default: "";
}
unset($_SESSION['message']);
?>
<html>
<head>
<title>Upload form</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>

<body bgcolor="#FFFFFF" text="#000000">
<form enctype="multipart/form-data" action="uploadfile.php" method="post">
<?php
// display messages
echo @$message;
?>
Upload this file: <input name="upload_file" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>


uploadfile.php
Code:
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors", "1");

// redirect path
$redirect = "http://your_site.com/uploadform.php"; // type here right URL
// saving destination
$save = "upload";
// max size
$size = 300000;

// first security check
if(@$_SESSION['name'] != session_id()){
$_SESSION['message'] = 1;
header("Location:$redirect");
exit;
}

// check file size and errors in uploading
if(@$_FILES["upload_file"]["size"] > $size || $_FILES["upload_file"]["error"] > 0){
$_SESSION['message'] = 2;
header("Location:$redirect");
exit;
}

// check for more then one dot in the name
if(substr_count($_FILES["upload_file"]["name"], ".") > 1){
$_SESSION['message'] = 3;
header("Location:$redirect");
exit;
}

// check names of existing files
if(file_exists($save . "/" . $_FILES["upload_file"]["name"])) {
$_SESSION['message'] = 4;
header("Location:$redirect");
exit;
}

// check is it file right type
list($name, $ext) = explode(".", $_FILES["upload_file"]["name"]);
if($_FILES["upload_file"]["name"]  != "images/jpeg" && $ext != "jpg") {
$_SESSION['message'] = 5;
header("Location:$redirect");
exit;
} else {
move_uploaded_file($_FILES["upload_file"]["tmp_name"], $save . "/" . $_FILES["upload_file"]["name"]);
$_SESSION['message'] = 6;
header("Location:$redirect");
exit;
}
?>

Wink Good luck,
Sonam
My first post, but not last one. in main with 1 comments on Thu Sep 06, 2007 12:54 pm
Hi,

It is great idea from Bondings to give us free blog. Of course, you can say, he is not only one (etc, etc) but where you can find free hosting, free mail, free directory and other things on one place? OK, maybe I am fun of Frihost but this is really exelent idea.

My blog have two different mision.
First one - I will try to post here some snipets of my PHP codes, etc. I am not programing guru, and I don't want to say: "This is best for you", but, I hope so, beginers can find some good points for their start.

Second - English is not my mother language, and you have good place for correcting my mistakes and polishing your English skills. Very Happy

See you.
--> All blog posts (5)

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.