veedeoo 474 Junior Poster Featured Poster

Hi,

I was a big fan of all of these MVC frameworks in the past, but the more I tried to write something based on them, the more time I spent on learning how to get around their restrictions. Unlike CI, the CAKE is not that js friendly, while symfony allows ajax and js integration flawlessly.

Here is a link of a tutorial on how to pass data from the controller to javascript files, and I hope this will help you.

good luck to you.

veedeoo 474 Junior Poster Featured Poster

Hi,

Did you read the Zend API Documentation on figlet? The answer to your question is right on the page.

veedeoo 474 Junior Poster Featured Poster

:) It looks like an order to me.

@siddharth.dixit.5243 WELCOME TO DANIWEB. You will have to learn how to write your questions properly. All people here are volunteers. We don't expect people to give us back those favors, but we do NOT expect people to give us orders. We give response solely under our own prerogative.

properly written question,

I am new to PHP language and I really need an expert guidance on how to write a foreign currency  converter script ASAP.

You can post the same question in this forum and you will be surprised how many people will even write it for you.

poorly written question,

Write me a foreign currency converter script ASAP.

If someone helped you, the most positive response is

Thank you very much for taking your time in responding to my questions.

The more negative response that can get you strangulated at times.

Well, after reading much about the topic online, I found out that your proposed sulution is not the right way.

I have seen this type of feedback from many posters. If they don't like the proposed sulutions, they must keep it for themselves. The right thing to do is always be thankful for any suggested solutions. Besides, it is free while the time spent by the experts is their own free time.

In response to your order ( or whatever you intended it to be), there is a google API for this. If you don't have any …

veedeoo 474 Junior Poster Featured Poster

Here is my suggestion. Please examine how the tables are constructed and their relationships. They are related on two things course section and studentID.

table for the members , can accept students or proffessors

table name: members
columns:
id = auto-incremented
username
password
type = student->001, professors->007
studentID = unique for student ONLy.
year = school year
terms = semesters .e.g. fall, spring, winter, summer etc.
status = true or false .. this to filter if the student is enrolled or not
courses= This is should be the integer of number of courses the student is enrolled on current term. You must increment this by the number of courses, when the student confirmed enrollment.

Table name: courses
columns:
c_id = auto incremented
c_name = course name
c_desc = course description
c_section = course section
c_term = course semester offerings
c_max = maximum number of students this course allows to be enrolled at any given time

Table name: current_enrollement
columns:
e_id = NOT auto-incremented must be equal to the c_id in the courses table
e_section = course section where students are enrolled
e_studentID = student id of the student enrolled in this class
e_coursetitle = title of the course equal to the c_name in the courses table

Table name: grades
columns:
g_id = auto incremented
g_courseId = equal to the c_section in the courses table

LastMitch commented: Very Detailed Explanation! +9
veedeoo 474 Junior Poster Featured Poster

Hi,

You can echo them in single line. Use single quotes to eliminate the extra efforts on escaping the double quotes.

Something like this

echo '<img src="'. $row['ImagePath'] .'" alt = "Country Music Nightclub Orlando" title="'. $row['ArtistDate'] .'" /> </a>';
veedeoo 474 Junior Poster Featured Poster

There are PHP predefined variables called $_SERVER. This may help you.

I would look into the following variables

    HTTP_HOST
    HTTP_REFERER

There are plenty of resources online on how to implement this. I just don't have the time today to test it, but if ever you will not be able to find something, please let me know and I will write you the codes if needed.

The second option is making a minor changes on your API specifically on the GET request. So the remote site will have to add piece of codes to their requesting script.. for example, if your API accepts request like this

yourSiteDotCom/api/search?q=something

you can ask them to add something like this

$theirDomain = $_SERVER["HTTP_HOST"]; 

## the new query for sending an API request to your site

yourSiteDotCom/api/search?q=something&rsite=<?php echo $theirDomain;?>

On your API application, you can add simple codes like this

    if(isset($_GET['rsite'])){
    ## this is the domain name of the requesting remote site
    $remotSite = $_GET['rsite'];
    ## we need to clean this up and validate, and make sure it is a valid url
    if(filter_var($remoteSite, FILTER_VALIDATE_URL)){

    ## do what you need to do e.g. like adding it to your database

    }

    }
    ## allow other request from other site to get process.
    ## or you can use the PHP variables I have suggested above.
veedeoo 474 Junior Poster Featured Poster

Hi,

Try this..

    $password = md5($_POST['oldpass']);
    $newpassword = md5($_POST['newpass1']);
    $confirmnewpassword = md5($_POST['newpass2']);

plese try if it work, if it does let us know.

RaeesIqbal commented: thanx, it was a problem also. +0
veedeoo 474 Junior Poster Featured Poster

May I ask the OP, when you envision developing this site, did you write a barebone flowchart as to which file will include which one?

The reason I am asking is that, in a project of this size, there should be a file manager. For a much bigger one, there is file called director to direct all include and require requests of the scripts. Without these methods, it will be pretty hard to track down which files is needing another files.

A file manager is like a location map of your site. Similar to the one we see at the shopping complex. So, if page1.php needed to include page2.php, then page one must include the filemanager.php first, and include the page2.php. filemanger.php will take care of finding the page2.php. This is a common practice used in MVC framework and OOP.

