Как составить ссылку php

Как создать и вывести ссылку в php? Кликабельная ссылка, гиперссылка, активная ссылка через php, вставить ссылку в php код,вставить ссылку href в код php – далее возникает как мимум одна ошибка! Конфликт кавычек!

Попробуем разобраться в теме ссылки в php, приведем несколько примеров вывода ссылок на экран, в тексте, в коде…

  • Как вывести ссылку в коде php

    Нам требуется прямо здесь вывести вот эту ссылку :

    https://dwweb.ru/?tema=php_url

    Для этого существует несколько вариантов, к примеру, есть ссылка, которая имеет вид:

    Мы сможем её вывести через echo:

    <?php

    echo “https://dwweb.ru/?tema=php_url”;

    ?>

    смотрим, что у нас получилось:

    https://dwweb.ru/?tema=php_url

  • Как вывести ссылку в коде php из переменной

    У нас есть в переменной ссылка, которую нам нужно вывести в тексте, либо где-то в другом месте, стандартно через echo.

    К примеру, вы скажите где и зачем у нас ссылка появилась в переменной и где вообще может пригодиться ссылка в переменной!? Если вы дойдете до создания сайта. то у вас будет много разных переменных, и в том числе и ссылки, в том числе на данную страницу у нас она называется $hp_page

    $domen = $_SERVER[“HTTP_X_FORWARDED_PROTO”].’://’.$_SERVER[“HTTP_HOST”];

    $parse_url = parse_url(strip_tags($_SERVER[‘REQUEST_URI’]), PHP_URL_PATH);

    $hp_page = $domen . $parse_url;

    echo $hp_page;

    Результат:

    https://dwweb.ru/page/php/url/001_kak_vyivesti_ssyilku_v_php.html

  • Вывод активной ссылки в php

    Но нам нужна активная кликабельная ссылка, которая будет к примеру такого вида:

    текст ссылки

    Код данной ссылки :

    <a href=”https://dwweb.ru/?tema=php_url” target=”_blank”>текст ссылки</a>

    Но!

    Если мы применим такую конструкцию

    echo “<a href=”https://dwweb.ru/?tema=php_url”>текст ссылки</a>”;

    То получим вот такую ошибку:

    Parse error: syntax error, unexpected ‘https’ (T_STRING), expecting ‘,’ or ‘;’ in

    здесь будет путь

    on line 1

    Что нам говорит данная ошибка!? Это синтаксическая ошибка – нарушение правил составления предложений языка из отдельных предложений.

    Непонятно!? Конечно непонятно! Я сам не понимаю! wall
    смайлы
    Если мы посмотрим на текст ошибки, то unexpected (рус:неожиданный, неправильный) и он не понимает, что такое https, потому, что после второй двойной кавычки (echo “<a href=”) он хочет увидеть, что-то другое, например переменную, либо точку(присоединение), либо запятую, либо окончание предложения ; но php там видит строку… которая явно не на месте…
    Что нам говорит expecting (рус:ожидать, надеяться, полагать )…

    Примерно вот что он хочет увидеть:

    echo “<a href=”,”https://dwweb.ru/?tema=php_url”,”>текст ссылки</a>”;

    Именно так, конечно никто не делает, поэтому перейдем к следующим пунктам : экранирование кавычек в ссылке php!

  • В ссылке php везде двойные кавычки.

    Для того, чтобы не возникала выше описанная ошибка, нам потребуется экранировать какие-то кавычки, если они повторяются внутри!

    Используем в ссылке двойные кавычки, внутри двойные экранируем обратным слешем.

    <?

    echo

    <a href=

    https://dwweb.ru/?tema=php_url

    >текст ссылки</a>

    ;

    ?>

  • В ссылке php везде одинарные кавычки.

    Используем в ссылке одинарные кавычки, внутри одинарные экранируем обратным слешем.

    <?

    echo

    <a href=

    https://dwweb.ru/?tema=php_url

    >текст ссылки</a>

    ;

    ?>

  • В ссылке php снаружи двойные внутри одинарные кавычки.

    Если в ссылке php используем снаружи двойные, то внутри можно использовать одинарные кавычки, тогда экранировать не нужно!

    <?

    echo

    <a href=

    https://dwweb.ru/?tema=php_url

    >текст ссылки</a>

    ;

    ?>

  • В ссылке php снаружи одинарные внутри двойные кавычки.

    Можно снаружи php ссылки использовать одинарные, а внутри двойные кавычки – тоже экранировать ничего не нужно!

    <?

    echo

    <a href=

    https://dwweb.ru/?tema=php_url

    >текст ссылки</a>

    ;

    ?>

  • Как вставить ссылку href в код php.

    Данная страница вся посвящена созданию, выводу ссылок на экран, на монитор, в коде, если ссылка активная, то там точно встретиться атрибут href – это конечно не обязательно, но мы то говорим об активной ссылке через php, то атрибут href в данном случае обязателен!

    Ну так, что же с вставлением ссылки href в код php

    Все темы на данной странице начиная с пункта номер 1, так или иначе связаны с темой использования ссылки href в коде php, идем в начало страницы и начинаем изучать тему, как же работает вывод вставки ссылок href в код php!

    Поисковый запрос href php это что

    Мы уже здесь столько всего говорили о том, что такое “href php“, поэтому href php это что – это то, чему посвящена страница.

  • Как в php вставить картинку с ссылкой.

    1). Для того, чтобы вставить картинку в ссылку в php, нам потребуется картинка! Мы тут буквально переделывали свой первый слайдер – вот оттуда и возьмем!

    https://dwweb.ru/__img/php/img_php/morning.png

    2). Далее нам потребуется тег картинки:

    <img src=”” alt=”картинка”>

    3). И нам нужна опять ссылка:

    <a href=url_ссылки target=_blank>текст</a>

    4). Теперь соединим все вместе и выведем через echo:

    echo ‘<a href=https://dwweb.ru/?tema=php target=_blank><img src=”https://dwweb.ru/__img/php/img_php/morning.png” alt=”пример картинки выведенной с ссылкой в php”></a>’;

    5). Результат вывод картинки с ссылкой в php:

    пример картинки выведенной с ссылкой в php

  • Как вывести анкорную ссылку в php

    Вывод анкорной=якорной ссылки в php ничем не отличается от вывода обычной ссылки, посещаем в echo эту самую якорную ссылку name, ну и собственно все:

    echo “<a name=”paragraph_10″></a>”;

    Не забываем про конфликт кавычек в php

  • Вообще о ссылках в PHP.

    Эта страница о ссылках в php была написана еще в старом дизайне и мы просто её обновили и поменяли несколько строк и подправили код.

    И когда я писал эту страницу, то писал о том, что меня интересовало и волновало! И если тема была интересной. то я просто писал, о ней!

    Но оказалось, что “ссылки в php” имеет вообще другой смысл, правильнее сказать не только такой смысл, о чем вы прочитали сверху, но и тот смысл, который, если честно, то пытался понять, зачем это нужно – так и не понял! Реально!

    Есть какие-то вещи, которые написаны в учебнике… – они существуют… – но понять о чем идет речь невозможно!

    Я не претендую, что я великий программист – об этом я никогда и не говорил!(я всего лишь любитель…)

    Но! Что точно было! За эти 3 года изучения php – эта тема – ссылка в php – вообще нигде и никогда не всплывала, ни напрямую ни косвенно! Может я ещё не настолько продвинут в php, но я был искренне удивлен, что смысл, который закладывается в словосочетание – ссылка в php – вовсе не о том, о чем я думал, а о том, что я не могу понять…

    И о моем непонимании…

    О чем я и говорил, на странице о сайте – какая была идея – донести смысл именно такой информации для людей с нулевыми знаниями! Но здесь – именно в этом понятии ссылки в php – я точно вам не смогу помочь!

  • Поисковые запросы на тему Ссылка в php

    Дополнительно о поисковых запросах, которые кроме того, могут быть смешными, тупыми и т.д.

    php вывод русской ссылки

    Эээээ….. что!? php вывод русской ссылки ?… даже и сказать не знаю, что это такое…

    php вывод русской ссылки

    Как присвоить переменной ссылку в php

    Как присвоить переменной ссылку в php
    Для того, чтобы присвоить ссылку переменной, нужно взять выше приведенный материал вывода ссылки через echo и заменить в этом коде echo на переменную со знаком равно! Таким образом, вы присвоите переменной ссылку:

    $example = “<a href=’адрес’>текст</a>”;

    Что делают ссылки

    Есть три основных операции с использованием ссылок:
    присвоение по ссылке,
    передача по ссылке
    и возврат по ссылке.
    Данный раздел познакомит вас с этими операциями и предоставит ссылки для дальнейшего
    изучения.

    Присвоение по ссылке

    Первая из них – ссылки PHP позволяют создать две переменные
    указывающие на одно и то же значение. Таким образом, когда выполняется следующее:

    то $a указывает на то же значение
    что и $b.

    Замечание:

    $a и $b здесь абсолютно эквивалентны,
    но это не означает, что $a указывает на $b
    или наоборот. Это означает, что $a
    и $b указывают на одно и то же значение.

    Замечание:

    При присвоении, передаче или возврате неинициализированной переменной по ссылке,
    происходит её создание.

    Пример #1 Использование ссылок с неинициализированными переменными


    <?php
    function foo(&$var) { }foo($a); // $a создана и равна null$b = array();
    foo($b['b']);
    var_dump(array_key_exists('b', $b)); // bool(true)$c = new stdClass;
    foo($c->d);
    var_dump(property_exists($c, 'd')); // bool(true)
    ?>

    Такой же синтаксис может использоваться в функциях, возвращающими ссылки,
    и с оператором new:


    <?php
    $foo
    =& find_var($bar);
    ?>

    Использование того же синтаксиса с функцией, которая не
    возвращает по ссылке, приведёт к ошибке, так же как и её использование с результатом
    оператора new.
    Хотя объекты передаются как указатели, это не то же самое, что ссылки, как описано
    в разделе Объекты и ссылки.

    Внимание

    Если переменной, объявленной внутри функции как
    global, будет присвоена ссылка, она будет видна только
    в функции. Чтобы избежать этого, используйте массив $GLOBALS.

    Пример #2 Присвоение ссылок глобальным переменным внутри функции


    <?php
    $var1
    = "Пример переменной";
    $var2 = "";

    function

    global_references($use_globals)
    {
    global
    $var1, $var2;
    if (!
    $use_globals) {
    $var2 =& $var1; // только локально
    } else {
    $GLOBALS["var2"] =& $var1; // глобально
    }
    }
    global_references(false);
    echo
    "значение var2: '$var2'n"; // значение var2: ''
    global_references(true);
    echo
    "значение var2: '$var2'n"; // значение var2: 'Пример переменной'
    ?>

    Думайте о global $var; как о сокращении от
    $var =& $GLOBALS['var'];. Таким образом,
    присвоение $var другой ссылки влияет лишь на локальную
    переменную.

    Замечание:

    При использовании переменной-ссылки в foreach,
    изменяется содержание, на которое она ссылается.

    Пример #3 Ссылки и foreach


    <?php
    $ref
    = 0;
    $row =& $ref;
    foreach (array(
    1, 2, 3) as $row) {
    // сделать что-нибудь
    }
    echo
    $ref; // 3 - последнее значение, используемое в цикле
    ?>

    Хотя в выражениях, создаваемых с помощью конструкции
    array(),
    нет явного присвоения по ссылке, тем не менее они могут вести себя как таковые,
    если указать префикс & для элементов массива. Пример:


    <?php
    $a
    = 1;
    $b = array(2, 3);
    $arr = array(&$a, &$b[0], &$b[1]);
    $arr[0]++; $arr[1]++; $arr[2]++;
    /* $a == 2, $b == array(3, 4); */
    ?>

    Однако следует отметить, что ссылки в массивах являются потенциально опасными.
    При обычном (не по ссылке) присвоении массива, ссылки
    внутри этого массива сохраняются. Это также относится
    и к вызовам функций, когда массив передаётся по значению. Пример:


    <?php
    /* Присвоение скалярных переменных */
    $a = 1;
    $b =& $a;
    $c = $b;
    $c = 7; //$c не ссылка и не изменяет значений $a и $b

    /* Присвоение массивов */

    $arr = array(1);
    $a =& $arr[0]; // $a и $arr[0] ссылаются на одно значение
    $arr2 = $arr; // присвоение не по ссылке!
    $arr2[0]++;
    /* $a == 2, $arr == array(2) */
    /* Содержимое $arr изменилось, хотя было присвоено не по ссылке! */
    ?>

    Иными словами, поведение отдельных элементов массива
    не зависит от типа присвоения этого массива.

    Передача по ссылке

    Второе, что делают ссылки – передача параметров по ссылке. При этом
    локальная переменная в функции и переменная в вызывающей области видимости
    ссылаются на одно и то же содержимое. Пример:


    <?php
    function foo(&$var) {
    $var++;
    }
    $a = 5;
    foo($a);
    ?>

    Этот код присвоит $a значение 6. Это происходит, потому
    что в функции foo переменная $var
    ссылается на то же содержимое, что и переменная $a. Смотрите
    также детальное объяснение
    передачи по ссылке.

    ladoo at gmx dot at

    18 years ago


    I ran into something when using an expanded version of the example of pbaltz at NO_SPAM dot cs dot NO_SPAM dot wisc dot edu below.
    This could be somewhat confusing although it is perfectly clear if you have read the manual carfully. It makes the fact that references always point to the content of a variable perfectly clear (at least to me).

    <?php
    $a
    = 1;
    $c = 2;
    $b =& $a; // $b points to 1
    $a =& $c; // $a points now to 2, but $b still to 1;
    echo $a, " ", $b;
    // Output: 2 1
    ?>


    Hlavac

    15 years ago


    Watch out for this:

    foreach ($somearray as &$i) {
      // update some $i...
    }
    ...
    foreach ($somearray as $i) {
      // last element of $somearray is mysteriously overwritten!
    }

    Problem is $i contians reference to last element of $somearray after the first foreach, and the second foreach happily assigns to it!


    elrah [] polyptych [dot] com

    12 years ago


    It appears that references can have side-effects.  Below are two examples.  Both are simply copying one array to another.  In the second example, a reference is made to a value in the first array before the copy.  In the first example the value at index 0 points to two separate memory locations. In the second example, the value at index 0 points to the same memory location.

    I won't say this is a bug, because I don't know what the designed behavior of PHP is, but I don't think ANY developers would expect this behavior, so look out.

    An example of where this could cause problems is if you do an array copy in a script and expect on type of behavior, but then later add a reference to a value in the array earlier in the script, and then find that the array copy behavior has unexpectedly changed.

    <?php
    // Example one
    $arr1 = array(1);
    echo
    "nbefore:n";
    echo
    "$arr1[0] == {$arr1[0]}n";
    $arr2 = $arr1;
    $arr2[0]++;
    echo
    "nafter:n";
    echo
    "$arr1[0] == {$arr1[0]}n";
    echo
    "$arr2[0] == {$arr2[0]}n";// Example two
    $arr3 = array(1);
    $a =& $arr3[0];
    echo
    "nbefore:n";
    echo
    "$a == $an";
    echo
    "$arr3[0] == {$arr3[0]}n";
    $arr4 = $arr3;
    $arr4[0]++;
    echo
    "nafter:n";
    echo
    "$a == $an";
    echo
    "$arr3[0] == {$arr3[0]}n";
    echo
    "$arr4[0] == {$arr4[0]}n";
    ?>


    amp at gmx dot info

    15 years ago


    Something that might not be obvious on the first look:
    If you want to cycle through an array with references, you must not use a simple value assigning foreach control structure. You have to use an extended key-value assigning foreach or a for control structure.

    A simple value assigning foreach control structure produces a copy of an object or value. The following code

    $v1=0;
    $arrV=array(&$v1,&$v1);
    foreach ($arrV as $v)
    {
      $v1++;
      echo $v."n";
    }

    yields

    0
    1

    which means $v in foreach is not a reference to $v1 but a copy of the object the actual element in the array was referencing to.

    The codes

    $v1=0;
    $arrV=array(&$v1,&$v1);
    foreach ($arrV as $k=>$v)
    {
        $v1++;
        echo $arrV[$k]."n";
    }

    and

    $v1=0;
    $arrV=array(&$v1,&$v1);
    $c=count($arrV);
    for ($i=0; $i<$c;$i++)
    {
        $v1++;
        echo $arrV[$i]."n";
    }

    both yield

    1
    2

    and therefor cycle through the original objects (both $v1), which is, in terms of our aim, what we have been looking for.

    (tested with php 4.1.3)


    Anonymous

    7 years ago


    to reply to ' elrah [] polyptych [dot] com ', one thing to keep in mind is that array (or similar large data holders) are by default passed by reference. So the behaviour is not side effect. And for array copy and passing array inside function  always done by 'pass by reference'...

    nay at woodcraftsrus dot com

    11 years ago


    in PHP you don't really need pointer anymore if you want to share an  object across your program

    <?php

    class foo{

            protected
    $name;

            function
    __construct($str){

                   
    $this->name = $str;

            }

            function
    __toString(){

                    return 
    'my name is "'. $this->name .'" and I live in "' . __CLASS__ . '".' . "n";

            }

            function
    setName($str){

                   
    $this->name = $str;

            }

    }

    class

    MasterOne{

            protected
    $foo;

            function
    __construct($f){

                   
    $this->foo = $f;

            }

            function
    __toString(){

                    return
    'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "n";

            }

            function
    setFooName($str){

                   
    $this->foo->setName( $str );

            }

    }

    class

    MasterTwo{

            protected
    $foo;

            function
    __construct($f){

                   
    $this->foo = $f;

            }

            function
    __toString(){

                    return
    'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "n";

            }

            function
    setFooName($str){

                   
    $this->foo->setName( $str );

            }

    }
    $bar = new foo('bar');

    print(

    "n");

    print(
    "Only Created $bar and printing $barn");

    print(
    $bar );

    print(

    "n");

    print(
    "Now $baz is referenced to $bar and printing $bar and $bazn");

    $baz =& $bar;

    print(
    $bar );

    print(

    "n");

    print(
    "Now Creating MasterOne and Two and passing $bar to both constructorsn");

    $m1 = new MasterOne( $bar );

    $m2 = new MasterTwo( $bar );

    print(
    $m1 );

    print(
    $m2 );

    print(

    "n");

    print(
    "Now changing value of $bar and printing $bar and $bazn");

    $bar->setName('baz');

    print(
    $bar );

    print(
    $baz );

    print(

    "n");

    print(
    "Now printing again MasterOne and Twon");

    print(
    $m1 );

    print(
    $m2 );

    print(

    "n");

    print(
    "Now changing MasterTwo's foo name and printing again MasterOne and Twon");

    $m2->setFooName( 'MasterTwo's Foo' );

    print(
    $m1 );

    print(
    $m2 );

    print(

    "Also printing $bar and $bazn");

    print(
    $bar );

    print(
    $baz );

    ?>


    php.devel at homelinkcs dot com

    18 years ago


    In reply to lars at riisgaardribe dot dk,

    When a variable is copied, a reference is used internally until the copy is modified.  Therefore you shouldn't use references at all in your situation as it doesn't save any memory usage and increases the chance of logic bugs, as you discoved.


    Oddant

    9 years ago


    About the example on array references.
    I think this should be written in the array chapter as well.
    Indeed if you are new to programming language in some way, you should beware that arrays are pointers to a vector of Byte(s).

    <?php $arr = array(1); ?>
    $arr here contains a reference to which the array is located.
    Writing :
    <?php echo $arr[0]; ?>
    dereferences the array to access its very first element.

    Now something that you should also be aware of  (even you are not new to programming languages) is that PHP use references to contains the different values of an array. And that makes sense because the type of the elements of a PHP array can be different.

    Consider the following example :

    <?php

    $arr

    = array(1, 'test');$point_to_test =& $arr[1];$new_ref = 'new';$arr[1] =& $new_ref;

    echo

    $arr[1]; // echo 'new';
    echo $point_to_test; // echo 'test' ! (still pointed somewhere in the memory)?>


    Amaroq

    13 years ago


    I think a correction to my last post is in order.

    When there is a constructor, the strange behavior mentioned in my last post doesn't occur. My guess is that php was treating reftest() as a constructor (maybe because it was the first function?) and running it upon instantiation.

    <?php
    class reftest
    {
        public
    $a = 1;
        public
    $c = 1;

        public function

    __construct()
        {
            return
    0;
        }

        public function

    reftest()
        {
           
    $b =& $this->a;
           
    $b++;
        }

        public function

    reftest2()
        {
           
    $d =& $this->c;
           
    $d++;
        }
    }
    $reference = new reftest();$reference->reftest();
    $reference->reftest2();

    echo

    $reference->a; //Echoes 2.
    echo $reference->c; //Echoes 2.
    ?>


    dovbysh at gmail dot com

    15 years ago


    Solution to post "php at hood dot id dot au 04-Mar-2007 10:56":

    <?php
    $a1
    = array('a'=>'a');
    $a2 = array('a'=>'b');

    foreach (

    $a1 as $k=>&$v)
    $v = 'x';

    echo

    $a1['a']; // will echo xunset($GLOBALS['v']);

    foreach (

    $a2 as $k=>$v)
    {}

    echo

    $a1['a']; // will echo x?>


    charles at org oo dot com

    15 years ago


    points to post below me.
    When you're doing the references with loops, you need to unset($var).

    for example
    <?php
    foreach($var as &$value)
    {
    ...
    }
    unset(
    $value);
    ?>


    akinaslan at gmail dot com

    12 years ago


    In this example class name is different from its first function and however there is no construction function. In the end as you guess "a" and "c" are equal. So if there is no construction function at same time class and its first function names are the same, "a" and "c" doesn't equal forever. In my opinion php doesn't seek any function for the construction as long as their names differ from each others.

    <?php

    class reftest_new

    {

        public
    $a = 1;

        public
    $c = 1;

        public function

    reftest()

        {

           
    $b =& $this->a;

           
    $b++;

        }

        public function

    reftest2()

        {

           
    $d =& $this->c;

           
    $d++;

        }

    }
    $reference = new reftest_new();
    $reference->reftest();

    $reference->reftest2();

    echo

    $reference->a; //Echoes 2.

    echo $reference->c; //Echoes 2.

    ?>


    dexant9t at gmail dot com

    1 year ago


    It matters if you are playing with a reference or with a value

    Here we are working with values so working on a reference updates original variable too;

    $a = 1;
    $c = 22;

    $b = & $a;
    echo "$a, $b"; //Output: 1, 1

    $b++;
    echo "$a, $b";//Output: 2, 2 both values are updated

    $b = 10;
    echo "$a, $b";//Output: 10, 10 both values are updated

    $b =$c; //This assigns value 2 to $b which also updates $a
    echo "$a, $b";//Output: 22, 22

    But, if instead of $b=$c you do
    $b = &$c; //Only value of $b is updated, $a still points to 10, $b serves now reference to variable $c

    echo "$a, $b"//Output: 10, 22


    Amaroq

    15 years ago


    The order in which you reference your variables matters.

    <?php
    $a1
    = "One";
    $a2 = "Two";
    $b1 = "Three";
    $b2 = "Four";$b1 =& $a1;
    $a2 =& $b2;

    echo

    $a1; //Echoes "One"
    echo $b1; //Echoes "One"echo $a2; //Echoes "Four"
    echo $b2; //Echoes "Four"
    ?>


    Drewseph

    14 years ago


    If you set a variable before passing it to a function that takes a variable as a reference, it is much harder (if not impossible) to edit the variable within the function.

    Example:
    <?php
    function foo(&$bar) {
       
    $bar = "hellon";
    }
    foo($unset);
    echo(
    $unset);
    foo($set = "setn");
    echo(
    $set);?>

    Output:
    hello
    set

    It baffles me, but there you have it.


    dnhuff at acm dot org

    14 years ago


    In reply to Drewseph using foo($a = 'set'); where $a is a reference formal parameter.

    $a = 'set' is an expression. Expressions cannot be passed by reference, don't you just hate that, I do. If you turn on error reporting for E_NOTICE, you will be told about it.

    Resolution: $a = 'set'; foo($a); this does what you want.


    firespade at gmail dot com

    16 years ago


    Here's a good little example of referencing. It was the best way for me to understand, hopefully it can help others.

    $b = 2;
    $a =& $b;
    $c = $a;
    echo $c;

    // Then... $c = 2


    Amaroq

    13 years ago


    When using references in a class, you can reference $this-> variables.

    <?php
    class reftest
    {
        public
    $a = 1;
        public
    $c = 1;

        public function

    reftest()
        {
           
    $b =& $this->a;
           
    $b = 2;
        }

        public function

    reftest2()
        {
           
    $d =& $this->c;
           
    $d++;
        }
    }
    $reference = new reftest();$reference->reftest();
    $reference->reftest2();

    echo

    $reference->a; //Echoes 2.
    echo $reference->c; //Echoes 2.
    ?>

    However, this doesn't appear to be completely trustworthy. In some cases, it can act strangely.

    <?php
    class reftest
    {
        public
    $a = 1;
        public
    $c = 1;

        public function

    reftest()
        {
           
    $b =& $this->a;
           
    $b++;
        }

        public function

    reftest2()
        {
           
    $d =& $this->c;
           
    $d++;
        }
    }
    $reference = new reftest();$reference->reftest();
    $reference->reftest2();

    echo

    $reference->a; //Echoes 3.
    echo $reference->c; //Echoes 2.
    ?>

    In this second code block, I've changed reftest() so that $b increments instead of just gets changed to 2. Somehow, it winds up equaling 3 instead of 2 as it should.


    php at hood dot id dot au

    16 years ago


    I discovered something today using references in a foreach

    <?php
    $a1
    = array('a'=>'a');
    $a2 = array('a'=>'b');

    foreach (

    $a1 as $k=>&$v)
    $v = 'x';

    echo

    $a1['a']; // will echo xforeach ($a2 as $k=>$v)
    {}

    echo

    $a1['a']; // will echo b (!)
    ?>

    After reading the manual this looks like it is meant to happen. But it confused me for a few days!

    (The solution I used was to turn the second foreach into a reference too)


    strata_ranger at hotmail dot com

    13 years ago


    An interesting if offbeat use for references:  Creating an array with an arbitrary number of dimensions.

    For example, a function that takes the result set from a database and produces a multidimensional array keyed according to one (or more) columns, which might be useful if you want your result set to be accessible in a hierarchial manner, or even if you just want your results keyed by the values of each row's primary/unique key fields.

    <?php
    function array_key_by($data, $keys, $dupl = false)
    /*
    * $data  - Multidimensional array to be keyed
    * $keys  - List containing the index/key(s) to use.
    * $dupl  - How to handle rows containing the same values.  TRUE stores it as an Array, FALSE overwrites the previous row.
    *         
    * Returns a multidimensional array indexed by $keys, or NULL if error.
    * The number of dimensions is equal to the number of $keys provided (+1 if $dupl=TRUE).
    */  
    {
       
    // Sanity check
       
    if (!is_array($data)) return null;// Allow passing single key as a scalar
       
    if (is_string($keys) or is_integer($keys)) $keys = Array($keys);
        elseif (!
    is_array($keys)) return null;// Our output array
       
    $out = Array();// Loop through each row of our input $data
       
    foreach($data as $cx => $row) if (is_array($row))
        {
    // Loop through our $keys
         
    foreach($keys as $key)
          {
           
    $value = $row[$key];

            if (!isset(

    $last)) // First $key only
           
    {
              if (!isset(
    $out[$value])) $out[$value] = Array();
             
    $last =& $out; // Bind $last to $out
           
    }
            else
    // Second and subsequent $key....
           
    {
              if (!isset(
    $last[$value])) $last[$value] = Array();
            }
    // Bind $last to one dimension 'deeper'.
            // First lap: was &$out, now &$out[...]
            // Second lap: was &$out[...], now &$out[...][...]
            // Third lap:  was &$out[...][...], now &$out[...][...][...]
            // (etc.)
           
    $last =& $last[$value];
          }

                if (isset(

    $last))
          {
           
    // At this point, copy the $row into our output array
           
    if ($dupl) $last[$cx] = $row; // Keep previous
           
    else       $last = $row; // Overwrite previous
         
    }
          unset(
    $last); // Break the reference
       
    }
        else return
    NULL;// Done
       
    return $out;
    }
    // A sample result set to test the function with
    $data = Array(Array('name' => 'row 1', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_a'),
                  Array(
    'name' => 'row 2', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_b'),
                  Array(
    'name' => 'row 3', 'foo' => 'foo_a', 'bar' => 'bar_b', 'baz' => 'baz_c'),
                  Array(
    'name' => 'row 4', 'foo' => 'foo_b', 'bar' => 'bar_c', 'baz' => 'baz_d')
                  );
    // First, let's key it by one column (result: two-dimensional array)
    print_r(array_key_by($data, 'baz'));// Or, key it by two columns (result: 3-dimensional array)
    print_r(array_key_by($data, Array('baz', 'bar')));// We could also key it by three columns (result: 4-dimensional array)
    print_r(array_key_by($data, Array('baz', 'bar', 'foo')));?>


    joachim at lous dot org

    20 years ago


    So to make a by-reference setter function, you need to specify reference semantics _both_ in the parameter list _and_ the assignment, like this:

    class foo{
       var $bar;
       function setBar(&$newBar){
          $this->bar =& newBar;
       }
    }

    Forget any of the two '&'s, and $foo->bar will end up being a copy after the call to setBar.


    butshuti at smartrwanda dot org

    10 years ago


    This appears to be the hidden behavior: When a class function has the same name as the class, it seems to be implicitly called when an object of the class is created.
    For instance, you may take a look at the naming of the function "reftest()": it is in the class "reftest". The behavior can be tested as follows:

    <?php
    class reftest
    {
        public
    $a = 1;
        public
    $c = 1;

        public function

    reftest1()
        {
           
    $b =& $this->a;
           
    $b++;
        }

        public function

    reftest2()
        {
           
    $d =& $this->c;
           
    $d++;
        }

            public function

    reftest()
        {
           echo
    "REFTEST() called here!n";
        }
    }
    $reference = new reftest();
    /*You must notice the above will also implicitly call reference->reftest()*/$reference->reftest1();
    $reference->reftest2();

    echo

    $reference->a."n"; //Echoes 2, not 3 as previously noticed.
    echo $reference->c."n"; //Echoes 2.
    ?>

    The above outputs:

    REFTEST() called here!
    2
    2

    Notice that reftest() appears to be called (though no explicit call to it was made)!


    admin at torntech dot com

    9 years ago


    Something that has not been discussed so far is reference of a reference.
    I needed a quick and dirty method of aliasing incorrect naming until a proper rewrite could be done.
    Hope this saves someone else the time of testing since it was not covered in the Does/Are/Are Not pages.
    Far from best practice, but it worked.

    <?php
    $a
    = 0;$b =& $a;
    $a =& $b;$a = 5;
    echo
    $a . ', ' . $b;
    //ouputs: 5,5echo ' | ';$b = 6;
    echo
    $a . ',' . $b;
    //outputs: 6,6echo ' | ';
    unset(
    $a );
    echo
    $a . ', ' . $b;//outputs: , 6 class Product {

        public

    $id;
        private
    $productid;

        public function

    __construct( $id = null ) {
           
    $this->id =& $this->productid;
           
    $this->productid =& $this->id;
           
    $this->id = $id;
        }

        public function

    getProductId() {
            return
    $this->productid;
        }

    }

    echo

    ' | ';$Product = new Product( 1 );
    echo
    $Product->id . ', ' . $Product->getProductId();
    //outputs 1, 1
    $Product->id = 2;
    echo
    ' | ';
    echo
    $Product->id . ', ' . $Product->getProductId();
    //outputs 2, 2
    $Product->id = null;
    echo
    ' | ';
    echo
    $Product->id . ', ' . $Product->getProductId();
    //outouts ,


    This is a very basic question but I couldn’t seem to find anything on Google, hm.

    Anyway, I’m not referring to creating links, i’m talking of generating links like site.com/1 or how to generate links in php?, the numbers after the url are stored in the database with a corresponding post for example. How do I generate these using php?

    If i visit h**p://site.com/questions/3870639/how-to-generate-links-in-php how do I tell the server to query the database and retrieve the corresponding post of 3870639? (without htaccess).

    Community's user avatar

    asked Oct 6, 2010 at 8:22

    luq's user avatar

    That’s not possible with just PHP, it requires an Apache server module called mod_rewrite (assuming you use Apache for your server). Google for it.

    answered Oct 6, 2010 at 8:26

    Core Xii's user avatar

    Core XiiCore Xii

    6,2004 gold badges31 silver badges42 bronze badges

    1

    You have to use .htaccess.

    You can implement these kind of URLs by forwarding all request to a specific file. This is your Front Controller and it will decompose the URL, extract the information and perform or delegate the necessary actions. With the front controller you have a single point of entry to your website.

    But you need to set up .htaccess to forward all requests to this file, e.g.

     RewriteRule ^(.*)$ index.php [QSA,L]
    

    You should check various frameworks like symfony or Zend, that implement this pattern.

    answered Oct 6, 2010 at 8:30

    Felix Kling's user avatar

    Felix KlingFelix Kling

    789k174 gold badges1082 silver badges1135 bronze badges

    3

    I’m not sure how you would tell the server to navigate to a page if you went to a directory 3870639 that wasn’t there. I would commanly use htaccess to redirect to page.php or similar and use $_SERVER[‘REQUEST_URI’] to get the page URL, or convert the URL to a $_GET variable in the htaccess you can then split(‘/’,$_SERVER[‘REQUEST_URI’]) to get an array of the directories.

    $directories = split('/',$_SERVER['REQUEST_URI']);
    print_r($directories);
    

    gives

    array(
       [0] => 'site.com',
       [1] => 'questions',
       [2] => '3870639',
       [3] => 'how-to-generate-links-in-php'
    )
    

    But like I said, no idea how to get to that page.

    answered Oct 6, 2010 at 8:32

    BenWells's user avatar

    BenWellsBenWells

    3171 silver badge10 bronze badges

    1

    Text transforms. Write a regular expression that will spot a URL and transform it to <a href="$1">$1</a>.

    answered Oct 6, 2010 at 8:27

    amphetamachine's user avatar

    amphetamachineamphetamachine

    27.1k11 gold badges60 silver badges72 bronze badges

    1

    Using mod_rewrite would be the best solution, but if you can’t use it you can still achieve something similar using MultiViews. You would, however, still need it enabled (normally done via .htaccess or the Apache conf).

    MultiViews is meant for allowing content negotiation, so you can request /images/banner and Apache returns an appropriate type (banner.png, banner.svg, etc) depending on the browser’s Accept header. You can use this to hide the extension of your scripts, allowing you to change the technology running your site without changing your urls.

    In your case, you could use

    /questions/3870639/how-to-generate-links-in-php

    which would be the same as

    /questions.php/3870639/how-to-generate-links-in-php

    Within questions.php $_SERVER["PATH_INFO"] would contain /3870639/how-to-generate-links-in-php (or you could parse $_SERVER['REQUEST_URI'] as BenWells mentions). Use explode() or a regular expression to get just the ID.

    answered Oct 6, 2010 at 8:58

    Deebster's user avatar

    DeebsterDeebster

    2,8291 gold badge26 silver badges26 bronze badges

    1

    I don’t think it is possible with PHP alone. You have to use mod_rewrite (which you do not wish to use) or change the default 404 error file to index.php. Then in index.php you can use explode('/', $_SERVER['REQUEST_URI']) to obtain the id from the url.

    But another way to do this is to use the url (I am not sure that this will work, but I think I have seen it somewhere)
    http://site.com/index.php/questions/3870639/how-to-generate-links-in-php

    answered Oct 6, 2010 at 8:59

    Joyce Babu's user avatar

    Joyce BabuJoyce Babu

    19.3k13 gold badges62 silver badges95 bronze badges

    Scott-Cartwright / Getty Images

    Updated on February 12, 2018

    Websites are filled with links. You’re probably already aware of how to create a link in HTML. If you’ve added PHP to your web server to be able to enhance your site’s capabilities, you may be surprised to learn that you create a link in PHP the same as you do in HTML. You have a few options, though. Depending on where in your file the link is, you might present the link HTML in a slightly different way.

    You can switch back and forth between PHP and HTML in the same document, and you can use the same software—any plain text editor will do—to write PHP as to write HTML.

    How to Add Links to PHP Documents

    If you are making a link in a PHP document that is outside of the PHP brackets, you just use HTML as usual. Here is an example:

    <a href="https://twitter.com/angela_bradley">My Twitter</a>
    <?php
    ----- My PHP Code----
    ?>

    If the link needs to be inside the PHP, you have two options. One option is to end the PHP, enter the link in HTML, and then reopen PHP. Here is an example:

    <?php
    ----- My PHP Code----
    ?>
    <a href="https://twitter.com/angela_bradley">My Twitter</a>
    <?php
    ----- My PHP Code----
    ?>

    The other option is to print or echo the HTML code inside the PHP. Here is an example:

    <?php
    Echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>"
    ?>

    Another thing you can do is create a link from a variable. Let’s say that the variable $url holds the URL for a website that someone has submitted or that you have pulled from a database. You can use the variable in your HTML.

    <a href="https://twitter.com/angela_bradley">My Twitter</a>
    <?php
    Echo "<a href=$url>$site_title</a>"
    ?>

    For Beginning PHP Programmers

    If you are new to PHP, remember you begin and end a section of PHP code using <?php and ?> respectively. This code lets the server know that what is included is PHP code. Try a PHP beginner’s tutorial to get your feet wet in the programming language. Before long, you’ll be using PHP to set up a member login, redirect a visitor to another page, add a survey to your website, create a calendar, and add other interactive features to your webpages.

    PHP URL

    Definition of PHP URL

    Generally, the URL means Uniform Resource Locater. Likewise, URL in PHP Programming Language is also the same. URL is nothing but a website address. It helps in connecting the client and the server when browsed using a specific link. URL looks simple but it contains specific info of the specific website address which actually points to a specific IP Address which actually points to a specific domain hosting. This PHP URL also has many URL functions to handle which are useful in handling the URL like encoding, decoding, parsing, etc. based on our requirement. Usually, there will be two types of URLs. They are HTTPS enabled URLs and HTTPS disabled URLs which are shown in the below syntax. Check out the below content so that you will understand the whole concept of the PHP URL concept in detail.

    Syntax and Parameters

    The syntax and parameters of PHP URL is given below:

    https://www.educba.com
    http://www.profitloops.in

    Explanation of the PHP URL Parameters:

    • https and http parameter: This is the parameter that represents whether the URL is HTTPS enabled or HTTP enabled. HTTP means Hyper Text Transfer Protocol whereas HTTPS means Hyper Text Transfer Protocol Secured.
    • www parameter: This parameter is a normal parameter for any time of the website URL before the domain name. WWW means the World Wide Web.
    • domain name parameter and domain extension: The domain name parameter is the name of the specific website and it will end with some domain extension like .com or .biz or .in or .us etc. The “.COM” is normal for many websites but if the extension ends with “.IN” that means it belongs to Indian Country Domain like. “. The US” is for US Domains, “.BIZ” is for Business Domains etc..

    How does URL works in PHP?

    In any web programming language which are like PHP Programming Language, whenever a user enters a specific URL in the URL section of the browser then that request will be passed to the specific domain name server. Then the domain server will return to a specific assigned IP Address and proceeds to the hosting server which hosts a blog/website. Then browser like Educba Chrome/any other request a specific page from the specific web server with the help of the IP Address which is actually specified by the domain name server. Then that web server will return the page to a specific IP Address which is actually specifying by the specific browser which is actually requesting the page. That specific page that appeared in front of you on the browser may contain many other URL’s which may contain many server pages, many images, etc. The URL can be anything like www.educba.com or any other like that.

    URL Function in PHP

    There are different types of URL Functions that help in dealing with the URL strings. The URL is an address that is helpful in identifying a specific website and that URL string text may appear like:https://freeforts.blogspot.com/2017/01/download-youtube-clone-template-for.html. Here I used some BlogSpot sub domain. Some of the URL Functions include.

    • get_headers()
    • get_meta_tags()
    • parse_url()
    • urlencode()
    • urldecode()
    • rawurlencode()
    • rawurldecode()

    1. get_header() URL Function

    The get_header() URL Function helps in fetching all headers which are actually sent by the specific server in response to the HTTP request/requests.

    Example

    This is the example of illustrating the get_headers() function which helps in fetching all the headers which are actually sent by the specific server as a response for HTTP request/requests. Here I am using http://www.educba.com as an URL input. Here we will get all headers of that specific URL.

    Code:

    <?php
    $url = 'http://www.educba.com';
    print_r(get_headers($url));
    ?>

    Output:

    PHP URL-1.1

    2. get _meta_tags() URL Function

    The get_meta_tags() URL Function helps in extracting all the meta tag content data attributes which are from the file which returns a specific array.

    Example

    This is the example of illustrating the get_meta_tags() URL function to get all meta tag attibutes of the specific input URL. Here only the home page URL is used so there will be no meta tags and this will shown as empty inside of the array.

    Code:

    <?php
    $url = "https://www.educba.com/";
    $metas = get_meta_tags($url);
    print_r($metas);
    ?>

    Output:

    PHP URL-1.2

    3. parse_url() URL Function

    The parse_url() URL Function helps in parsing the URL and helps in returning its components.

    Example

    This is the example of parsing a specific input URL based on our requirements. Here we are parsing the http://www.educba.com URL. Check out the output so that you will get how the input URL is parsed.

    Code:

    <?php
    $url = 'http://www.educba.com';
    var_dump(parse_url($url));
    ?>

    Output:

    PHP URL-1.3

    4. urlencode() URL Function

    The urlencode() URL Function helps in encoding the URL.

    Example

    This is the example of illustrating urlencode() URL function. Here I used four different types of URL’s. With the help of urlencode() URL Function, each and every URL will be encoded into different types but string type only. You can check the output so that you will under how different types of URL’s are encoded. <br> tags with echo statement just to display line breaks and <hr> tags are used to display horizontal lines when the syntax is executed.

    Code:

    <?php
    // This is the PHP program of illustrating the urlencode functionality
    echo urlencode("https://www.educba.com") . "n";
    echo urlencode("http://www.profitloops.in/") . "n";
    echo urlencode("https://profitloops.wordpress.com/") . "n";
    echo urlencode("https://freeforts.blogspot.com/") . "n";
    ?>

    Output:

    PHP URL-1.4

    5. urldecode() URL Function

    The urldecode() URL Function helps in decoding the encoded URL.

    Example

    This is the example of illustrating the urldecode() URL function. In order to decode the URL, we need the already encoded code that means the specific input URL or URL’s of urldecode() should be the output of urlencode() function. Here I used the encoded urls of the outputs of the above example. Then after the execution, you will get the above example’s inputs. Check out the outputs so that you will know how the decode function is working.

    Code:

    <?php
    //This is the program of illustrating URL Decode() function of PHP
    echo urldecode("https%3A%2F%2Fwww.educba.com");
    echo "n";
    echo urldecode("http%3A%2F%2Fwww.profitloops.in%2F");
    echo "n";
    echo urldecode("https%3A%2F%2Fprofitloops.wordpress.com%2F");
    echo "n";
    echo urldecode("https%3A%2F%2Ffreeforts.blogspot.com%2F");
    echo "n";
    ?>

    Output:

    Output-1.5

    6. rawurlencode() URL Function

    The rawurlencode() URL Function helps in encoding the URL according to the RFC 1738.

    Example

    This is the example of illustrating the rawurlencode() function. Here with the help of the rawurlencode() function, only the string will be encoded for the specific URL.

    Code:

    <?php
    echo '<a href="www.educba.com',
    rawurlencode('A Multi Info Portal for Bloggers'), '">';
    ?>

    Output:

    Output-1.6

    7. rawurldecode() URL Function

    The rawurldecode() URL Function helps in decoding the URL which is decoded according to the RFC 1738.

    Example

    This is the example of decoding the rawurlencode() inputs. Check out the above example and this example so that you will understand what is happening and also check out the outputs.

    Code:

    <?php
    echo rawurldecode('A%20Multi%20Info%20Portal%20for%20Bloggers');
    ?>

    Output:

    Output-1.7

    Recommended Articles

    This is a guide to the PHP URL. Here we also discuss the introduction, syntax, working, and functions of URL in PHP along with examples and its code implementation. You may also have a look at the following articles to learn more –

    1. PHP Split Array
    2. PHP include_once
    3. PHP Array Search
    4. PHP GET Method

    Добавить комментарий