Archive for the ‘PHP/MYSQL’ Category
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 »
Wordpress Plugin Mass Mail
Written by Codes Tips on March 23, 2009 – 4:25 pm -1. Description
This is a beta release of my first wordpress plugin. I called it Mass Mail because it can help you sending mass mails to a custom group from your blog. This is the first version of the plugin ( 1.0).
After you install the plugin to your blog, it is setup to send emails to you users from your blog.
2. Install
Here is a description on how to install this mass mail plugin:
1. Put MassMail.php into [wordpress_dir]/wp-content/plugins/
2. Go into the WordPress admin interface and activate the plugin
3. Optional: Go to Settings panel and click on Mass Mail, fill the group you wanna send emails and your email detail.
The plugin it’s very customizable because you can specify on which table(group) you send emails. You can for example send messages to your blog users, people that made a donation for you, people that subscribed to your blog and many other groups that you wanna send a mail.
Using Mass Mail Plugin
Mass Mail Setup
After installing the plugin you should go to Settings panel, click on Mass Mail and enter the details that you are requested.
At first it is setup to use the table wp_users that means it will send mails to all your blog users. To modify the first two values to fit to your group you should look in your Mysql wordpress database and see what table are the users stored to which you wanna send messages.
Table name: - is the table name to which you wanna send mass mails.
Table email field: - is the email field table of users specified in Table name.
Sender email: - is the sender email, that will appear in the header of the user.
Sender email will be something like name@domain.com . If you want to appear more user friendly to user headers you should customize Sender email like this Name
Send Mass Mail
After you setup the details of the group you should click on Save & Send Mails -> and fill the Subject and Message and Seconds between messages.
This will be the subject and body that every user of the group will receive in his mail and the seconds that will pass between emails that will be sent. This option is to not overload the smtp server if you send many emails.
Download Wordpress Plugin Mass Mail
Tags: PHP, PHP/MYSQL
Posted in Codes, PHP/MYSQL, Scripts | 4 Comments »
PHP save image from url
Written by Codes Tips on March 22, 2009 – 2:11 pm -Download Source Code
You can save image from url in PHP you should first get thesource of the image from the url  and after that save image to your server or disk depending on where you execute the php script.
First for getting an image from url you can use three ways to do this:
1. Using file_get_contents
$contents= file_get_contents('http://mydomain.com/folder/image.jpg');
2. Using fsockopen() function
To fetch an image with fsockopen() You should specify the host name of the server and the the rest or the url where the image is stored. To understand better here is a sample function, that takes the  that returns the source code of the image:
function GetImg($host,$link) { $fp = fsockopen($host, 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr (error number $errno) \n"; } else { $out = "GET $link HTTP/1.1\r\n"; $out .= "Host: $host\r\n"; $out .= "Connection: Close\r\n\r\n"; $out .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n"; $out .= "Accept-Language: en-us,en;q=0.5\r\n"; $out .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"; $out .= "Keep-Alive: 300\r\n"; $out .= "\r\n"; fwrite($fp, $out); $contents=''; while (!feof($fp)) { $contents.= fgets($fp, 1024); } fclose($fp); return $contents; } }
Example call:Â
$sourceimg=GetImg("www.mywebsiteexample.com","/image.jpg"); $sourceimg=strchr($sourceimg,"\r\n\r\n");//removes headers $sourceimg=ltrim($sourceimg);//remove whitespaces from begin of the string
3.Using CURL
function GetImageFromUrl($link) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch,CURLOPT_URL,$link); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result=curl_exec($ch); curl_close($ch); return $result; }
You should have installed at least  PHP 4.0.2. and libcurl installed to use curl.
Here is a function that will get the source of the image into a string variable:
You can use this code to call the function to get the source of the image:
$sourcecode=GetImageFromUrl("http://domain.com/path/image.jpg");
Â
After getting the image from url you should save image from url, doing a simple save to file from  a string variable.
You can use this piece of code:
$savefile = fopen('/home/path/image.jpg', 'w'); fwrite($savefile, $sourcecode); fclose($savefile);
Tags: PHP, PHP/MYSQL
Posted in Codes, PHP/MYSQL | 2 Comments »
Simple Free Mass Mailer Sender PHP
Written by Codes Tips on March 19, 2009 – 2:08 pm -Why SFMMS?
I just made a simple mass mailer sender in php, which can help you to easily send mass mail to your members. It’s very simple to setup and very useful.
This is a first version of the script, if people will like it, I will make other modify to it.
What is SFMMS?
This is a simple but very usefull Mass Mailer Sender script, that you can use from your server to send mass mails.You can for example use it to send annoncements for your members, that you have an offer for them. You can also use it as mass mailer subscriber to send weekly mails to yours subcribers.
How to install it?
To install SFMMS you should unzip the sfmms.zip to a folder of your choice to your hard disk  and modify the config.php in order to fit to your needs.
$server - it’s the server of your mysql database, which is ussually ‘localhost’
$database - is the name of your database on which your table is stored from the server
$db_user - the user of the database
$db_pass - the password for the user of the database
$fromadmin - email which the users will receive in his email
$table - the table from database where the users are stored
$table_email - the name field for the email of the $table(ex. ‘email’,'Email’)
You can customize the header.php and footer.php to fit with your website.
Upload all the files to a folder from your server.
Â
How to use it?
Access http://www.mywebsites.com/folder/massmail.php and put all the details you wanna send to users.
Â
Subject - is the subject that will appear in email subject to users.
Message - the message that you will send to users.
Seconds between messages - time to pass between each email that is sent to users(leave it 0.1). This is used when you send lots of messages to not overload smtp server.
Download Simple Free Mass Mailer Sender PHP
Tags: PHP, PHP/MYSQL
Posted in Codes, PHP/MYSQL, Scripts | No Comments »
Uploading doc/docx file to my server
Written by Codes Tips on March 19, 2009 – 6:09 am -Â
You can do allowing of doc/docx file in 2 modes: in html source with the property accept or by php code.
For uploading a doc/docx file you should first have a form where youhave all fields you need to send to server and another field that is of type file.
<form enctype="multipart/form-data" method="POST">This is the code for html: <table border="0"> <tbody> <tr> <td align="left">File:</td> <td><input accept="doc/docx" name="filename" size="40" type="file" /></td> </tr> <tr> <td><input name="Upload" type="submit" value="Upload" /></td> </tr> </tbody></table> </form>
Â
We should specify the enctype of the form to multipart/form-data in order to upload a file.
Â
Here is a brief explanation on how we can write the php code to upload one file to our server:
First we should set and verify the file extensions that we will allow the user to upload. We will allow only files with doc/docx extension. We should also verify that the filesize it’s greater then 10 bytes to be sure that is a doc/dox file. If we have no errors then we can use move_uploaded_file function to upload our doc/docx file.
Php code to upload doc/docx file to the server
Â
//if we clicked on Upload button if($_POST['Upload'] == 'Upload')   {   //make the allowed extensions   $goodExtensions = array(   '.doc',   '.docx',   );     $error='';   //set the current directory where you wanna upload the doc/docx files   $uploaddir = '/home/uername/folderroot/';   $name = $_FILES['filename']['name'];//get the name of the file that will be uploaded   $min_filesize=10;//set up a minimum file size(a doc/docx can't be lower then 10 bytes)   $stem=substr($name,0,strpos($name,'.'));   //take the file extension   $extension = substr($name, strpos($name,'.'), strlen($name)-1);   //verify if the file extension is doc or docx   if(!in_array($extension,$goodExtensions))    $error.='Extension not allowed<br>'; <span> </span> //verify if the file size of the file being uploaded is greater then 1   if(filesize($_FILES['filename']['tmp_name']) < $min_filesize)    $error.='File size too small<br>'."\n";   $uploadfile = $uploaddir . $stem.$extension; $filename=$stem.$extension;  if ($error=='') { //upload the file to if (move_uploaded_file($_FILES['filename']['tmp_name'], $uploadfile)) { echo 'File Uploaded. Thank You.'; } } else echo $error; }
Tags: PHP, PHP/MYSQL, programming
Posted in PHP/MYSQL | No Comments »
Fetching results from a mysql table
Written by Codes Tips on March 18, 2009 – 1:50 pm -To connect to a mysql database you should use the command mysql_connect .You should first setup the details of the mysql database.
$connect=mysql_connect($server, $db_user, $db_pass) or die ("Error: could not connect to database");
$server is the server for the mysql database, usually this is localhost, but you should double check.
$db_user is the user which connects to the server
$db_pass the password for the user
If the can’t connect to the server we should display an error message with die() command.
After we connect to the database we can make a sql query on the database that we want.
//we select all the rows from table TableName where the Field1 has a value of $value $results = mysql_db_query($database, "SELECT * FROM TableName WHERE Field1=".$value); while($resultrow = mysql_fetch_array($results, MYSQL_ASSOC)) { echo $resultrow['Field2'];//we show the result of the field Field1 }
After we make the query we can take each row of the result query and do whatever we want.
For closing a mysql connection we can use mysql_close($connect);
Example Code in PHP:
$server="localhost";//this is ussually localhost $db_userName="UserName"; $db_password="Password"; $database="DatabaseName"; $connect=mysql_connect($server, $db_userName, $db_password or die ("Mysql connection error"); $results = mysql_db_query($database, "SELECT * FROM TableName WHERE Field1=".$value); while($resultrow = mysql_fetch_array($results, MYSQL_ASSOC)) { echo $resultrow['Field2'];//we show the result of the field Field1 } mysql_close($connect);
Tags: PHP/MYSQL
Posted in PHP/MYSQL | 1 Comment »


