Here is a simple filemanger-definition file based on Diafol's observed structure.

 ## not necessarily the first one, but let's define the directory separator
 define('DS', DIRECTORY_SEPARATOR);

 ## define the root directory where your script is going to run
 define('ROOT', dirname(__FILE__));
     ## define root directory files that will be included by another files
     // for example if the register.php is going to be included by another file, then it can be define as this
     define( 'REGISTER_FILE', ROOT.DS .'register.php' );

 ## define location of your includes directory
 define('INC_DIR', ROOT.DS .'includes');
     ## define files in include directory
     define('HEADER_PAGE', INC_DIR.DS .'header.php' );
     define('LOGIN_INC', INC_DIR.DS .'login.inc.php' );
     // add the rest of your files 
veedeoo 474 Junior Poster Featured Poster

ok, I tried them and other IP's I found on other sites with similar service, but for some reason cURL would fail most of the time.

For the random IPs above, I've got 2 dead ones and one 403 with redirection. Codes I used is the same as your code above except I added this..

    curl_setopt($ch,CURLOPT_HTTPPROXYTUNNEL, 1);

We can also check if the cURL is reading something by passing the fetched data to a PHP function called stripos or even better pregmatch.

    if (preg_match("/html/i", $data)) {
        echo 'IP is alive';
} else {
    echo 'IP is dead';
}

## I have seen some other guys do it like this

  $countX = stripos($data,'</html>');   
  if($countX > 0 ){

  echo 'It is alive';

  }

  else{

  echo 'Not available';

  }

There is a class written by Stanislav in PHPclass.org that looks pretty promising. Another one is written by Alexey , this may need minor work, but it is looking pretty good because of the Ping functions, instead of sending the cURL right away.

UPDATE: I forgot mention there is a PHP exec that can be very helpful in knowing if the IP is alive or not. If you run this code..

        function GetPing($ip=NULL) {
             if(empty($ip)) {$ip = $_SERVER['REMOTE_ADDR'];}
             if(getenv("OS")=="Windows_NT") {
              $exec = exec("ping -n 3 -l 64 ".$ip);
              return end(explode(" ", $exec ));
             }
             else {
              $exec = exec("ping -c 3 -s 64 -t 64 ".$ip);
              $array = explode("/", end(explode("=", $exec )) );
              return ceil($array[1]) …
Resentful commented: Awesome solution! +1
veedeoo 474 Junior Poster Featured Poster

Sorry, I have to remove it my response. I think you already got it sorted out..

veedeoo 474 Junior Poster Featured Poster

ok, this is what I found out. This is what my brother Michael told me, and hes is working for the big G. What he told me "when there is a remote application accessing the atom, from unknown IP address, google will throw 401."

If you are getting this 401, all need to do is log-in to your gmail account. Look on top of the page for the red bar notification. The notification will say "Someone is trying to access your account from ....", What you could do at this point is to click on the red bar, and then if you recoginized the IP address to your server's IP in which the application is located, you have an option to allow it. This is just like a twitter OATH class.

Now, the dreaded security issues. Make sure no ONE BUT YOU have the access to your cURL script. The reason is that your password is exposed in plain text. I will not do this in shared hostings, unless I am pretty much aware of who are the other people currently hosted in the same very server, where the cURL script is running.

veedeoo 474 Junior Poster Featured Poster

If the site is requiring you to have cookies, then we can create a directory named tmp, this should be adjacent to your curl script.

    ## first we define a directory where to temporarilty store it

    $cookieDump = tempnam("tmp/", "cookies");

Now, add these to your cURL codes

curl_setopt($ch, CURLOPT_POST, 0); // Set this to 1 is it is a POST method
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieDump);
## is the target server host uses SSL layer?
## turn these to true or false and false is 0
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

If it does not work, try looking into the post data cURL function.

PHP code reference http://php.net/manual/en/function.tempnam.php

veedeoo 474 Junior Poster Featured Poster

@kashifbhatti,

You mean to say that the format process only took five seconds? If it is, then you have a better chance of recovering your data. The reason data can be recover during quick format is that the data are not being overwritten.

You must try the gparted tutorial.

veedeoo 474 Junior Poster Featured Poster

Here is another one for you, it is called testDisk.

veedeoo 474 Junior Poster Featured Poster

Do as suggested by caperjack, and then on another computer boot from CD with a live copy of gparted, and then attempt to follow this instructions.

Another option that you may have is to use a software called GetDataBack . However, this application may only work (NOT guarantee), if you quick formatted the hard drive, you may still have chance, but for a normal formatting ( this is a complete overwrite), I could see the chance of getting your data back is pretty slim to none.

People who are trying to experiment with dual boot, should use gparted to create a new partition and then install the second OS to the newly created partition, but then installation question like installing it along the existing OS or replace the existing OS should be watched closely.

The tutorial is for the bad partition, but you still it is worth trying. Goog luck to you.

veedeoo 474 Junior Poster Featured Poster

Ooops, My apology about that, I just got bored and I thought It would be nice if I show people how to do it. It is not a mandatory type of thing. I always believe, people should explore outside the box to be able to discover their maximum potential. I don't know, it's probably just me who think this way, and the rest fell in love in the cookie cutter type of uniformity. I like multitude of ideas that comes in different types and shapes without bounds.

But then, If you guys noticed the link I have provided on my first response, those are the links of all the plugins for embedding videos.

veedeoo 474 Junior Poster Featured Poster

Hi,

Please allow me to post another response.. I got bored reading some of the questions, let me evive this thread. Maybe we can learn something from this. Most importantly on how the wordpress plugins work.

Two years ago, I can pretty much write what I like to do with my wordpress. However, that was in the old version. I have a newer version, but I never bother writing plugins for my own use.

Writing a wordpress plugin is not that hard. As long as you follow what the codex instructions.

I will attempt to create a simple shortcode function plugin that will embed a youtube video on your wordpress article.. Yes, right here in Daniweb.com and right now :)..

