PHP无法将变量转换为int

时间:2017-01-11 06:52:07

标签: php

我努力将变量从$ _POST []转换为int(long)以满足需要很长时间的函数。

这个函数需要一些输入变量($ width和$ height),它们都很长。该脚本从$ _POST []获取这些变量,当然它们在获取时是字符串。我已经尝试了几种方法将这些变量转换为float,int和long:

$variable = (float) $_POST["variable"];

$variable = $_POST["variable"] + 0;

settype($variable, "float");

但无论我做什么,我仍然会在error.log中得到同样的错误:

PHP Warning: imagecreatetruecolor() expects parameter 1 to be long, string given in /bla bla bla/resize_image.php on line 30

它已经到了我厌倦了在Google上寻找解决方案的地步,因为无论如何似乎没有什么可以转换该死的东西。所以我问你们是否有我忽略的东西,或者这是否可能。

get_image.php

$url = "../../" . $_POST["url"];

$cropped = false;
$width = 0;
$height = 0;

if (isset($_POST["cropped"])) {
    $cropped = $_POST["cropped"];
}

if (isset($_POST["width"])) {
    $width = $_POST["width"];
}

if (isset($_POST["height"])) {
    $height = $_POST["height"];
}

//  Get image
$type = pathinfo($url, PATHINFO_EXTENSION);
$data = file_get_contents($url);

if ($width > 0 && $height > 0) {

    include "Classes/resize_image.php";

    settype ( $width , "float" );
    settype ( $height , "float" );

    $data = resize_image($url, $cropped, $width, $height, $_POST["type"]);
}

$base64 = base64_encode($data);
echo $base64;

resize_image.php (班级)

function resize_image($file, $w, $h, $crop=FALSE, $type) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
    if ($width > $height) {
        $width = ceil($width-($width*abs($r-$w/$h)));
    } else {
        $height = ceil($height-($height*abs($r-$w/$h)));
    }
    $newwidth = $w;
    $newheight = $h;
} else {
    if ($w/$h > $r) {
        $newwidth = $h*$r;
        $newheight = $h;
    } else {
        $newheight = $w/$r;
        $newwidth = $w;
    }
}

if ($type == "png") {
    $src = imagecreatefrompng($file);
} else if ($type == "jpeg") {
    $src = imagecreatefromjpeg($file);
}

$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

return $dst;

}

我迫切需要!!

2 个答案:

答案 0 :(得分:1)

警告

  

PHP警告:imagecreatetruecolor()期望参数1为long,给定字符串...

表示第一个参数是字符串。让我们看看resize_image.php中的函数调用:

$dst = imagecreatetruecolor($newwidth, $newheight);

第一个参数是$newwidth,分配给$w$h*$r。乘法的结果总是一个数字(浮点数或整数)。但是,$w传递给函数而没有类型转换:

if (isset($_POST["cropped"])) {
    $cropped = $_POST["cropped"];
}

// ...

$data = resize_image($url, $cropped, $width, $height, $_POST["type"]);

函数中的$cropped(第二个参数)也没有类型转换。

因此,您需要在函数调用中或$w内将resize_image强制转换为整数。最好清理函数体内的参数:

function resize_image($file, $w, $h, $crop=FALSE, $type) {
  $w = (int)$w;
  $h = (int)$h;
  // ...

啊,你可能并不想将$cropped作为$w传递。

答案 1 :(得分:0)

我想知道帖子是否真的是数字。 也许试试:

$int = (is_numeric($_POST['variable']) ? (int)$_POST['variable'] : 0);

如果不是数字,则返回0,您可以根据需要进行修改。