Home > Backend Development > PHP Tutorial > php制作图片验证码echo $url和echo file_get_content($url)的区别

php制作图片验证码echo $url和echo file_get_content($url)的区别

WBOY
Release: 2016-06-06 20:14:19
Original
989 people have browsed it

在一个PHP中有个表单用于输出验证码图片,我原以为下面的代码中$url = "images/".$randomkey.".jpg"就是图片路径,为什么还需要file_get_content函数?我的理解是echo $url就输出了images/pic2.jpg,那么src="chaptcha_img.php?r="不就是src="images/pic2.jpg"吗?但这样输出不了图片,求解惑,感谢~

下面是输出验证码图片的html代码

<code><img  id="chaptcha" border="1" src="chaptcha_img.php?r=<?php%20echo%20rand();?>"    style="max-width:90%"  style="max-width:90%" alt="php制作图片验证码echo $url和echo file_get_content($url)的区别" ></code>
Copy after login
Copy after login

下面是生成图片路径的chaptcha.php

<code><?php session_start();
    $table = array(
        "pic0" => "乌龟",
        "pic1" => "兔子",
        "pic2" => "狗",
        "pic3" => "猫",
        "pic4" => "青蛙"
    );

    $randomkey = array_rand($table,1);

    $_SESSION['authcode'] = $table[$randomkey];
    header('content-type: image/jpg');

    // 错误方法,直接echo $url
    $url = "images/".$randomkey.".jpg";
    // echo $url;

    // 正确方法
    $content = file_get_contents($url);
    echo $content;</code>
Copy after login
Copy after login

回复内容:

在一个PHP中有个表单用于输出验证码图片,我原以为下面的代码中$url = "images/".$randomkey.".jpg"就是图片路径,为什么还需要file_get_content函数?我的理解是echo $url就输出了images/pic2.jpg,那么src="chaptcha_img.php?r="不就是src="images/pic2.jpg"吗?但这样输出不了图片,求解惑,感谢~

下面是输出验证码图片的html代码

<code><img  id="chaptcha" border="1" src="chaptcha_img.php?r=<?php%20echo%20rand();?>"    style="max-width:90%"  style="max-width:90%" alt="php制作图片验证码echo $url和echo file_get_content($url)的区别" ></code>
Copy after login
Copy after login

下面是生成图片路径的chaptcha.php

<code><?php session_start();
    $table = array(
        "pic0" => "乌龟",
        "pic1" => "兔子",
        "pic2" => "狗",
        "pic3" => "猫",
        "pic4" => "青蛙"
    );

    $randomkey = array_rand($table,1);

    $_SESSION['authcode'] = $table[$randomkey];
    header('content-type: image/jpg');

    // 错误方法,直接echo $url
    $url = "images/".$randomkey.".jpg";
    // echo $url;

    // 正确方法
    $content = file_get_contents($url);
    echo $content;</code>
Copy after login
Copy after login

直接echo $url 是直接打印字符串.怎么可能返回图片呢?
图片是一个文件,自然需要用引入文件的方式引入他
file_get_contents就是引入文件啊

至于html中没看出有图片,你直接进入图片地址看下有无图片先,没有的话就是有地方写错了

src的值是PHP文件对应的URL没错啊,但这个PHP应该输出一张图片也没错啊

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template