First step: Creating a shortcode function is the easiest one in wordpress. Here we go, our simple youtube embedder shortcode.

save this file as ytembedder.php

    <?php 

       function AddYoutube($params = array()){
           extract(shortcode_atts(array(

             'vtitle'=>$vtitle,
             'vid' =>$vid,
             'width'=>$width,
             'height'=>$height), $params)
            );

       $youtube = '<iframe width="'.$width." height="'.$height.'" src="http://www.youtube.com/embed/'.$vid.'" frameborder="0" allowfullscreen></iframe>';

        return $youtube;
        }

        add_shortcode('vid', 'AddYoutube');

Save ytembedder.php inside your default theme dirctory.

  1. Open your default theme directory, and then find functions.php. Load this file to your editor. and add this code somewhere in the page,

    include_once('ytembedder.php');

but I prefer to add it on top section

  1. Save your changes..

  2. To add embedded video your post, just add the short code like this

     [vid vid=Vo_0UXRY_rY  width=580 height=380 vtitle=testing]
    

    Explanation:

    always start with vid followed by vid=YoutubeVideoId , width=PlayerWidth height=PlayerHeight …

veedeoo 474 Junior Poster Featured Poster

Hi Diafol,

For the fullscreen, the colorbox event assignment to element example7 ( as defined on my demo) it was set to

        $(".example7").colorbox({width:"75%", height:"75%", iframe:true});

I just changed the % values for both width and height to 100%. :) pretty neat huh?

We can also load jwplayer on the colorbox just by referring to the player.swf and the youtube video id, but I got an email from google 6 weeks ago telling me that I cannot distribute anything that loads youtube videos on different player. I guess its fine for me to show demos in the google API community but cannot distribute.

veedeoo 474 Junior Poster Featured Poster

I am pretty sure this is what the book is talking about.(Basic constructs). Not the same constructor, I thought it would be..

It should be called control structures..

veedeoo 474 Junior Poster Featured Poster

check if your colorbox.css and jquery.colorbox.js exists. to use colorbox for youtube videos the href format should be like this

    <a class='youtube' href="http://www.youtube.com/v/Vo_0UXRY_rY" >

Here is a demo, please feel free to look at the source code. Please DO NOT make a direct link on my js and css files. That is all I am asking..

To add title on the colorbox, you will have to add title attribute to the link, like this

<a class='youtube' href="http://www.youtube.com/v/Vo_0UXRY_rY" title="This is Title">
veedeoo 474 Junior Poster Featured Poster

Let me add something, because I just noticed you are using mysqli, so the php.ini file settings for the mysqli should be something like this

    ;this is the entire site using mysql 3 for three seconds time out in seconds. If you have other applications running on the native mysql, then increase this to the number of seconds you want before timing out. -1 is no timeout at all.

    mysql.connect_timeout = 3

    ; by the way this -> ; is how you comment on the php.ini file

    ;for the mysqli settings,
    mysqli.max_persistent = -1
    ; Maximum number of persistent links.  -1 means no limit.
    ; http://php.net/mysqli.max-persistent
    mysqli.max_persistent = -1

    ; Allow accessing, from PHP's perspective, local files with LOAD DATA statements
    ; http://php.net/mysqli.allow_local_infile
    mysqli.allow_local_infile = On

    ; Allow or prevent persistent links.
    ; http://php.net/mysqli.allow-persistent
    mysqli.allow_persistent = On

    ; Maximum number of links.  -1 means no limit.
    ; http://php.net/mysqli.max-links
    mysqli.max_links = -1

    ; If mysqlnd is used: Number of cache slots for the internal result set cache
    ; http://php.net/mysqli.cache_size
    mysqli.cache_size = 2000

If you want to make sure that the short tags is allowed on your server change this value

    ;short_open_tag = Off

to this

    short_open_tag = on

If you want to write your php codes with ASP opening and closing style, for example these

    <?php

    echo "hello";

    ?>

Can be written also as and the php handler will parse this..

    <% …
veedeoo 474 Junior Poster Featured Poster

You may want to check the values assigned to max_input_time, max_input_vars, memory_limit, post_max_size , max_execution_time. You can either change the values of these items in WHM panel under domain management or account management. However, if you would like an independent changes for each domains hosted in your VPS server, you can changed them by adding a new php.ini file in the root of the domain executing the script in question.

Before we can change anything, we need to know the Server API of your server and the Loaded Configuration File (php.ini). Create a new document and save as info.php, paste codes below unto this document

<?php

phpinfo();

?>

Upload the info.php to your server. Direct your browser to this page. Look for the values of Server API and the loaded configuration file. Once we know the location of the loaded configuration file, we can change the values as required by your script.

  1. You can either access this via black box or terminal just by typing (terminal only)

    sudo -s
    ## type in your password
    ## then type gedit or whatever is the installed editor on your server
    cd location of your loaded configuration file
    v /location of your loaded configuration file/ 
    

Or, if you have a windows desktop, then you will need a free SSH program called Putty. Open putty, and log on to your remote server.. I believe we can do this on putty

    cd /directory of your loaded configuration file normally it is etc/ …
veedeoo 474 Junior Poster Featured Poster

Hi,

On your vps account, what do you have? WHM panel ? or something else?

What is your setting value for

    mysql.max_persistent 

You can read more of the most common settings here. Anything where it says php_ini system under changeable column can be adjusted or changed on your servers loaded configuration file. loaded configuration file can be found by running

phpinfo();   
veedeoo 474 Junior Poster Featured Poster

Hi,

