Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, April 4, 2012

Downloading files using PHP

Put the file you wish to download in your website directory. Example:
/file.rar

Now when you want to download it just go http://mysite.com/file.rar

It's that simple, don't over complicated it and you don't need PHP. Yesterday I tried to figure out how to download files but ran across all kinds of complicated methods. Using HTTP heaters, download helper; force_download in codeigniter, and PEAR. Maybe the reason I had such a hard time finding the solution was because its too obvious. Shot! I personally missed it.

Wednesday, February 29, 2012

Programming Languages Comparison

Programming languages are alike. If you know how to program in one language changes are you know how to program in other languages. However the only difference is the syntax. I always wanted a chart that showed this and I finally found it hyperpolyglot.org.

Saturday, January 7, 2012

SimpleXML, Birds Eye View

XML is always been a pain to me. The way I learn the best is by looking at examples. Below is a script from a project that I was recently working on using php SimpleXML object. It shows an organize format of the XML file to serve as a road map


<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie page="0" numpages="38">
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;



//Output
$xml = new SimpleXMLElement($xmlstr);

echo '<pre>';
print_r($xml->movie);
echo '</pre>';
echo 'Example:' . $xml->movie[0]->title;

?>


Script above will output


SimpleXMLElement Object
(
[@attributes] => Array
(
[page] => 0
[numpages] => 38
)

[title] => PHP: Behind the Parser
[characters] => SimpleXMLElement Object
(
[character] => Array
(
[0] => SimpleXMLElement Object
(
[name] => Ms. Coder
[actor] => Onlivia Actora
)

[1] => SimpleXMLElement Object
(
[name] => Mr. Coder
[actor] => El ActÓr
)

)

)

[plot] =>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.

[great-lines] => SimpleXMLElement Object
(
[line] => PHP solves all my web problems
)

[rating] => Array
(
[0] => 7
[1] => 5
)

)
Example:PHP: Behind the Parser

Thursday, January 5, 2012

PHP file_get_contents() error, openssl

If PHP is throwing the error below its because protocols other than http is not allowed.

Warning: file_get_contents() [function.file-get-contents]: Unable to find the wrapper "https" - did you forget to enable it when you configured PHP? in ...

To allow other protocols the php_openssl extension must exist and enabled.

To enable go to php.ini and uncomment it or if using WAMP go to the PHP folder, then PHP extensions and check php_openssl


Problem Solved.

Monday, January 2, 2012

Twilio try-out and cURL error

I was using skype and I finding it expensive. Why $30 a year for a service plus $60 for a phone number? That's $90 dollars for an voip service a year! So I went looking for other services and found twilio. I will testing in the following days.

I was testing how to send sms messages via twilio API and ran into error. Below is how I fixed it

Error1:
undefined constant CURLOPT_USERAGENT
Solution:
check your php.ini file and uncomment the line (remove ;): extension=php_curl.dll
restart your apache server.
resource:
http://drupal.org/node/1044216

Error2:
SSL certificate problem, verify that the CA cert is OK
Solution:
Added the line of code
        //this is a temporary fix for 
//Uncaught exception 'Services_Twilio_TinyHttpException' with message 'SSL certificate problem, verify that the CA cert is OK
//this may have a security flaw
//resources: https://github.com/twilio/twilio-php/issues/18 http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
$http = new Services_Twilio_TinyHttp('https://api.twilio.com', array('curlopts' => array(
CURLOPT_SSL_VERIFYPEER => false
)));
Resource:
https://github.com/twilio/twilio-php/issues/18

Monday, December 12, 2011

Turn PHP array into objects - stdClass

Want to access the contents of an array as simple as $array->firtParam

Here's how you do it

<?php
$person = array (
'firstname' => 'Richard',
'lastname' => 'Castera'
);

$p = (object) $person;
echo $p->firstname; // Will print 'Richard'
?>

Multi-dimensional array example

<?php
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}

$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
?>

<?php
$person = array (
'first' => array('name' => 'Richard')
);

$p = arrayToObject($person);
?>

<?php
// Now you can use $p like this:
echo $p->first->name; // Will print 'Richard'
?>
Reference

Wednesday, December 7, 2011

