Posts Tagged ‘PHP’


Custom error pages with htaccess

A tutorial to enable custom error pages with an htaccess file. Note htaccess files only work on a linux server

To create an htaccess file open notepad or any plain text editor and save the file as .htaccess, if using notepad make sure the file type is set to all files or you will create a txt file.

There are five types of error pages that your server has to offer which are:

400 – Bad request

401 – Authorization Required

403 – Forbidden directory

404 – Page not found

500 – Internal Server Error

if you don’t have the right page like say a 404 page then the server issues you the error and informs you it could not find an error document. Making your own custom error page is very easy with htaccess on an htaccess file enter the command ErrorDocument then the error number then a forward slash then the path to the error page which tells the page where to go like this:

ErrorDocument 404 /errors/404.php

The final file will look like this:

ErrorDocument 400 /400.html

ErrorDocument 401 /401.html

ErrorDocument 403 /403.html

ErrorDocument 404 /404.html

ErrorDocument 500 /500.html

Save the htaccess file in the root of the server then if their is an error the custom error page is served.
Credit : phphelptutorials.com

PHP Cookies: How to Set Cookies & Get Cookies

Cookies don’t have to be an essential part of a website but can provide some of the “little things” that can set your website apart from the rest. Cookies are small tidbits of information that you save on the client’s computer so that you can access them next time they visit the website. Session ID’s are also usually held in cookies.

So what are the most popular uses of cookies? They are:

  • To store username/password information so that the user doesn’t have to log in every time they visit the website (“remember me” sign ins).
  • To simply remember the user’s name.
  • To keep track of a user’s progress during a specified process.
  • To remember a user’s theme.

Setting the Cookie

Setting a cookie requires a key, a value, and the amount of time to allow the cookie to exist.

$first_name = 'David';
setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day

Above, we set the user’s first name equal to ‘David’ (this data would actually come from a form or database but for the sake of the example we’ll use my name). Then, we set a cookie with the key of “first_name” with the value ‘David’, and program it to expire 7 days from now.

Getting the Cookie Values

Now that we’ve set our cookie, it’s time to get the value pretend they left your site and are coming back two days later).

echo 'Hello '.($_COOKIE['first_name']!='' ? $_COOKIE['first_name'] : 'Guest'); // Hello David!

Above, we check to see if the cookie with ‘first_name’ as the key still exists. If so, we use their name; if not, we call them “Guest”. Basic cookies are that easy!

PHP cookies can be set with more specific directives, including path, domain, secure, and httponly.

setcookie('first_name',$first_name,time() + (86400* 7),'/~sugar/','sudhirtiwari.com,true,true);

This cookie is the same as above, but we’re also telling the cookie to be applied towards the “~sugar” directory on the “davidwalsh.name” domain. It is for use only on an SSL connection and it may not be used by JavaScript.

Some other things to know about cookies:

  • Although you set an expiration on the cookie, a user can delete cookies at any time.
  • Cookies can only be accessed by the browser that set them (Firefox and IE don’t share them)
  • A user can turn cookies off in their browser.

What is difference between mysql_fetch_array(),mysql_fetch_row() and mysql_fetch_object() ?

mysql_fetch_array ? Fetch a result row as an associative array, a numeric array, or both. Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

mysql_fetch_object ? Fetch a result row as an object. Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

mysql_fetch_row ? Get a result row as an enumerated array. Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

PHP: List files in a directory

<?php
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != ".."))
{
echo("<a href='$dirname$file'>$file</a> <br />");
}
}
?>

so lets resolve the problem that your mind facing regarding listing of file inside folder, i needed to list some files in a directory on my server to generate a few things. As i was busy with that i thought some people might need to do the same, but don’t really know how or are struggling with it.

That’s why i decided to put it on a page here so that everyone can use it. Feel free to play around with it. It isn’t a lot of code and simply lists a list of files without any format, but it’s a great start if you want to make a list of images or a gallery. Or maybe you want to list rar files, who knows right.

Anyway! Look below for the simple solution to listing files in a folder on your server with PHP

On the top of your page BEFORE everything else you put the following code. Add your folder name between the ” ” The . between them is the current folder your php page will be in:

<?php
$dirname = ".";
$dir = opendir($dirname);
?>

In your body you put this:

<?php
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != ".."))
{
echo("$file <br />");
}
}
?>

And to make them into links you could use this one instead:

This will list all the files in the appointed folder under each other with a link to that file. You can further edit it and add more functions etc etc to make it more complicated. Do leave a comment if you added something so that we can add it to the page as an example by users or php pros.

Insert Your Recent Comments from Facebook to Database

The sample is for scraping data from Facebook home page. Once you will pass your username and password in variables  i have declared in file and execute the code you will get your home page of Facebook.

Here php code will pass the variables by POST method to https://login.facebook.com/login.php page and login into facebook account then other curl call will call my home page to get the home page HTML.

I have written code of how i am scrapping data by DOM Parser.