Thanks for the kind message. Yes, try it. The above cURL script should be functional. I was using it for a long long time, including remote age verification, paypal authentication and some other things.

As an alternative, you can also do API ajax response if it is available from the remote site as what pritaeas suggested. If API or rss feeds is available, it should be the right choice than using cURL.

veedeoo 474 Junior Poster Featured Poster

@Mitch,

It could be just a url stuff and nothing serious. If you could output the other data off from the same file, maybe it is just the directory reference mishaps. Did you try

    ../images/

On your image's src?

Back to the case of smarty's iteration function.. I totally agree with all of you. I have no problem digesting whatever is posted here. Except for the odd implementation on the constructor.

For the template, LastMitch implemented the section loop instead of the foreach loop. So, it is pretty much capable of what the foreach can do.

    {section name=tbl loop=$book->title}

I preferred using dot notation though as much as possible, but it just only me :).

LastMitch commented: Yes, it was the URL all along +9
veedeoo 474 Junior Poster Featured Poster

WARNING! It is not my intension to promote any unauthorized content parsing. By using the script I have provided below, you are responsible for any copyright violations and damages it may caused.

Knowledge is Power, but it can also destroy many things, if the probable consequencies are not evaluated, before hand.

Remote Server form structures
Let say, the remote site have a form structure like this

<form action="remoteProcess.php" method="post">
<input type="text" name="first_name">
<input type="text" name="last_name">
<input type="text" name="roll_number">
<input type="submit" name="submit" value="submit">
</form>

Assuming that the remoteProcess.php" will return "records not available" on all faults, and return something if roll_number is valid one.

On your Server

This simple cURL implementation can parse the remote response to your site.

## first you need to process your own form in your site.
if(isset($_POST['submit'])&&(!empty($_POST['fname'])) && (!empty($_POST['sname'])) && (!empty($_POST['roll_number']))){

## You must add more form filtering before sending it to the remote site.
## if all is well, prepare your data for remote trasmission using cURL

## define remote form processor script
$location = 'http://remoteSite.com/remoteProcessor.php';
## define your user agent
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $location );

$post_array = array(
    "first_name"=>preg_replace('/[^a-zA-Z0-9 ]/s', ' ', $_POST['fname']),
    "last_name"=>preg_replace('/[^a-zA-Z0-9 ]/s', ' ', $_POST['sname']),
    "roll_number" => $_POST['roll_number'],
    "submit" => "submit"
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array); 

## grab the response from the remote form processor
$response = curl_exec($ch);

## …
veedeoo 474 Junior Poster Featured Poster

Here is a simple example of joins. I could have written this in shorthand form, but I will do it in long haul to make my points a lot clearer.

Say, we have a table called students, and on this table we have id, name, username, password, email, course_num, and status columns.

+-----+------+----------+----------+-------+------------+----------+
+ id  + name + username + password + email + course_num + status   +
+-----+------+----------+----------+-------+------------+----------+
+ 100 + name + user     + pass     + @home + 300        + enrolled +
+-----+------+----------+----------+-------+------------+----------+

Another table called courses is also in the same database, and it also have the following columns course_id, course_name, instructor,term, year. course_id is not auto incremented.

+------------+-------------+-----------+------+-------+---------------------------------------------+
+ course_id  + course_name + instuctor + term + year  +               bio                           +
+------------+-------------+-----------+------+-------+---------------------------------------------+
+ 300        + physics     + veedeoo   + fall + 2012  + The youngest professor ever walked on earth +
+------------+-------------+-----------+------+-------+---------------------------------------------+

!NOTICE? the only columns that have common value between these two tables are the course_num and course_id.

Scenario 1: The student log in ( of course another page does the validation), we will show this student of the classes he or she is enrolled. Including the course name, course id, the term and the year of enrollment.

The mysql database query: For even more clarification, I will write the main Key of the query in uppercase. I hope other readers will not take that against me.

   $this_query = "id, name, course_num, status, course_id, course_name, instructor, term, year";
   ## Notice the above …
LastMitch commented: Well Explain! +7
veedeoo 474 Junior Poster Featured Poster

Hi Diafol,

Yes, all of them have a really bad documentations. I am really fascinated by what this little template engine TBS could do. I experimented on it for a few weeks, and it is not that hard to get familiarized with how they do things.

I also experimented with the contents coming from the database, and I don't have to do any loops at all.

What is so interesting about this template engine is that it has its own hook ( some people call it binding capability) to mysql, mysqli and I think it can do PDO also.

For example, if we are to fetch some contents from database, the TBS php code can be as minimum as this... this is on the php file side. I love writing them in simple function for easy implementation later on.

    ## function db_connect

    function db_connect($db_host, $db_user, $db_password, $db_database){

    # connect to our databse Use the example below.
    $this_connection = mysql_connect($db_host, $db_user, $db_password);
    mysql_select_db($db_database,$this_connection);

    ## we need some simple boolean response
    $sql_ok = ( isset($this_connection) && is_resource($this_connection) ) ? 1 : 0;

    if ($sql_ok==0) $this_connection = 'clear'; 
    ## this makes the block to be cleared instead of merged with an SQL query.

    ## connection is valid we return it for other fucntion to use
    return $this_connection;
    }

    ## we can directly assign the results to our template using the block function or merge block function
    $query = "select title, description, id from content";

    $Veedeoo->MergeBlock('blk2', db_connect( 'localhost', 'username', 'password', 'password'), $query);
diafol commented: Thanks for the heads up. +14
veedeoo 474 Junior Poster Featured Poster

Hello Everyone,

