Archive for April, 2009
PHP logout script
Written by Codes Tips on April 25, 2009 – 4:19 pm -This is a short php logout script for logging out a user that you previously logged in through your website:
<? function redirect($url) { echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL=$url\">"; echo "Click <a href=$url>".here.'</a> if you not get redirected'; } session_start();//initialize the session data $_SESSION['session_user'] = '';//clear the session user that you created on login unset($_SESSION['session_user']);//destroy the session variable of the user //redirect to home page redirect('index.php'); ?>
Tags: PHP, PHP/MYSQL
Posted in Codes, PHP/MYSQL | No Comments »
Delphi ftp upload files directory
Written by Codes Tips on April 25, 2009 – 2:56 pm -To upload files from a directory in delphi to a ftp server you should first loop through all the files that are in that directory. To do this you should first declare a new type of files, that will be a string of array that will hold the names of files from that directory.
type FilesArray=array[1..1000] of string;
To get all the files from a directory you should use the function FindFirst and FindNext to loop through all the files of directory. To use those functions you should include the unit SysUtils in the uses. To get the attribute of a file you should use the record TSearchRec.The TSearchRec record has the following attribute:
type TSearchRec = record Time : Integer; Size : Integer; Attr : Integer; Name : TFileName; ExcludeAttr : Integer; FindHandle : THandle; FindData : TWin32FindData; end;
The most impostant attributes you need are the following:
Time - when the file was last modified
Size - the size of the file
Attr - file attributes
Name - the name of the file
Here is the function to get all the files from a directory:
function GetFiles(dirpath:string;var nrfiles:integer):FilesArray; var searchResult : TSearchRec; allfiles: FilesArray; begin nrfiles:=0; if FindFirst(dirpath+'*.*', faAnyFile, searchResult) = 0 then begin repeat if (searchresult.name<>'.') and (searchresult.name<>'..') then begin inc(nrfiles); allfiles[nrfiles]:=searchresult.name; end; until FindNext(searchResult) <> 0; FindClose(searchResult);//free the memory GetFiles:=allfiles; end; end;
To upload a file to a ftp server we can use the ftp Indy component IdFtp, using the Put command to upload a file. In order not the application to stop when the file is uploaded use a try except statement to catch the error:
procedure UploadFiles(host:string;username:string;password:string); var files:FilesArray; j,nrfiles:integer; idftp1:TIdFtp; begin //conect to ftp server idftp1.Host:=host; idftp1.Username:=username; idftp1.Password:=password; idftp1.Connect; //go in which directory you need with ChangeDir command idftp1.ChangeDir('www'); //get all files from local dir files:=Getfiles(ExtractFilePath(application.exename)+'mydir\',nrfiles); //upload all files from dir to ftp server for j:=1 to nrfiles do begin idftp1.put(ExtractFilePath(application.exename) + 'mydir\' + files[j], files[j]); except On E:Exception do begin end; end; end; //disconnect from ftp server idftp1.Quit; end;
Tags: borland delphi, Delphi
Posted in Codes, Delphi | No Comments »
PHP clear cache directory
Written by Codes Tips on April 18, 2009 – 12:09 pm -We talked before how we can cache with php. In this post I will show you how we can clear cache. So, for caching a website in php we said we need a directory were we will store all the pages that are showing to the user and save the output to a folder on our server. So in order to clear the cache you should delete all the files from directory that were created.
To do that we only need to loop through the cache folder(go here for learning how to get all the files from a folder) and delete all the files that are inside that folder. Remember to change permissions 777 to cache directory. Here is the code to do that
<? $cachedir = "../cache/"; if ($cachehandle = opendir($cachedir)) { while (false !== ($file = readdir($cachehandle))) { if ($file != "." && $file != "..") { $file2del = $cachedir."/".$file; unlink($file2del); } } closedir($cachehandle); } echo 'Cached cleared.'; ?>
Tags: PHP
Posted in PHP/MYSQL | 1 Comment »
PHP cache file for a period
Written by Codes Tips on April 12, 2009 – 3:25 pm -The concept to cache it’s very simple in PHP. First you should have some content on a page in order to cache it. First you should have a directory where all the cached pages are stored.
How it works?
First, we should verify if the page exists in our directory, if exists then it means that the page was saved(chached) before and we can list that page. For caching a page for a period of time we should verify if the date creation of the page cached was before the time that we want to keep the page cached, otherwise we create a fresh cached page. Here is a sample code to do this:
<?php $filetocache = "../cache/".$filename.".html"; //to cache outside root directory //time to cache the page $timecache = 3600 * 24 * 7;//// calculate a period of 1 week // Here we test if the file exists and if the cached file was created in the period we specify if (file_exists($filetocache) && (time() - $time cache < filemtime($filetocache))) { include($filetocache);//we show the page that was cached previously echo "<!-- Date cached ".date('jS F Y H:i', filemtime($filetocache))." -->n"; exit; } ob_start(); // here we start the output buffer //HERE we otput the page as html .... ?>
If it not exists we list our page and in the end we save the page to the cache directory, so next time the page is loaded we will get the content from cache directory. So if it time creation is higher then our period then we list the page and rewrite again to the cache directory. Here is the code for saving the contents output displayed on the browser:
<? ob_start(); //HERE we otput the page as html ..... $filetocache = "../dircache/".$filename.".html";//this is the page that we should cache, the filename is the name of the page $fp = fopen($filetocache, 'w'); // first open the cache file for writting fwrite($fp, ob_get_contents()); // we put the output contents that are sent to browser fclose($fp); // close the file ob_end_flush(); // for sending content to the browser ?>
Tags: Codes, PHP
Posted in Codes, PHP/MYSQL | 1 Comment »
PHP read directory into array
Written by Codes Tips on April 12, 2009 – 4:10 am -In this short tutorial I will show how you can read directory into array that is on the server where the script is placed. We will get the names of all the files from that directory. For doing this you should create a handler for the directory by using opendir, passing the name of the directory.
After creating a handler to that directory we should iterate through all the files of that directory, so we gone use a loop until all the files from that directory are read:
while ($file = readdir($handler)) {
//get the name of the file
}
After reading finishing the loop we should close the handler to that directory.
closedir($handler);
Code:
$directory="exampledir";
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$nofiles=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$nofiles++;
$files[$nofiles]=$file;
}
}
//close the handler
closedir($dirhandler);
Tags: PHP
Posted in PHP/MYSQL | 3 Comments »
PHP ftp upload tutorial
Written by Codes Tips on April 12, 2009 – 4:04 am -To upload a file to ftp you need a html form where you can insert the ftp details, like the ones described above:
server - is the server on which he wanna upload the file
username - is the user for which he makes the connection to ftp server
password - is the user password for ftp username
path to server - is the path on the ftp server which he wanna upload his file.
user file - is the file of the you wanna upload to ftp server
Hint: If you want to offer to your website members a form where he will upload his file, you should take the ftp server details and path, from a config file. Here we made a complete example how to upload through ftp putting all the details.
We will have a POST form and an enctype of multipart/form-data because we have a file on our form.
The user form that the user will insert info is like that:
<form action="upload.php" method="POST" enctype="multipart/form-data"> <table align="center"> <tr> <td align="right"> Server: </td> <td> <input size="50" type="text" name="server" value=""> </td> </tr> <tr> <td align="right"> Username: </td> <td> <input size="50" type="text" name="user" value=""> </td> </tr> <tr> <td align="right"> Password: </td> <td> <input size="50" type="text" name="password" value="" > </td> </tr> <tr> <td align="right"> Path on the server: </td> <td> <input size="50" type="text" name="pathserver" > </td> </tr> <tr> <td align="right"> Select your file to upload: </td> <td> <input name="userfile" type="file" size="50"> </td> </tr> </table> <table align="center"> <tr> <td align="center"> <input type="submit" name="submit" value="Upload image" /> </td> </tr> </table> </form>
Now, when the user submits the form, we should get all the details that he inputed and then upload the file to the ftp server.
// the file name that should be uploaded $filep=$_FILES['userfile']['tmp_name']; // ftp server $ftp_server=$_POST['server']; //ftp user name $ftp_user_name=$_POST['user']; //ftp username password $ftp_user_pass=$_POST['password']; //path to the folder on which you wanna upload the file $paths=$_POST['pathserver']; //the name of the file on the server after you upload the file $name=$_FILES['userfile']['name'];
To upload the file , first we should establish a connection to the ftp server using ftp_connect and specifing as a parameter the ftp servver. This function return a connection id.
$con_id=ftp_connect($ftp_server);
After connecting to server we should login using the function ftp_login passing three parameters: connection id, ftp user, ftp user password and checking if the login was sucessfull
// login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // check connection if ((!$conn_id) || (!$login_result)) { echo "FTP connection has failed!"; echo "Attempted to connect to $ftp_server for user $ftp_user_name...."; exit; } else { echo "Connected to $ftp_server, for user $ftp_user_name"."....."; }
After loging in we can upload the file to the server and after that check if the file was uploaded correctly:
// upload the file $upload = ftp_put($conn_id, 'public_html/'.$paths.'/'.$name, $filep, FTP_BINARY); // check upload status if (!$upload) { echo "FTP upload has failed!"; } else { echo "Uploaded $name to $ftp_server "; }
In the end we should close the ftp connection using ftp_close passing the connection id:
ftp_close($conn_id);
For uploading big files you should set the time limit of the server in order not to finish the script while it’s uploading:
set_time_limit(300);
Here is the complete code:
<? if(!isset($_POST["submit"])){?> <form action="upload.php" method="POST" enctype="multipart/form-data"> <table align="center"> <tr> <td align="right"> Server: </td> <td> <input size="50" type="text" name="server" value=""> </td> </tr> <tr> <td align="right"> Username: </td> <td> <input size="50" type="text" name="user" value=""> </td> </tr> <tr> <td align="right"> Password: </td> <td> <input size="50" type="text" name="password" value="" > </td> </tr> <tr> <td align="right"> Path on the server: </td> <td> <input size="50" type="text" name="pathserver" > </td> </tr> <tr> <td align="right"> Select your file to upload: </td> <td> <input name="userfile" type="file" size="50"> </td> </tr> </table> <table align="center"> <tr> <td align="center"> <input type="submit" name="submit" value="Upload image" /> </td> </tr> </table> </form> <?} else { set_time_limit(300);//for setting $paths=$_POST['pathserver']; $filep=$_FILES['userfile']['tmp_name']; $ftp_server=$_POST['server']; $ftp_user_name=$_POST['user']; $ftp_user_pass=$_POST['password']; $name=$_FILES['userfile']['name']; // set up a connection to ftp server $conn_id = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); // check connection and login result if ((!$conn_id) || (!$login_result)) { echo "FTP connection has encountered an error!"; echo "Attempted to connect to $ftp_server for user $ftp_user_name...."; exit; } else { echo "Connected to $ftp_server, for user $ftp_user_name"."....."; } // upload the file to the path specified $upload = ftp_put($conn_id, $paths.'/'.$name, $filep, FTP_BINARY); // check the upload status if (!$upload) { echo "FTP upload has encountered an error!"; } else { echo "Uploaded file with name $name to $ftp_server "; } // close the FTP connection ftp_close($conn_id); } ?>
Download source code
Tags: PHP, PHP/MYSQL
Posted in Codes, PHP/MYSQL, Scripts | No Comments »
PHP paging tutorial
Written by Codes Tips on April 4, 2009 – 2:27 am -In this tutorial I want to make a paging tutorial in php.
A friend of mine tell me to help him with a script to do paging in php from a mysql database and I would like to share with all.
If you wanna take data from a xls,csv or other files, from a database like mysql,mssql and you wanna list the results on the page, you may have many results for your result.
I want to present an example so you can understand how a paging can be made in php. I made an example about how to search results from a mysql database and make pagination on the results.
You should first have a form in html from where the user can input the search field:
<form action="Search.php" method="POST"> <table align="center"> <tr><td>Name:</td><td><input type="text" name="search" width="40"></td><td><input name=submit type=submit value=Search><input type=hidden name=hiddensearch value=yes></td></tr> </table> </form>
You should now put the code before the html form for verifying if the user submits the form through a POST, if not show the html form. So we will have 2 cases, when when we first post the form we will show the first page and links to all other pages. The links to other pages will look something like search.php?search=Name&page=10 -> this will fetch the results from database for the page number 10 with the search query ‘Name’. Each page will have a number of results say 20, which we will call it pagesize.
First we should connect to the mysql server and make a query on the database. We discuss previously how we can connect to a database and how to make a query, go here for learning how to connect and fetch results from mysql. After we make a query we get each row of the query result and verify if it is on the current page( if it is a post then we will get the first $pagesize records). To select records for a page we should use verify a condition for every row:
if ($nr>=($pagesize*($page-1)+1)&&($nr<=($pagesize*$page))) { //write the result }
Where $nr - is the current record
$pagesize - is the size of a page
$page - is the page number
In the end we should write all the links to other pages( the navigation through result pages part ):
<? echo '<tr>'; echo '<td>'; for ($i=1;$i<=ceil($nr/$pagesize);$i++) if ($i!=$page) echo '<a href="Search.php?search='.urlencode($name).'&page='.$i.'">'.$i.'</a> | '; else echo $i.' | '; echo '</td>'; echo '<tr>'; ?>
Here is the complete code:
<? $server=""; $user=""; $pass=""; $database=""; include("header.php"); if($_POST['hiddensearch'] == 'yes'|| isset($_GET['search'])) { $connect=mysql_connect($server, $user, $pass) or die ("Database Connection Error"); $pagesize=20;//how many results will be on a page $page=$_GET['page'];//curent page if ($page=="") $page=1; //we if ( $_POST['hiddensearch'] == 'yes') $name=$_POST['search']; else $name=$_GET['search']; //we write the query $result = mysql_db_query($database, "SELECT * FROM Table Where Name='".$name."'"); if(mysql_num_rows($result) > 0) { ?> <br> <center>Results <?=mysql_num_rows($result);?> with <b><?echo $name;?> parameter</b></center> <TABLE align="center" cellspacing="0" cellpadding="0"> <? $nr=0; //fetch every row and verify if it is in the current page while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $nr++; if ($nr>=($pagesize*($page-1)+1)&&($nr<=($pagesize*$page))) { echo '<tr>'; echo '<td>'.$row['Name'].'</td>'; echo '</tr>'; } } //build the navigation links to other pages if ($pagesize<$nr) { echo '<tr>'; echo '<td>'; for ($i=1;$i<=ceil($nr/$pagesize);$i++) if ($i!=$page) echo '<a href="Search.php?search='.urlencode($name).'&page='.$i.'">'.$i.'</a> | '; else echo $i.' | '; echo '</td>'; echo '<tr>'; } echo '</table>'; } else { echo 'No results found.'; } mysql_close($connect); } else { ?> <center><b>Search </b></center><br><br> <form action="Search.php" method="POST"> <table align="center"> <tr><td>Name:</td><td><input type="text" name="search" width="40"></td><td><input name=submit type=submit value=Search><input type=hidden name=hiddensearch value=yes></td></tr> </table> </form> <? } include("footer.php"); ?>
Download code here
Tags: PHP, PHP/MYSQL
Posted in Codes, PHP/MYSQL, Scripts | No Comments »


