Concatenate Variables names in PHP

This is for when you want to have a variable to be part of a new variable nam

$var1 = 'category';
$var2 = 'one';
${$var1.$var2} = 'sometext';

//OR
$var1 = 'category';
$var2 = 'one';
$var = $var1.$var2;
$$var = 'sometext';

/*
this creates the var $categoryone
with with the value of 'sometext'
*/

Intergrate Zend into Codeigniter

Use Zend framework Libraries in CodeIgniter framework

click me

tags:
youtube API, GData

Friday, November 25, 2011

Autostart XAMPP in linux ubuntu

This is the simplest and easiest way to autostart automatically xampp when your computer boots

1. run the line below in terminal, this opens the file rc.local for editing
$ sudo gedit /etc/rc.local

2. write this line of code in the file rc.local. Make sure you follow the instructions contained in the file
/opt/lampp/lampp start

3. save and exit




#no need to edit init.d

Wednesday, October 19, 2011

Web Charts - PHP and Javascript

pChart.net and jqPlot.com are two different libraries that allow you as a web developer create beautiful charts and graphs.

jqPlot is a javascript library that uses jQuery. jqPlot is great because it can pull data directly from multiple mediums such as csv, txt, json and so on. However it sucks because different charts may need different plugin files and you need to make sure the right script is included, but its still simple.

pChart is a PHP libray that uses its GD library. You may need to configure your php depending if this library is installed or not. pChart is a object oriented class that creates an image of a chart on the webpage. The webpage becomes an image which will not let you output any html. The only way you can link to the chart is by using <img> or <iframe> tag. Whats great is that you can create an image that can be save but what sucks is that you may not be able to use AJAX and it takes a huge load on your CPU.

Friday, September 23, 2011

DOMDocument, accessing other sites HTML. Bypassing the Same Origin Policy

Below is a code that retrieves <a> tags from a webpage outside the server using the DOMDocument. A built in PHP class that retrieves HTML and XML from a webpage. Bypassing the Same Origin Policy. This is an alternative to cURL which downloads the entire HTML page.



$keywords = array();
$domain = array('http://bing.com');//select website to extract

$doc = new DOMDocument;
$doc->preserveWhiteSpace = FALSE;

foreach ($domain as $key => $value) {
@$doc->loadHTMLFile($value); //Load HTML from a file
$anchor_tags = $doc->getElementsByTagName('a'); //get <a> tags by accessing the DOM
foreach ($anchor_tags as $tag) {
$keywords[] = strtolower($tag->nodeValue);
}
}
echo '
';
print_r ($keywords);
echo '
';

Wednesday, August 24, 2011

Frameworks

Don't reinvent the wheel. Below are frameworks that allow you to code without having to start from scratch.

HTML - Boilerplate

PHP - CodeIgniter

CSS - Twitter Bootsrap

CSS structure - 960

Javascript - jQuery

Wednesday, August 10, 2011

Youtube Data API

Below is a PHP script that uses Youtube API through xml to show the comments on your personal website.

I didn't include any CSS.
Use this link a reference
http://code.google.com/intl/it-IT/apis/youtube/2.0/developers_guide_protocol.html

<?php

//// video id
$videoId='M1Wm9nGJcYo';

//echo the video
echo "";

// url where feed is located
$url="http://gdata.youtube.com/feeds/api/videos/$videoId/comments";

// get the feed
$comments=simplexml_load_file($url);

// parse the feed using a loop
foreach($comments->entry as $comment)
{
echo '
'. $comment->content .'
'. $comment->author->name .'
';
}



?>

Monday, August 8, 2011

.inc vs .php file extention

.inc stands for include.
Some may prefer to name their file page.inc when using the php function include() because it looks prettier.

include('page.inc');

page.inc or page.php both work the same way.

I would stick with the .php extension instead of the .inc extension because the difference is that the .inc is easier to identify when navigating through files in website directory. It has security issues because if positioned in the wrong directory it will not be parse as php by your host if opened directly, making you code readable. But when you have a .php extension php is parsed and the code is not shown to the outside.

Saturday, July 30, 2011

jQuery $.ajax and $.post

Below is an ajax jQuery code that allow uses for POST. Communication between two pages.