I got bored reading PHP questions. So, this is probably the best time to add another article here at daniweb.com. If someone ever stumbled upon by boring blog (mini-tutorial), I talked about how light and simple is the tinybutstrong templating engine. However, I began to wonder why not too many people are using it.

Months ago, I went to their site and read their implementation and I finally answer my own question. The reason most people would ignore the validity or the existence of tinybutstrong is that, until now they are using the tables instead of div on their example of implementation. So, I guess it is safe to say that developers and designers these days does not have anything to do with tables, UNLESS, it is deem necessary :).

Why is TinyButStrong, a good template engine?
I am confident it has potentials. However, it is and can be powerful as any BIG template engines available out there .. can be considered somewhere just below twig and smarty. What makes it good is that it has one 1 Php class with 6 methods and 5 properties. This one file makes it a templating engines runner up :).

How do we use TinyButStrong?
Please read tutorials below..

First Step: Download the tinyButStrong here. Unzipped this file and move the tbs_class.php to your working directory.

Second Step: In your working directory (server of course), create a new dirctory called 'templates'.
Thirs Step: Copy and paste …

LastMitch commented: Thanks for sharing! +7
veedeoo 474 Junior Poster Featured Poster

here is another one... :).

<?php

$string = 'abcd_23$_&';

if(!preg_match('/^[\w-]+$/',$string)){

echo 'oops! not a valid username';

}
else{

echo 'Valid Username'. $string;


}
veedeoo 474 Junior Poster Featured Poster

Here is the extended response proving both of the responses above :) are true.

<?php

function check_bool($value){

return ($value == 1 ? 'yes' : 'no');

}

$value = true; // this can be from database

## let us test the function above.

echo 'This shows a true value : <b>'. check_bool($value) .'</b><br/>';

echo 'This shows a false value : <b>'. check_bool('false') .'</b><br/>';

echo 'This given the value of 1 : <b>'. check_bool(1) .'</b><br/>';

echo 'This has value of 0 : <b>'. check_bool(0) .'</b><br/>';

echo 'This has value of "1" : <b>'. check_bool("1") .'</b><br/>';

echo 'This has value of "0" : <b> '. check_bool("0") .'</b><br/>';

echo 'This has an empty value : <b> '. check_bool(" ") .'</b><br/>';


## another way of utilizing the above function can be something like a comparator seen in c or java not like it, but serves like it ( now, I am confused which one is it really ???) :)

echo (check_bool($value) == 'yes' ?  '<b> Yes is the answer </b>' : 'No Way' );
diafol commented: show off! :) +14
LastMitch commented: Good Job! +7
veedeoo 474 Junior Poster Featured Poster

@lastMitch,

Here is an extremely simple example of inheritance where both the parent and the child has its own constructor.

Looking at the code, the parent does not even know that the child class exist. Only the child knows that the parent class exist.., and yes we don't have to let the parent knows whatever methods is being use by the child.

<?php

class Person{
        ## please pardon my shorthand approach. Normally, variable below are itemized for clarification.
        private $name,$lastName,$age;

        ## in older version of php, var was used instead and the constructor is not included. 
        ## However the first method should be named after the class name as in function Person().

        // var $name,$lastName,$age;
        //public function Person(){  return $name; }


        ## this is the constructor for the class Person 
        public function __construct($name,$lastName,$age){
            $this->name = $name;
            $this->lastName = $lastName;
            $this->age = $age;

        }

        public function get_name(){

        return $this->name;
        }

        public function get_info(){

            ## simple example of using another method of a class within another method within class ??????? :)
            return array($this->name,$this->lastName,self::get_age() );

        }

        public function get_age(){

        return $this->age;

        }
}

## extending the class Person above, child class can inherit all the properties of a parent class

class Info extends Person{

        ## this child class will inherit all the properties of the parent class.
        ## we can create a consructor here for this child class, and at the same time, must invoke the parent's constructor.