<?PHP
$first_name = 'First Name';
$login_email = 'facebookloginemail';
$login_pass = 'password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_exec($ch);

curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
$page = curl_exec($ch);

/*
Here it will print the facebook home page with your recent updates
*/

echo $page;

// Parse the HTML information and return the results.
$dom = new DOMDocument();
@$dom->loadHtml($page);

$xpath = new DOMXPath($dom);

// Get a list of articles from the section page

$articleList = $xpath->query("*/div[@id='m_stream_stories']");
print_r($articleList);

// Add each articles url to the Articles array
// This way we can scrap any part of data of any sites.

$articles = array();
foreach ($articleList as $item){
	$articles[] = array(
								'url' => $item->getElementsByTagName('a')->item(0)->getAttribute('href')
					   );
}

print_r($articles);

// Here we can loop for the article array and insert it into database.
?>

If you have any trouble in getting it work let me know i will help you.

Uploading file by PHP Code

Let’s start by creating the html file form:

Files are uploaded from the browser using an input tag, with the type parameter set to “file”. This is supported by all browsers currently available on the market.

The most important thing is to set the ENCTYPE attribute of the form to “multipart/form-data” and set the form’s action to the file upload page. The file upload page will handle the actual file uploading.
html file : upload.html

 <form name="frmupload" id="frmupload" method="post" action="/upload.php" enctype="multipart/form-data">
  <fieldset>
  <legend>File upload:</legend>
  <table>
  <tr>
	<td>
	  <label for="file">File:</label>
	</td>
	<td>
	  <input name="vFile" type="file" id="vFile" />
	</td>
  </tr>
  </table>
  <input type="submit" name="upload" value="Upload" />
  </fieldset>
</form>

Now first create the upload script:
In PHP, uploaded files are accessed via the $_FILES array:

* $_FILES["file"]["name"]: The original filename on the client’s machine.
* $_FILES['file']['type']: The mime type of the file.
* $_FILES['file']['size']: The size, in bytes, of the uploaded file.
* $_FILES['file']['tmp_name']: The temporary filename of the file in which the uploaded file was stored on the server.

Here i have created one function so we will call this in our upload.php it will makes easy to upload , optimize the code and make the code reusable.

php script file : upload.php

<?php
$imagepath='';		// Make Sure you have set the permission of folder in which you are uploading files.
$image= $_FILES['file']['tmp_name'];
$image_name= $_FILES['file']['name'];
$prefix=''; 	// Optional
$vaildext= "gif,jpg,jpeg,bmp,PNG,JPG,JPEG,GIF,BMP,png"; 

$output = fileupload($imagepath , $image , $image_name , $prefix , $vaildext);

fileupload($imagepath,$image,$image_name,$prefix='', $vaildExt= "gif,jpg,jpeg,bmp,PNG,JPG,JPEG,GIF,BMP,png");
 function fileupload($imagepath,$image,$image_name,$prefix='', $vaildext= "gif,jpg,jpeg,bmp,PNG,JPG,JPEG,GIF,BMP,png")
	{

	   $msg="";
	   if(!empty($image_name) and is_file($image) )
		{
			$tmp=explode(".",$image_name);
			for($i=0;$i<count($tmp)-1;$i++)
			{
				$tmp1[]=$tmp[$i];
			}
			$file=implode("_",$tmp1);
			$ext=$tmp[count($tmp)-1];

			$vaildext_arr = explode(",", strtoupper($vaildext));
			if(in_array(strtoupper($ext), $vaildext_arr))
			{
				$imagefile=$prefix.$file."_".date("YmdHis").".".$ext;
				$ftppath1 = $imagepath.$imagefile;
				if(!copy($image, $ftppath1))
				{
					$imagefile = '';
					$msg="Failed to Upload files !!";
				}
				else
					$msg="File uploaded successfully !!";
			}
			else
			{
				$imagefile = '';
				$msg="Extension Is Not Valid, please use mentioned extesions only $vaildExt !!!";
			}
		}
		$ret[0] = $imagefile;
		$ret[1] = $msg;
		return $ret;
	}
?>

Its easy and working :)

Let me know your thoughts if you are facing any problem while uploading files.

PHP Functions to Import/Export CSV data

These two function make it very easy to import and export CSV in PHP.
Documentation
CSVEport()

This function has just one argument – the query that returns the necessary data to be exported.

Example: CSVExport(“SELECT name,username,email,url FROM User WHERE status=1″);
CSVImport()

This will upload a CSV file and import the data into the specified table. This function must have the following arguments…

$table
The name of the table the data must be imported to
$fields
An array of fields that will be used
$csv_fieldname
The name of the CSV file field

