Friday, June 27, 2014

Using curl to perform a POST request in PHP

Just use this simple function to perform a POST request :

function do_post($url, $data)
{
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  curl_close($ch);
  return $response;
}

$url is the website url for the request.
$data is an array that contains the form data that you want to send to the server. For example,
$data = array('name'=>'Bui Hoang Hai', 'website'=>'http://www.romajidesu.com')

Thursday, June 01, 2006

Google Search prefixes

Some Google Search prefixes:
  • link:url Shows other pages with links to that url.
  • related:url same as "what's related" on serps.
  • site:domain restricts search results to the given domain.
  • allinurl: shows only pages with all terms in the url.
  • inurl: like allinurl, but only for the next query word.
  • allintitle: shows only results with terms in title.
  • intitle: similar to allintitle, but only for the next word. "intitle:imagesh Free image hosting" finds only pages with webmasterworld in the title, and google anywhere on the page.
  • cache:url will show the Google version of the passed url.
  • info:url will show a page containing links to related searches, backlinks, and pages containing the url. This is the same as typing the url into the search box.
  • spell: will spell check your query and search for it.
  • stocks: will lookup the search query in a stock index.
  • filetype: will restrict searches to that filetype. "-filetype:doc" to remove Microsoft word files.
  • daterange: is supported in Julian date format only. 2452384 is an example of a Julian date.
  • maps: If you enter a street address, a link to Yahoo Maps and to MapBlast will be presented.
  • phone: enter anything that looks like a phone number to have a name and address displayed. Same is true for something that looks like an address (include a name and zip code)
  • site:www.somesite.net (tells you how many pages of your site are indexed by google)
  • allintext: searches only within text of pages, but not in the links or page title
  • allinlinks: searches only within links, not text or title

Tuesday, May 30, 2006

Little PHP tip: to get a shorter string.

It's simple, but helpful to get the shorter string (for abstract,...)

$num_words=10; // No. of words to get
$i=0;
$array=explode(" ",$longString);
$new_array=array();
$total=count($array);
while (($i<$num_words) && ($i<$total))
{
$new_array[]=$array[$i];
$i++;
}
$shortString = implode(" ",$new_array);

You can then make a function for reusing.

function shortString($longString,$num_words)
{
$i=0;
$array=explode(" ",$longString);
$new_array=array();
$total=count($array);
while (($i<$num_words) && ($i<$total))
{
$new_array[]=$array[$i];
$i++;
}
return implode(" ",$new_array);
}
Cheer!

Friday, September 23, 2005

Apress's Mandelbrot Generator Contest Result!


After carefully examining and testing numerous submissions for the fractal contest, Appress have selected three winners; one winner per language group. The speedy execution of their codes have earned each of them the prize of an Ipod Shuffle. Well, except for Mr. David Coakley (program in C, 1.08 seconds): his code runs the fastest among all the submissions and he wins the grand prize of a Playstation Portable!

The winner for PHP group is Mathias Helm, which generation time is 2 minutes 28.7 seconds. You see, the PHP is somehow more than 100 times slower than C. My subscription entry is slower: 3 minutes 2.5 seconds. To tell the true, I could optimize it a little more, but I was disappointed with the slow run so I just sent the second or third optimized version of it. Anyway, I was quite happy to do it. Recall an old saying: "If something is worth doing, it's worth doing the best" or some thing like that. If someone had submitted the contest, please post your result and experience here?

http://www.apress.com/promo/fractal/result.html

Thursday, August 25, 2005

PHP/MySQL List By Alphabet


This simple tutorials will show you how to create a alphabet index to grabs data from a mysql database.
Let's go on...




1. The alphabet index - how to create a cool one?



The first thing is list character from a to
z. How to do this? In a I've read, the author did it by doing a loop like

for ($i=$start ;$i<=$end; $i++);

Where $start and $end is the ASCII code of a
and z. However, It's sometimes quite hard to remember this value. Actually, I
cannot at the moment ;) So I solve the problem like this:

$list[]='0-9';
for ($ch=ord('a');$ch<=ord('z');$ch++)
{
$list[]=chr($ch);
}

Now that we have the list for the index. The next step is
simple. You will define the number of items per row, for example:

define('num_per_row','6');

The open a table, lop through the character set.
Check if an item is the first cell -> open the row, or the last cell -> close a
row:

$num_rows=count($list);
define ("TB_COLOR_LIGHT","#EEF7FA");
define ("TB_COLOR_DARK","#DBE9EF");
$width=(100/num_per_row).'%';
echo '<table bgcolor="'.TB_COLOR_DARK.'" width="100%">';
for ($i=0;$i<$num_rows;$i++)
{
if (0==$i%num_per_row)
{
echo '<tr align="center" valign="middle">'; // open the row
}
$url=append_sid('your_result_page&type=abc&keys='.$list[$i]);
echo '<td bgcolor="'.TB_COLOR_LIGHT.'" height="20" width="'.$width.'" nowrap>';
if (is_song_abc($list[$i])) // show only necessary items, see bellow
{
echo'<a href="'.$url.'"><b>'.$list[$i].'</b></a></td>';
}
else
{
echo $list[$i];
}
echo '</td>';
if ((num_per_row-1)==$i%num_per_row) // close the row
{
echo '</tr>';
}
}
echo '</table>';