$.post is a simpler version with less features than $.ajax. In the code below they are both configured to do the same concept.






mouseover me Type in box to see ajax

Monday, July 25, 2011

How to redirect

Below are examples on how you can redirect your website. When someone visits your site and you want the traffic to go somewhere else. Choose your language, modify url and copy and paste.

Javascript:

<script>
location.replace("http://baligena.com") //or
location = "http://baligena.com";
</script>


PHP:

<?php
header( 'Location: http://www.baligena.com' ) ;
?>


HTML:

<meta HTTP-EQUIV='REFRESH' content='0'; url='http://www.baligena.com'>

Wednesday, July 20, 2011

Working with .htaccess

What is .htaccess:
.htaccess (hypertext access) is the default name of a directory-level configuration file that allows for decentralized management of web server configuration. -Wikipedia

.htaccess is a way to modify the web server without editing the Master file.

In Apache the master file is called httpd.conf

How to create 404 and 403 pages:
404 pages appear when it doesn't exist (alternative to index.html in every directory on site) and 403 is a page exist but is forbidden to access.

In order for .htaccess to work you need to configure httpd.conf
AllowOveride must be set to All. See below. Remember its case sensitive. For some reason apache ships as "all" instead of a capitalized "All".

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All

What to put in .htaccess:
ErrorDocument 404 /yourerrorpage.html
ErrorDocument 403 /yourerrorpage.html

# Options -Indexes is what allows the 403 error to work
Options -Indexes


If you don't want to use .htaccess you can simply put
ErrorDocument 404 http:yourerrorpage.html
ErrorDocument 403 /yourerrorpage.html

Warning: Make sure you always restart Apache when changes are made to the httpd.conf because the changes won't be taken into effect until you do

You must edit httpd.conf at the server, you can't use ftp unless it's not secured. It should be located at /etc/apache2/httpd.conf



How to rewrite URLs?
To manipulate your links like transfroming ?name=page&URL's into /friendly/cute/links
you must activate rewrite_module in Apache.

Left click on the wamp icon then hover over "Apache" and go to "Apache Modules" and click on rewrite_module (or mod_rewrite) so it has a check. (or 500 Internal Server Error may throw)

or open httpd.conf and uncomment(remove #) the line below
LoadModule rewrite_module modules/mod_rewrite.so

Wait for Apache to restart.

In .htaccess insert this code:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) mvc/index.php/$1

------or-------

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

More information:
http://corz.org/serv/tricks/htaccess2.php

Good MVC clean URL video


_________________________________________________
Ubuntu sever 11.10
Now the mod rewrite is a little different in the Ubuntu server. You have to create a "rewrite.load" symlink from /etc/apache2/mods-available to /etc/apache2/mods-enabled by running:
$ sudo a2enmod rewrite
then edit:
$ sudo nano /etc/apache2/sites-available/default
and make line 11 to AllowOverride None to AllowOverride All, see snippet below

<Directory /home/marko/public_html/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>


then restart apache:
$ sudo service apache2 restart

reference: http://www.techytalk.info/enable-apache-mod_rewrite-on-ubuntu-linux/


description: mod_rewrite wamp, .htaccess issue (500 - Internal Server Error), .htaccess apache mvc configuration 500, redirecting and rewriting

Monday, June 13, 2011

Sort an Array of Arrays in PHP

Want to know how to sort the code below by [name]?
Click me to navigate to the tutorial.
Array
(
[0] => Array
(
[id] => 1
[name] => Rob
)
[1] => Array
(
[id] => 4
[name] => Ultimate
)
[2] => Array
(
[id] => 8
[name] => Dog
)

eg:
//for array
function views($a,$b){
return strnatcmp($a['name'], $b['name']);//to reverse the sort swap the variables(letters)
}
//for stdClass object array
function viewsObj($a,$b){
return strnatcmp($a->name, $b->name);
}
usort($result,'views');
echo '
';
print_r($result);
echo '
';

Sunday, June 12, 2011

Adding Syntax Highlighting to Blogger

Do you want to show code on your blog like I'm doing below? Click Me to see instructions.

<?php 
echo "hello world";
$ball = "ball";
?>