Example: CSVImport(“User”, array(‘name’,'username’,'email’,'url’), “csv_file”);
Code
//Get the result of the query as a CSV stream.
//http://www.bin-co.com/php/scripts/csv_import_export/
function CSVExport($query) {
$sql_csv = mysql_query($query) or die(“Error: ” . mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer

header(“Content-type:text/octect-stream”);
header(“Content-Disposition:attachment;filename=data.csv”);
while($row = mysql_fetch_row($sql_csv)) {
print ‘”‘ . stripslashes(implode(‘”,”‘,$row)) . “\”\n”;
}
exit;
}

//Import the contents of a CSV file after uploading it
//http://www.bin-co.com/php/scripts/csv_import_export/
//Aruguments : $table – The name of the table the data must be imported to
// $fields – An array of fields that will be used
// $csv_fieldname – The name of the CSV file field
function CSVImport($table, $fields, $csv_fieldname=’csv’) {
if(!$_FILES[$csv_fieldname]['name']) return;

$handle = fopen($_FILES[$csv_fieldname]['tmp_name'],’r');
if(!$handle) die(‘Cannot open uploaded file.’);

$row_count = 0;
$sql_query = “INSERT INTO $table(“. implode(‘,’,$fields) .”) VALUES(“;

$rows = array();

//Read the file as csv
while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE) {
$row_count++;
foreach($data as $key=>$value) {
$data[$key] = “‘” . addslashes($value) . “‘”;
}
$rows[] = implode(“,”,$data);
}
$sql_query .= implode(“),(“, $rows);
$sql_query .= “)”;
fclose($handle);

if(count($rows)) { //If some recores were found,
//Replace these line with what is appropriate for your DB abstraction layer
mysql_query(“TRUNCATE TABLE $table”) or die(“MySQL Error: ” . mysql_error()); //Delete the existing records
mysql_query($sql_query) or die(“MySQL Error: ” . mysql_error()); // and insert the new ones.

print ‘Successfully imported ‘.$row_count.’ record(s)’;
} else {
print ‘Cannot import data – no records found.’;
}
}

Thanks bin-co.com for writing such infomative Articles

Using PHP Short Tags

PHP Short Tags refers to ‘

Short tags are considered bad because they are in conflict with XML’s open tag – ‘

This problem can be solved easily – I use this code…

xml

I use the full tag almost all the time. The only exception is that I use . And I am not prepared to give that up.

I follow the MVC pattern in my projects. My PHP framework, iFrame, is an MVC framework. In the template(view) part, there is a lot of usage of such tags. It is more concise and more readable than the alternative…

You tell me – which is better?

I hear that they will be introducing in PHP 6. Until then, I will continue to use .
This article is from bin-co.com. IT was very usefull for me

Convert PHP arrays to JSON

While we are working with json arrays or calling ajax files that return json in their response sometime we stuck for making json array.
This is because the json array is quite difficult to maintain. You must have to take care of each every special character that is really very difficult if you are thinking to do it manually like “CDATA” for xml.
The best solution that i got from “bin-co.com” is to just make array of PHP and convert it into JSON by using user defined PHP function.

Usage

First you need a PHP array. For example…

$data = array(
‘success’ => “Sweet”,
‘failure’ => false,
‘array’ => array(),
‘numbers’ => array(1,2,3),
‘info’ => array(
‘name’ => ‘Binny’,
‘site’ => ‘http://www.openjs.com/’
)
);

Provide this array as the argument of the array2json() function…

$json = array2json($data);

The resulting string will be(actual output – the source says print array2json($data);)…

{“success”:”Sweet”,”failure”:false,”empty_array”:[],”numbers”:[1,2,3],”info”:{“name”:”Binny”,”site”:”http:\/\/www.openjs.com\/”}}

Code
function array2json($arr) {
if(function_exists(‘json_encode’)) return json_encode($arr); //Lastest versions of PHP already has this functionality.
$parts = array();
$is_list = false;

//Find out if the given array is a numerical array
$keys = array_keys($arr);
$max_length = count($arr)-1;
if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length – 1
$is_list = true;
for($i=0; $i
if($i != $keys[$i]) { //A key fails at position check.
$is_list = false; //It is an associative array.
break;
}
}
}

foreach($arr as $key=>$value) {
if(is_array($value)) { //Custom handling for arrays
if($is_list) $parts[] = array2json($value); /* :RECURSION: */
else $parts[] = ‘”‘ . $key . ‘”:’ . array2json($value); /* :RECURSION: */
} else {
$str = ”;
if(!$is_list) $str = ‘”‘ . $key . ‘”:’;

//Custom handling for multiple data types
if(is_numeric($value)) $str .= $value; //Numbers
elseif($value === false) $str .= ‘false’; //The booleans
elseif($value === true) $str .= ‘true’;
else $str .= ‘”‘ . addslashes($value) . ‘”‘; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Object?)

$parts[] = $str;
}
}
$json = implode(‘,’,$parts);

if($is_list) return ‘[' . $json . ']‘;//Return numerical JSON
return ‘{‘ . $json . ‘}’;//Return associative JSON
}

This article is taken from http://www.bin-co.com/php/scripts/array2json/

source:stackoverflow.com
Hire Me
Follow Me!
Search
Most Popular Articles & Pages
Because your vote is Important
Sorry, there are no polls available at the moment.
Categories