        public function __construct($name,$lastName,$age,$job,$hobby,$salary){

                    ## envokes the parent constructor
                    parent::__construct($name,$lastName,$age);

                    ## we only define things that …
veedeoo 474 Junior Poster Featured Poster

I love both of them, depending on application requirements. There is a neglectable performance differences between the two. MySQLI is somewhat faster than the PDO... however like what Pritaeas already mentioned, PDO can function and work in different environment.

One specific reason out of all other reasons, why I would also prefer PDO is that it can take an instance of a class and use it as the parameter on its query, this is called PDO fetch class . This functionality is perfect for applications requiring the implementation of a templating system like the smarty, dwoo, twig, tinybutstrong, and others. Although, it can be use in tinybutstrong environment, I prefer to use the built-in tinybutstrong database interface.

For example, say we have a class called rockStars ( Why some geeks adore rock stars and rock stars wishes to be a geek at some point of their lives?? wow! I can trade places at any time)..

  class RockStars{

  public function get_RockStars($name,$band,$cd){

  return array($name,$band,$cd);

  }
  }

 $thisPDO = $db->prepare("SELECT name, band,cd FROM rockstars");

 $thisPDO->execute();

 ## grab the output array and send it to the template engine or just loop over it

 ## for the template
 $smarty->assign('rockStars', $thisPDO->fetchAll(PDO::FETCH_CLASS, "RockStars"));

 ## you can loop through the result below as you wish
 $this_PDO_result = $thisPDO->fetchAll(PDO::FETCH_CLASS, "RockStars");

That's all I can say on this subject matter... performance wise? MYSQLI got a meniscule upper hand, but PDO supports named_parameters and supports many different database.

veedeoo 474 Junior Poster Featured Poster

I totally agree with jmaat7.. I also have xampp and eclipse on a flashdrive.. I even have the static ffmpeg to work with the ffmpeg-php in my thumb drive.

My portable eclipse is a portable eclipse php version can be downloaded by Clicking Here. I saved about 50MB of space..

It is working pretty well without any issues, but if you will be working on smarty templating system, make sure to ignore the errors and warnings being caught by the eclipse from the template directory. Portable eclipse just don't have the extra module to recognize the smarty syntax. To correct this problem you may want to mock up smartypdt with the eclipse installation as you see it fit.

veedeoo 474 Junior Poster Featured Poster

let me add something, to make it a lot easier for you to grab the array output of a function without relying so much on the integer indexer, we can do it like this also;

<?php

function some_Array($name,$last,$address){
        $arrayItem = array();
        $arrayItem['name'] = $name;
        $arrayItem['last'] = $last;
        $arrayItem['address'] = $address;

        $output_Array[] = $arrayItem;

        return $output_Array;

}

$id = some_Array('poor','boy','north pole');

    foreach($id as $pos_id){

    echo 'Name: '. $pos_id['name'] .' '. $pos_id['last'];
    echo '<br/>';
    echo 'Location: '. $pos_id['address'];

    }
veedeoo 474 Junior Poster Featured Poster

@davy_yg

Why are you saying it is difficult to design it on your own? Have you tried it yet? Did you attempt to at least jot down how would your program will flow?

A part of being a coder is to be able to write codes when there is no ready made open source out there. What you want to write is not even that hard... I mean a cup of hot nicely brewed coffee (starbucks), can definitely help out to visualize how the program should react to your user's click..

Please allow me to help you build the basic core foundation of the program you are trying to achieve or make.

First, you will need a page to add the banner links of the sponsors. Make sure the destination domains of these sponsors are saved in your database.

Second, the outgoing link should be forwarded to your outgoing page to track which url or domain is being clicked. This event should executed in split second, and the browser should not be held more than a blink of an eye. In this outgoing page, you will need to update your database by adding 1 to the outbound count as the browser is being redirected to the sponsors domain.

Third, create a function of which it will be able to detect the referring url, you then match this url to your sponsors or link exchange partners to track down how many are bouncing, returning, and coming from external links to your …

veedeoo 474 Junior Poster Featured Poster

LastMitch is right on the yii framework, but then again the rest will rely heavily on how much coding experience do you have in OOP.

If you are pretty fluent in OOP concept of writing codes in PHP, then you can attempt to just write your own MVC framework.. trust me it is not that hard, once you have a complete grasp on how the model, controller, view design pattern works.

If you want to practice in mvc pattern.. it is not that I am trying to inject something here that people don't need or not PHP related topic. However, achieving a broad knowledge in writing codes cannot be achieved overnight.. of course, there are many bumps and obstacles in the process. Sometimes, we are even required to take a few steps back just to make one step forward.

My suggestion is to practice first in ASP.net environment (about 1 week), and then move on to the ASP.Net razor C#(variables, logic, and loops) (1 to 2 days), and then move on to the ASP.net MVC. Work on building a simple application and then, once you have the grasp of building an application in ASP.net MVC using C# ( believe me this is not hard and it will give you so much coding techniques experience that you can use in PHP later on).

After that, I truly believe that you can write it your own.. The advantage of writing it your own is that you can decide which plugins you want …

LastMitch commented: You should be tutoring luis_see_me! =) +0
veedeoo 474 Junior Poster Featured Poster

just to add some very important info. on your php function usage, session_register has already been deprecated and removed in php 5.4. So, if you will be writing an application based on this function, it might not work in production server of which the majority now are using php 5.4.x.

you can replace the session_register with something like this,

    $_SESSION['username'] = $username;

In addition, we can also create a session array to simplify the process and it can be coded like this

    $thisSessionArray = array($username, $privs, $item3, $item4);
    ## assign the above array into one session

    $_SESSION['user_credit'] = $thisSessionArray;

    ## or we can shorten  it by coding it like this
     $_SESSION['user_credit'] = array($username, $privs, $item3, $item4);

To use the above approach, we can assign the individual session value into constant, but it is not necessary. The idea of defining them into constant is the ease of implementation accross pages. Although not many developers would agree with me, I found it pretty useful in my projects, especially in the developement of the open source vidiscript years back ( I don't want to sound as if I am pretty old. I will be turning 20 next month, so I guess I am old.).

    ## grab the session values from the session array

    ## for username
    define('USERNAME',$_SESSION['user_credit'][0]);

    ## define the privs
    define('PRIVS', $_SESSION['user_credit'][1]);

You can create a more application friendly user table, and on this table you must have a priviledge column that will accept a numerical …

veedeoo 474 Junior Poster Featured Poster

Hi,

Try adding...

if(isset($_GET['q'])){

## codes for the script response when GET is triggered
$q=$_GET["q"];
}

else{

$q = '';

}

Alternatively, I keep on seeing this type of approach by other developers of which I have not tested or ever tried, but I think it is worth teting for any vulnerability issues and weaknesses..

 if($_GET){

 ## codes here

 }
 else{

 $q = '';

 }

Again the alternative option is just too broad for my consideration. I am just assuming here that this method can fail.

veedeoo 474 Junior Poster Featured Poster

@MB.ShadowFox, LastMitch is correct.

Since Im already typing something in response to your question, why not do it something like this. but this does not happen very often..only when my mood is good (caffeinated).

## protect your script from getting undefined index in php 5 just in case itemnumb.png does not exist.
$thisImage = '' ;

## define the directory where the image is located.. this is needed just in case you will be storing this value in the database.
$imagePath = 'SomeLocationInYourServer/images/' ;


while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['owner'] . "</td>";
## check if the image does exist
if (@file_exists($imagePath.$row['itemnum'].".png")){

## I am not really into mixing PHP and html, but I will do it this time. Maybe a templating crash course could help.

echo '<td> <img src="'.$imagePath.$row['itemnum'] .'.png"/>';
}
## if it does not exist, why not show something else put the td, to prevent the table from behaving oddly.
else{
echo '<td>No Image</td>';


}
 echo "<td>" . $row['count'] . "</td>";
echo '</tr>';
}

echo '</table>';
veedeoo 474 Junior Poster Featured Poster

Hi,

Try searching from my older posts in daniweb. I wrote at least two functional upload scripts like this, even with the image to BLOB fucntionality.

Just a friendly advice, please make sure to describe the problems first, before posting your PHP code..

andyy121 commented: ok thnx +2
veedeoo 474 Junior Poster Featured Poster

Just to add some simple ensight, the $s don't even matter it is merely a place holder, because it is there waiting for whenever the class is called upon. So, we can replace the $s = new static with