2. The search code

The function is_abc($item) is to check if there is result which begin
with that item, for example, we search song_name from table TB_SONGS

function is_song_abc($keywords)
{
$where="song_name REGEXP '^[$keywords]'";
$sql ='SELECT count(*) as total
FROM '.TB_SONGS."
WHERE $where";
$result = sql_query($sql);
return mysql_result($result,'total');
}

The search code is totally similiar, you can
select what ever you want from the database with the WHERE condition is:

$where="song_name REGEXP '^[$keywords]'";


3. Conclusion

This tutorial is simple, yet useful to who new to mysql database search. In the next article, I intend to discuss more about mysql database search problem and some solution.

Monday, August 22, 2005

More on File Upload Handle In PHP

Some problem with PHP file upload handle:
Make sure the file size not exceed desired value
allow certain fype type: to prevent user upload harmful content.
In my current project. I have to solve it all. In this artice, I will share you some of the trick. If you like to know more, feel free to ask question by commenting.

Make a Upload function:

////////////////////
function upload_file($user_file,
$dest_dir,
$max_file_size,
$to_file_name='')
{

$file_name=(empty($to_file_name))
? $_FILES[$user_file]['name']
: $to_file_name;
$file_size=$_FILES[$user_file]['size'];
$temp_file=$_FILES[$user_file]['tmp_name'];
$upload_file="$dest_dir/$file_name";
$err='';
if ($_FILES[$user_file]['error'])
{
$err=upload_error_message(
$_FILES[$user_file]['error']
);
message_warning($err);
return false;
}
echo "
Uploading file $file_name...";
if (DEBUG)
{
echo "to $upload_file";
}
if (is_uploaded_file($temp_file))
{ //check size
if ($file_size>$max_file_size)
{
message_warning("
File size too large: $file_size
");
unlink($temp_file);
return false;
}
if (file_exists($upload_file))
{
message_warning('File Existed');
unlink($temp_file);
return false;
}
if (move_uploaded_file($temp_file,$upload_file))
{
echo "
File uploaded: $file_name!";
return true;
}
else
{
message_warning('Cannot copy file!');
return false;
}
}
else
{
message_warning('Upload Failed!');
return false;
}
}



Upload form valiate:

function validate_upload_form($update=false)
{
global $file_name;
global $tempfile;
global $err_file;

$ok=true;
if (empty($file_name))
{
$err_songfile='
No file specified!';
$ok=false;
}
else
{
$ext=get_ext($file_name);
if (!is_ext_allowed($ext))
{
$err_file='
Exentions not allow';
$ok=false;
}

}

if ( (!$ok)&&amp;(!empty($tempfile)) )
{
delete_file($tempfile);
}
return $ok;
}



Get File extension:


function get_ext($filename)
{
if (!empty($filename))
{
$pathinfo=pathinfo($filename);
return $pathinfo['extension'];
}
else
{
return 'Unkown';
}
}



Is an extension allow?


//
define ("EXT_ALLOWED",'mp3,wma,rm,mov,mid,swf,wmv');
function is_ext_allowed($ext)
{
$EXT_ALLOWED=explode(',',EXT_ALLOWED);
return in_array(strtolower($ext),$EXT_ALLOWED);
}



Upload error message:


function upload_error_message($err_code)
{
switch ($err_code)
{
case UPLOAD_ERR_OK:
return 'No error';
case UPLOAD_ERR_INI_SIZE:
$max_size=return_bytes(
ini_get('upload_max_filesize')
);
return 'The uploaded file exceeds
the upload_max_filesize directive
in php.ini: '.$max_size.' bytes';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds
the MAX_FILE_SIZE directive that
was specified in the HTML form.';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file
was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
default:
return 'Unkown error';
}
}



Upload Processing...


switch ($_action)
{
case 'upload':
if(validate_upload_form())
{
upload_processing();
}
else
{
show_upload_form();
}
break;
default:
show_upload_form();
break;

Saturday, August 20, 2005

File Upload Handle In PHP: Some tricky functions

I try to say few words here. I Just want to show some problem and Ideas on File Upload Hanlde in PHP and some samples – asap (as simple as possible):
Upload Limit Size There are 3 kind of limits:



  • Limit Specified in HTML code
  • Limit specified by you-PHP program
  • Limit specified of upload_max_filesize in PHP Configuration Directives.
The Limit by HTML form is useful to fast check upload file. But this can be trick if someone modifies the value in HTML code. So it's better recheck the value in PHP.
But in some cases, the value you specified exceeds the value upload_max_filesize.
The question is how to check this value?
You can use the following functions:


function return_bytes($val)
{
$val = trim($val);
$last = strtolower($val{strlen($val)-1});
switch($last)

{
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}


function upload_max_filesize()
{
return return_bytes(ini_get(\'upload_max_filesize\'));
}