Upload a file using cURL and PHP

cURL is a great library. It can do just about anything that a normal web browser can do including send a file via a post request.

This makes it really easy to transmit files between computers. In my case, I was looking for an easy way to send images snapped by various webcam systems to a central server with php managing the images.

Here is a simple script to send a file with php/cURL via POST:

	$target_url = '';
        //This needs to be the full path to the file you want to send.
	$file_name_with_full_path = realpath('./sample.jpeg');
        /* curl will accept an array here too.
         * Many examples I found showed a url-encoded string instead.
         * Take note that the 'key' in the array will be the key that shows up in the
         * $_FILES array of the accept script. and the at sign '@' is required before the
         * file name.
	$post = array('extra_info' => '123456','file_contents'=>'@'.$file_name_with_full_path);
        $ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$target_url);
	curl_setopt($ch, CURLOPT_POST,1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$result=curl_exec ($ch);
	curl_close ($ch);
	echo $result;

And here is the corresponding script to accept the file:

$uploaddir = realpath('./') . '/';
$uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);
echo '<pre>';
	if (move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
	    echo "File is valid, and was successfully uploaded.\n";
	} else {
	    echo "Possible file upload attack!\n";
	echo 'Here is some more debugging info:';
	echo "\n<hr />\n";
        print "</pre>\n";

That’s it.

Generate Slug from text in PHP

To create slug in PHP, please go thru below code:

function slugify($text)
  // replace non letter or digits by -
  $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
  // trim
  $text = trim($text, '-');
  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  // lowercase
  $text = strtolower($text);
  // remove unwanted characters
  $text = preg_replace('~[^-\w]+~', '', $text);

  if (empty($text))
    return 'n-a';
  return $text;

echo slugify("Paran (Paracetamol 500 mg)");

So the output will be


Convert Currency using Google finance calculator with PHP

Convert currency from one country to another easily with Google’s finance calculator, using that it’s possible to collect the output using PHP.

Please check below URL:


Use below code to extract actual curreny from html:

function convertCurrency($amount, $from, $to){
$data = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from&to=$to");
preg_match("'<span class=bld>(.*?)</span>'si",$data, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted[1]);
return number_format(round($converted, 3),2);

echo convertCurrency("1.00", "USD", "INR");