If you wanna get some information from servers using the protocols like http or ftp in PHP you can use cURL to do multithreading.
Multithreading is a term used when we do more jobs in parallel.
First I assume you know what cURL is and what you can it. If you are new to cURL, you can check one of my article on posting data with cURL , it will give you a brief intro to cURL.
To create this with cURL you should know what the following PHP functions do:
curl_multi_init – initialize a new cURL multi handle. It will return the cURL handle on success and FALSE on error.
curl_multi_add_handle — Add a cURL handle to a cURL multi handle.
curl_multi_exec — Runs all the curl handle in the cURL multi handle in parallel.
curl_multi_remove_handle — Removes a cURL handle from a cURL multi handle.
curl_multi_close — close the cURL multi handle.
You will need at least PHP 5.0 installed on your server in order this cURL function to work.
So now that you know what this functions do, we should first create the links to the servers from were we wanna get info. I will assume that we wanna get information from 3 servers simultaneous:
$list[1] = "http://www.example1.com";
$list[2] = "ftp://example.com";
$list[3] = "http://www.example2.com";
After creating the list of links we should initialize the cURL multi handle and adding the cURL handles.
$curlHandle = curl_multi_init();
for ($i = 1;$i <= 3; $i++)
$curl[$i] = addHandle($curlHandle,$list[$i]);
Now we should execute the cURL multi handle retrive the content from the sub handles that we added to the cURL multi handle.
ExecHandle($curlHandle);
for ($i = 1;$i <= 3; $i++)
{
$text[$i] = curl_multi_getcontent ($curl[$i]);
echo $text[$i];
}
In the end we should release the handles from the cURL multi handle by calling curl_multi_remove_handle and close the cURL multi handle:
for ($i = 1;$i <= 3; $i++)//remove the sub - handles
curl_multi_remove_handle($curlHandle,$curl[$i]);
curl_multi_close($curlHandle);
Here is the complete code for doing multithreading in php with cURL:
<?
//add a url to the handler
function addHandle(&$curlHandle,$url)
{
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HEADER, 0);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($curlHandle,$cURL);
return $cURL;
}
//execute the handle until the flag passed
// to function is greater then 0
function ExecHandle(&$curlHandle)
{
$flag=null;
do {
//fetch pages in parallel
curl_multi_exec($curlHandle,$flag);
} while ($flag > 0);
}
$list[1] = "http://www.example1.com";
$list[2] = "ftp://example.com";
$list[3] = "http://www.example2.com";
$curlHandle = curl_multi_init();
for ($i = 1;$i <= 3; $i++)
$curl[$i] = addHandle($curlHandle,$list[$i]);
ExecHandle($curlHandle);
for ($i = 1;$i <= 3; $i++)
{
$text[$i] = curl_multi_getcontent ($curl[$i]);
echo $text[$i];
}
for ($i = 1;$i <= 3; $i++)//remove the handles
curl_multi_remove_handle($curlHandle,$curl[$i]);
curl_multi_close($curlHandle);
?>
Tags:
PHP
To do cascading drop down in php using mysql we can use AJAX. The name AJAX is from asynchronous JavaScript and XML and it’s a new technique for web development to build rich interactive web application. The power of this technique comes from the fact that it can send to server requests from the client side, in order to not reload the page. The object that is using AJAX to send and retrieve data between server and the client is named XmlHttpRequest.
To build a cascading drop down in php to retrieve data from a mysql server we will first populate a drop down with the results from a first table from a mysql database. The first table is linked with a second table by a field. When we change the drop down we should assign to OnChanging event an Javascript function that will populate the second drop down . The function will create a new XmlHttpRequest object and make a call to other php script, grab data and populate the second drop down. The script that it’s called will fetch the results for that field that was changed.
Watch a demo here:populate drop down using ajax
Tags:
AJAX,
PHP,
PHP/MYSQL
To copy a directory source to a destination directory you will need to scan the source directory with all files and directory and copy to the destination. To accomplish this we should make a recursive function that will copy the files from source to target dir. If it is not a directory in the source dir we should just copy the file to target. If it is a directory in the source dir then we should create a new dir in the target directory and apply the same mechanism, so we need to recall again the same function.
Here is the code to do this:
<?
function copy_directory( $source, $destination ) {
if ( is_dir( $source ) ) {
@mkdir( $destination );
$directory = dir( $source );
while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
if ( $readdirectory == '.' || $readdirectory == '..' ) {
continue;
}
$PathDir = $source . '/' . $readdirectory;
if ( is_dir( $PathDir ) ) {
copy_directory( $PathDir, $destination . '/' . $readdirectory );
continue;
}
copy( $PathDir, $destination . '/' . $readdirectory );
}
$directory->close();
}else {
copy( $source, $destination );
}
}
?>
Calling the function:
copy_directory('dirnameSource','dirnameDestination');
Tags:
PHP,
PHP/MYSQL
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
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
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
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.
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
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:
For uploading big files you should set the time limit of the server in order not to finish the script while it’s uploading:
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);
}
?>
Tags:
PHP,
PHP/MYSQL
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");
?>
Tags:
PHP,
PHP/MYSQL
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.
Tags:
PHP,
PHP/MYSQL