   return new static();

this class will still continue to return the instances of the classes ABC respectively, because of the hierarchy imposed on class B inherit class A and ultimately class C inherits class B.

Let us get out of the OOP conundrum for a just a few seconds, and lets take few steps back. Remember in basic PHP how we write functions? kind of something like this

    function SaySomething(){

        if(isset($_POST['submit']){

        echo 'Form submitted';

        }

        }

What is happening in the simple codes above is just waiting for the right event when form is submitted.. therefore we can place this code anywhere in the page where the processor is located.

    $s = SaySomething();

    ## or just simply use code below and the effect and response will be absulutely the same
    SaySomething();

Pretty much that if ever the SaySomething is going to be triggered by the submit button, 'Form submitted' should be showing on the page, the same is true with the $s in your class.

If the class does not have any child classes, then the class can be written like this

    class A{

        public static $instanceA = NULL;

        private function __construct(){

            ## echo ONLY for the purpose of checking the instance of this …
LastMitch commented: Nicely Explain! +6
veedeoo 474 Junior Poster Featured Poster

Hi,

This should not be too hard to do. You can start by writing a simple function to do the db insert, and then call this function or method whenever there is something to be inserted.

for example, we can create something like this..* WARNING! Script below is not tested. I just made this up to give you the general idea.*

    function insert_to_db($query,$filter,$table){
    $dbConnect = mysql_connect("localhost", "dBUserName", "$dbPassword");
    mysql_select_db($table);

    ## $filter is something that will trigger or sort types of events so that we can actually execute the query if any or one of the set condition/s has been met.
    #$db is the database connection

    if($filter = 'condition 1'){

    mysql_query($query);
    ## add your error checking and connection failed below
    mysql_close($dbConnect);

    }

    else{

    ## if you only have two $filters then else is appropriate to use. However, for multiple $filter, use else if or if else.

    mysql_query($query);
    ## add your error checking and connection failed below
    mysql_close($dbConnect);

    }

    ## you can either return it true or say something to acknowledged the transaction  OR you can return from within the if and else statements.
    return true;

    }

To use the function you will have provide the database query. Let's use the above function assuming that it has been tested and error free.

    $tableOne_query = "INSERT INTO Table_ONe(col_one, col_two, col_three) VALUES ('value_one',value_two','value_three')";

    $tableTwo_query = "INSERT INTO Table_Two(col_one, col_two, col_three) VALUES ('value_one',value_two','value_three')";

    ## now we can call our function above to do the dirty work..

    $insertTo_table_One = insert_to_db($tableOne_query,'condtion 1', 'Table_ONe');

    ## …
veedeoo 474 Junior Poster Featured Poster

Hi,

We cannot directly re-create or generate a youtube id for this matter, because youtube is using a simple yet very effective method of generating video ID. It is so simple that you already done it on your script. However, the hardest one to match is the output of something that has no alogarithm at all. It is pretty much divided into to three random arrays to create dashes, caps, lower case, and numbers. So, the randomness can be something like this generate dash,generate random 2 upper case letters, generate 2 or single integers followed by random lowercase, generate the mix of the three in random. Then this ID is then match to the database if ever exist and if it does not, that becomes a unique ID. Unlike other video sharing website e.g. p**nhub ( it is not that I like visiting this type of site, but I was envolved in developing an id snipper script for this), which is pretty predictable.

How do I know all about these? Because my older brother Michael went to school and used to work with one of the founder of Youtube way back in the early years of paypal. Inspite of the change of ownership which is now google, I still believe that the video ID generator function has not changed at all or maybe at the very minimum to this date.

The easy method I used in my demo link is to use my minified version of the youtube API class …

veedeoo 474 Junior Poster Featured Poster

Hi,

You need to run this simple script on your server

    <?php 
    phpinfo(); 
    ?>

First, look for the value of **Server API ** is it Apache module or apache handler?
Yes? You need to add this on your .htaccess file or create one if you don't have it.

    php_value upload_max_filesize 100M
    php_value post_max_size 100M
    php_value max_execution_time 1000
    php_value max_input_time 1000

No? What is it? Is it CGI or Fast CGI? If yes, create a new text document (preferrably on notepad) save it as php.ini file add codes below

    post_max_size 100M
    upload_max_filesize 100M
    max_execution_time 1000

Set your FTP program transfer mode to auto, and then upload the newly created php.ini file to the root directory of your site. Test your upload script.

Else? Contact your hosting support, and ask them to increase your upload limit and execution time for php script.

veedeoo 474 Junior Poster Featured Poster

I aplogize for the interruption. Is this what you're trying to achieved? Click Here. That's random video from youtube with at least 99.00% accuracy.. of course, the remaining 01.00% can be given to the script load error.

veedeoo 474 Junior Poster Featured Poster

Hi LastMitch,

Long time no see :). I have a few school days off.

Anyways, the form input type attributes are the following.. let see if I can them out of my head. I have not seen forms for quite sometime now.

text, hidden, submit, button, image, reset, checkbox, file, radio.. I think I missed a couple, but it is ok, you don't need it for this project.

In your case, the input type attribute will be text. So, in your codes above, we can change it to

    <form action="photoimage.php" method="post">
    Photo: <input type="text" name"" valve=" />
    <br />
    Caption: <input type="type" name"" valve="" />
    <br /><br />
    <input type="submit" name="submit" value="Submit" /><?php echo $msg; ?>
    </form>

Let me re-read my previous post on the link provided above. Normally, I don't remember codes I wrote, because I wrote them as I type my response.

LastMitch commented: Nice answer +2
veedeoo 474 Junior Poster Featured Poster

simple explantion on what is going in the server once the upload.php is submitted.

  1. PHP will save the files in the tmp directory. This is above the public directory e.g. public_html or htdocs.

  2. Once the files has been uploaded successfuly, the process.php will then execute the

    move_uploaded_file($_FILES['ufile']['tmp_name'][0], $item1);

coding convention of move_uploaded_file

 bool move_uploaded_file ( string $filename , string $destination )

**layman's terms **

MoveThisUploadedFile('FromTempFileDir/tempName','ToUploadsDirectory/AsNewFilename.WithTheExtensionOfTheFileAsAllowed').    
LastMitch commented: Thanks for the explanation, it was very helpful! +0
veedeoo 474 Junior Poster Featured Poster

@lastMitch,

Here is a sample script I posted months back. This one is a multi-file uploader, but you can easily remove the form elements that you don't need..

!DISCLAIMER! HTML is not my strongest area in any of the coding languages.

filename: upload.php

<html>
<head>
</head>
<body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="process.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>multiple Files Upload </strong></td>
</tr>
<tr>
<td>Type Name:<input type ="text" name="poster"/></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</body>
</html>

filename: process.php . If will be processing single file upload, just remove the part where it is processing the 2nd and the 3rd file. That shouldn't be too hard to accomplished.

<?php
## deviced by veedeoo, and does not have any warranty of any kind.
## not intended in production server, UNTIL all possible security measures are implemented.

$poster = $_POST['poster'];
## define destination directory

define("DIR_","uploads/");

$item1= DIR_.$poster."_".$_FILES['ufile']['name'][0];
$item2= DIR_.$poster."_".$_FILES['ufile']['name'][1];
$item3= DIR_.$poster."_".$_FILES['ufile']['name'][2];


## use move_uploaded file function
move_uploaded_file($_FILES['ufile']['tmp_name'][0], $item1);
move_uploaded_file($_FILES['ufile']['tmp_name'][1], $item2);
move_uploaded_file($_FILES['ufile']['tmp_name'][2], $item3);

echo '<img src="'.$item1.'" width="150" height="150"><br/>';
echo "File Name :".$_FILES['ufile']['name'][0]."<br/>";
echo "File Size :".$_FILES['ufile']['size'][0]."<br/>";
echo "File Type :".$_FILES['ufile']['type'][0]."<br/>";


echo '<img src="'.$item2.'" width="150" height="150"><br/>';
echo "File Name :".$_FILES['ufile']['name'][1]."<br/>";
echo "File Size :".$_FILES['ufile']['size'][1]."<br/>";
echo "File Type :".$_FILES['ufile']['type'][1]."<br/>";


echo '<img src="'.$item3.'" width="150" height="150"><br/>';
echo …
LastMitch commented: Thanks for the script, it's very simple for me to understand! Thanks! +2
veedeoo 474 Junior Poster Featured Poster

Hello everyone,

!WARNING! this function should only be use, WHEN ffmpeg PHP CANNOT be installed in the server.

I just got some free time from tedious and hectic school schedules. About two months ago, I saw a question about "how to get the duration of a given video file?". Of course, the common response to this question is to utilize ffmpeg php.

Using the ffmpeg php extension, we can pretty much grab anything from all sorts of video extensions. For example, we can implement simple codes below to get the duration of a video file..

$thisVideoFile = new ffmpeg_movie("video.ext");

echo $thisVideoFile->getDuration();

The code above is that all we need to get and display duration of the video. Pretty easy huh? "Wait a minute, I don't have any ffmpeg installed on my server, what shall I do?" one developer screamed with disperation. Well, in response to the screaming developer's question is not that hard to guess??? Of course, it can be done with pure php, and this is how I did it...

Once again, I would like to WARN everyone that this equation or formula is sometimes off by 0.001 micro seconds. This is not an ultimate solution, but rather an easy fix when there is no FFMPEG php installed on the server.

function getDuration($file){

if (file_exists($file)){
 ## open and read video file
$handle = fopen($file, "r");
## read video file size
$contents = fread($handle, filesize($file));

fclose($handle);
$make_hexa = hexdec(bin2hex(substr($contents,strlen($contents)-3)));

if (strlen($contents) > $make_hexa){

$pre_duration = hexdec(bin2hex(substr($contents,strlen($contents)-$make_hexa,3))) ;
$post_duration = …
cereal commented: great work! +8
LastMitch commented: Nice Work! +0