So I downloaded and edited a script off the internet to pull an image and find out the hex values it contains and their percentages:
The script is here:
<?php
$delta = 5;
$reduce_brightness = true;
$reduce_gradients = true;
$num_results = 5;
include_once("colors.inc.php");
$ex=new GetMostCommonColors();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Colour Verification</title>
</head>
<body>
<div id="wrap">
<img src="http://www.image.come/image.png" alt="test image" />
<?php
$colors=$ex->Get_Color("http://www.image.come/image.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
$success = true;
foreach ( $colors as $hex => $count ) {
if ($hex !== 'e6af23') {$success = false; }
if ($hex == 'e6af23' && $count > 0.05) {$success = true; break;}
}
if ($success == true) { echo "This is the correct colour. Success!"; } else { echo "This is NOT the correct colour. Failure!"; }
?>
</div>
</body>
</html>
Here is a pastebin link to the file colors.inc.php
http://pastebin.com/phUe5Pad
Now the script works absolutely fine if I use an image that is on the server, eg use /image.png in the Get_Color function. However, if I try and use an image from another website including a http://www.site.com/image.png then the script no longer works and this error appears:
Warning: Invalid argument supplied for foreach() in ... on line 22
Is anyone able to see a way that I would be able to hotlink to images because this was the whole point of using the script!
You must download a file to the server and pass its full filename to the method Get_Color($img) as $img parameter.
So, you need to investigate another SO question: Download File to server from URL
The error indicates that the value returned by Get_Color is not a valid object that can be iterated on, probably not a collection. You need to know how the Get_Color works internally and what is returned when it doesn't get what it wants.
In the mean-time, you can download [with PHP] the image from the external url into your site, and into the required folder and read the image from there.
$image = "http://www.image.come/image.png";
download($image, 'folderName'); //your custom function
dnld_image_name = getNameOfImage();
$colors=$ex->Get_Color("/foldername/dnld_image_name.png");
By the way, did you confirm that the image url was correct?
Related
I´m running a php code inside an HTML code so that depending of the value of a variable a specific CSS file is selected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name = "viewport" content="width=device-width, initial-scale=1.0">
<title>Soluciones Elisar</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght#300;500;600&display=swap" rel="stylesheet">
<?php
$monitoreo = $_POST["actividad"];
$file='test.html';
$data = $monitoreo;
if ($data == 0) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles.css\";</style>";
}
if ($data == 1) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles2.css\";</style>";
}
if ($data == 2) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles3.css\";</style>";
}
if ($data == 3) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles4.css\";</style>";
}
if ($data == 4) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles5.css\";</style>";
}
if ($data == 5) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles6.css\";</style>";
}
?>
</head>
<body>
However the HTML file on my server ignores the CSS file and just prints
#import \"/css/styles.css\";"; } if ($data == 1) { echo ""; } if ($data == 2) { echo ""; } if ($data == 3) { echo ""; } if ($data == 4) { echo ""; } if ($data == 5) { echo ""; } ?>
I dont know if it´s my code or if I´m misunderstanding how php and HTML work. Thank you
How are you viewing what the server is producing? If you're using the browser's inspector, bear in mind that this does not show the actual source code — it shows the browser's best interpretation of the source code, with invalid HTML tidied up. You can view the actual source code with the "View Source" option in the browser; the usual shortcut in most browsers is Ctrl+U.
If you do that, my guess (I could be wrong) is that you'll see that the PHP isn't running at all, and what's being served to the browser is the actual PHP code you've written. If I do not mistake my guess, your problem is not a coding issue, but a server configuration issue.
The PHP file should be run and parsed on the server, and the output of that PHP should be sent to the browser, to be parsed there. Exactly how you tell the server to run and parse PHP varies from server to server, but usually it starts with naming the file with the .php extension (if you have full control of the server config, you can tell it to treat .html or even .asp or .whatever files as PHP if you want, but this is unusual and confusing, so you probably shouldn't). You'll also need to ensure that PHP is installed on the server, and that the server's PHP module is enabled for the site. You know your server better than we do, and can search for appropriate tutorials.
Try writing your code with single and double quotes like:
echo '<div class="card">';
It worked for me earlier when I had issues with php.
So I'm a bit stuck, and I've been given various solutions, none of which work. Any hotshot PHP folks out there? Here's the deal, I'm trying to get an image to display on my website, from another website, that has a randomly generated IMG. Though I'm actually trying to do this off a personal art site of mine, this example will serve perfectly.
http://commons.wikimedia.org/wiki/Special:Random/File
A random image page with an image on it pops up with that link. Now, I'd like to display THAT random image, or whatever image comes up, on another site. The two possible solutions I have encountered is gathering an array of URL LINKS from a given link. And then re displaying that array as images on another site, like a: < a href="https
The code I get back from what I'm talking about looks like this:
Array
(
[0] => https ://kfjhiakwhefkiujahefawef/awoefjoiwejfowe.jpg
[1] => https ://oawiejfoiaewjfoajfeaweoif/awoeifjao;iwejfoawiefj.png
)
Instead of the print out however, I'd like the actual images displayed, well specifically array [0], but one thing at a time. The code that's actually doing this is:
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
$url = 'http://commons.wikimedia.org/wiki/Special:Random/File';
// Fetch page
$string = FetchPage($url);
// Regex that extracts the images (full tag)
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $string, $out, PREG_PATTERN_ORDER);
$img_tag_array = $out[0];
echo "<pre>"; print_r($img_tag_array); echo "</pre>";
// Regex for SRC Value
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER);
$images_url_array = $out[1];
echo "<pre>"; print_r($images_url_array); echo "</pre>";
// Fetch Page Function
function FetchPage($path)
{
$file = fopen($path, "r");
if (!$file)
{
exit("The was a connection error!");
}
$data = '';
while (!feof($file))
{
// Extract the data from the file / url
$data .= fgets($file, 1024);
}
return $data;
}
for($i=0; $i<count($arr1); $i++) {
echo '<img src="'.$arr1[$i].'">';
}
?>
Solution two,
Use a file_get_contents command. Which is this:
<?php
$html =
file_get_contents("http://commons.wikimedia.org/wiki/Special:Random/File");
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$image_src = $xpath->query('//div[contains(#class,"fullImageLink")]/a/img')
[0]->getAttribute('src') ;
echo "<img src='$image_src'><br>";
?>
However, there's unfortunately an error message I get: Fatal error: Cannot use object of type DOMNodeList as array in /home/wilsons888/public_html/wiki.php on line 11. Or, if I remove a "}" at the end, I just get a blank page.
I have been told that the above code will work, but with openssl extension included. Problem is, I have no idea how to do this. (I'm very new to PHP). Anyone know how to plug it in, so to speak? Thank you so much! I feel like I'm close, just missing the last element.
I was able to load the random image, and "print it" as an image directly (so you can embed the php file directly on the IMG tag) using this code:
<?php
$html = file_get_contents("http://commons.wikimedia.org/wiki/Special:Random/File");
$dom = new DOMDocument();
$dom->loadHTML($html);
$remoteImage = $dom->getElementById("file")->firstChild->attributes[0]->textContent;
header("Content-type: image/png");
header('Content-Length: ' . filesize($remoteImage));
echo file_get_contents($remoteImage);
?>
Get a new file called showImage.php and put this code in it:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<img src="test.php">
</body>
</html>
Next, go to your browser and get the showImage.php path, and will show a random image fromt he site you asked...
I'm Vietnamese and i want to upload a utf-8 filename like
Tên Tệp Tiếng Việt.JPG
Here is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>utf-8</title>
</head>
<body>
<?php
if(isset($_POST["submit"])) {
if($_FILES["upload"]["error"] > 0 ) echo "FILE ERROR!";
else
{
$base_dir = "D:/";
$fn = $_FILES["upload"]["name"];
$fn2 = $base_dir.$fn;
move_uploaded_file($_FILES["upload"]["tmp_name"],$fn2);
}
}
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<input type="file" name="upload" id="upload" />
<input type="submit" name="submit" id="submit" value="Send" />
</form>
</body>
</html>
but when i upload that i see on my computer D:\ has a file like
Tên Tệp Tiếng Việt.JPG
How to fix that thanks
I'm on Windows 8 chinese version, and I deal with similar problem with this:
$filename = iconv("utf-8", "cp936", $filename);
cp stands for Code page and cp936 stands for Code page 936, which is the default code page of simplified chinese version of Windows.
So I think maybe your problem could be solved in a similar way:
$fn2 = iconv("UTF-8","cp1258", $base_dir.$fn);
I'm not quite sure whether the default code page of your OS is 1258 or not, you should check it yourself by opening command prompt and type in command chcp. Then change 1258 to whatever the command give you.
UPDATE
It seems that PHP filesystem functions can only handle characters that are in system codepage, according to this answer. So you have 2 choices here:
Limit the characters in the filename to system codepage - in your case, it's 437. But I'm pretty sure that code page 437 does not include all the vietnamese characters.
Change your system codepage to the vietnamese one: 1258 and convert the filename to cp1258. Then the filesystem functions should work.
Both choices are deficient:
Choice 1: You can't use vietnamese characters anymore, which is not what you want.
Choice 2: You have to change system code page, and filename characters are limited to code page 1258.
UPDATE
How to change system code page:
Go to Control Panel > Region > Administrative > Change system locale and select Vietnamese(Vietnam) in the drop down menu.
This meta has no effect:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
because the web server has already sent Content-Type header, and thus decided what the encoding will be. Web browsers send forms in the same encoding. The meta is useful when user is off-line.
So you have to sned http header Content-Type by yourself:
<?php header("Content-Type: text/html; charset=utf-8"); ?>
ensure that you put this before any html, content or whatever is sent.
Alternatively, accept-charset tag on form should work as weel:
<form accept-charset="utf-8">
I am Persian and I have same problem with utf-8 character in my language.
I could solve my problem with this code:
$fn = $_FILES["upload"]["name"]; // name of file have some utf-8 characters
$name=iconv('utf-8','windows-1256', str_replace('ی', 'ي', $fn));
move_uploaded_file($_FILES["upload"]["tmp_name"],$name );
I am not sure about vientam language but maybe you can use the same code as above with a few changes:
$fn = $_FILES["upload"]["name"]; // name of file have some utf-8 characters
$name=iconv('utf-8','cp936', $fn);
move_uploaded_file($_FILES["upload"]["tmp_name"],$name );
The only solution I have found so far.. (2014 year):
1) I dont store files on my FTP in UTF-8 string. Instead, i use this function, to rename the uploaded files:
<?php
// use your custom function.. for example, utf8_encode
$newname = utf8_encode($_FILES["uploadFile"]["name"]);
move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $newname);
?>
2) Now you can rename (or etc) $newname;
For a start get detecting filename encoding (before uploading).
print_r($_FILES["upload"]);
Insert filename to decoder and check encoding.
Sorry! your question is about file name.
You must save your file name with iconv but read without this.
for saving:
<?php
$name = $_FILES['photo']['name'];
$unicode = iconv('windows-1256', 'utf-8', $name);
move_uploaded_file($_FILES['photo']['tmp_name'], 'photos/' . $name);
mysql_query("INSERT INTO `photos` (`filename`) VALUES ('{$unicode}')");
?>
for reading:
<?php
$images = mysql_query('SELECT * FROM `photos`');
if($images && mysql_num_rows($images) > 0) {
while($image = mysql_fetch_assoc($images)) {
$name = iconv('utf-8', 'windows-1256', $image['filename']);
echo '<img src="photos/' . $name . '"/>';
}
mysql_free_result($images);
}?>
function convToUtf8($str)
{
if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" )
{
return iconv("gbk","utf-8",$str);
}
else
{
return $str;
}
}
$filename= convToUtf8($filename) ;
try this
$imgname = $_FILES['img'] ['name'] ;
$imgsize = $_FILES['img'] ['size'] ;
$imgtmpname = $_FILES['img'] ['tmp_name'] ;
$imgtype = $_FILES['img'] ['type'] ;
$size = 1024;
$imgtypes = array('image/jpeg','image/gif','image/png');
$folder = "up";
if(empty($imgname)){
echo "Shose ur photo";
}else if(!in_array($imgtype,$imgtypes)){
echo "this photo type is not avalable";
}else if($imgsize > $size){
echo "this photo is dig than 6 MB";
}else if($imgwidth > 5000){
echo "the file is to big";
}
else{
move_uploaded_file($imgtmpname, $folder, $filename);
}
You can use this
$fn2 = basename($_FILES['upload']['name']);
I'm Vietnamese and i want to upload a utf-8 filename like
Tên Tệp Tiếng Việt.JPG
Here is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>utf-8</title>
</head>
<body>
<?php
if(isset($_POST["submit"])) {
if($_FILES["upload"]["error"] > 0 ) echo "FILE ERROR!";
else
{
$base_dir = "D:/";
$fn = $_FILES["upload"]["name"];
$fn2 = $base_dir.$fn;
move_uploaded_file($_FILES["upload"]["tmp_name"],$fn2);
}
}
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<input type="file" name="upload" id="upload" />
<input type="submit" name="submit" id="submit" value="Send" />
</form>
</body>
</html>
but when i upload that i see on my computer D:\ has a file like
Tên Tệp Tiếng Việt.JPG
How to fix that thanks
I'm on Windows 8 chinese version, and I deal with similar problem with this:
$filename = iconv("utf-8", "cp936", $filename);
cp stands for Code page and cp936 stands for Code page 936, which is the default code page of simplified chinese version of Windows.
So I think maybe your problem could be solved in a similar way:
$fn2 = iconv("UTF-8","cp1258", $base_dir.$fn);
I'm not quite sure whether the default code page of your OS is 1258 or not, you should check it yourself by opening command prompt and type in command chcp. Then change 1258 to whatever the command give you.
UPDATE
It seems that PHP filesystem functions can only handle characters that are in system codepage, according to this answer. So you have 2 choices here:
Limit the characters in the filename to system codepage - in your case, it's 437. But I'm pretty sure that code page 437 does not include all the vietnamese characters.
Change your system codepage to the vietnamese one: 1258 and convert the filename to cp1258. Then the filesystem functions should work.
Both choices are deficient:
Choice 1: You can't use vietnamese characters anymore, which is not what you want.
Choice 2: You have to change system code page, and filename characters are limited to code page 1258.
UPDATE
How to change system code page:
Go to Control Panel > Region > Administrative > Change system locale and select Vietnamese(Vietnam) in the drop down menu.
This meta has no effect:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
because the web server has already sent Content-Type header, and thus decided what the encoding will be. Web browsers send forms in the same encoding. The meta is useful when user is off-line.
So you have to sned http header Content-Type by yourself:
<?php header("Content-Type: text/html; charset=utf-8"); ?>
ensure that you put this before any html, content or whatever is sent.
Alternatively, accept-charset tag on form should work as weel:
<form accept-charset="utf-8">
I am Persian and I have same problem with utf-8 character in my language.
I could solve my problem with this code:
$fn = $_FILES["upload"]["name"]; // name of file have some utf-8 characters
$name=iconv('utf-8','windows-1256', str_replace('ی', 'ي', $fn));
move_uploaded_file($_FILES["upload"]["tmp_name"],$name );
I am not sure about vientam language but maybe you can use the same code as above with a few changes:
$fn = $_FILES["upload"]["name"]; // name of file have some utf-8 characters
$name=iconv('utf-8','cp936', $fn);
move_uploaded_file($_FILES["upload"]["tmp_name"],$name );
The only solution I have found so far.. (2014 year):
1) I dont store files on my FTP in UTF-8 string. Instead, i use this function, to rename the uploaded files:
<?php
// use your custom function.. for example, utf8_encode
$newname = utf8_encode($_FILES["uploadFile"]["name"]);
move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $newname);
?>
2) Now you can rename (or etc) $newname;
For a start get detecting filename encoding (before uploading).
print_r($_FILES["upload"]);
Insert filename to decoder and check encoding.
Sorry! your question is about file name.
You must save your file name with iconv but read without this.
for saving:
<?php
$name = $_FILES['photo']['name'];
$unicode = iconv('windows-1256', 'utf-8', $name);
move_uploaded_file($_FILES['photo']['tmp_name'], 'photos/' . $name);
mysql_query("INSERT INTO `photos` (`filename`) VALUES ('{$unicode}')");
?>
for reading:
<?php
$images = mysql_query('SELECT * FROM `photos`');
if($images && mysql_num_rows($images) > 0) {
while($image = mysql_fetch_assoc($images)) {
$name = iconv('utf-8', 'windows-1256', $image['filename']);
echo '<img src="photos/' . $name . '"/>';
}
mysql_free_result($images);
}?>
function convToUtf8($str)
{
if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" )
{
return iconv("gbk","utf-8",$str);
}
else
{
return $str;
}
}
$filename= convToUtf8($filename) ;
try this
$imgname = $_FILES['img'] ['name'] ;
$imgsize = $_FILES['img'] ['size'] ;
$imgtmpname = $_FILES['img'] ['tmp_name'] ;
$imgtype = $_FILES['img'] ['type'] ;
$size = 1024;
$imgtypes = array('image/jpeg','image/gif','image/png');
$folder = "up";
if(empty($imgname)){
echo "Shose ur photo";
}else if(!in_array($imgtype,$imgtypes)){
echo "this photo type is not avalable";
}else if($imgsize > $size){
echo "this photo is dig than 6 MB";
}else if($imgwidth > 5000){
echo "the file is to big";
}
else{
move_uploaded_file($imgtmpname, $folder, $filename);
}
You can use this
$fn2 = basename($_FILES['upload']['name']);
Download link:
Download php file
download.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Home</title>
</head>
<body>
<h1>PHP file</h1>
<?php
function get_text($text)
{
....
}
function get_time($time)
{
....
}
$url = "http://api.xxx.com/info.php?words=".$_GET['words']."&sort=".$_GET['sort']."&type="$_GET['type'];
$xml = simplexml_load_file($url);
if (count($xml))
{
foreach($xml->book as $book)
{
echo ....
}
}
?>
</body>
</html>
The download.php is a ready made API php script to provide webmasters upload to their FTP. Webmasters can be choose many options(e.g: download.php?words=2000&sort=popular&type=xml) from a form, then submit the form to get their custom API script.
This is the line that will replace the options after they submit the form.:
$url = "http://api.xxx.com/info.php?words=".$_GET['words']."&sort=".$_GET['sort']."&type="$_GET['type'];
This is the code to force download. But i don't know how to wrap whole page with $content = "";. I know how to wrap the HTML codes but how to wrap the PHP function and codes on the page?
header("Content-Disposition: attachment; filename="download.php");
print $content;
Not sure if that is what yo want; but you could create a second script that calls the first one, gets the output, and sends that with the mentioned headers:
<?php
$words = (int) $_GET['words'];
$sort = $_GET['sort'];
$url = sprintf("http://localhost/wherever/download.php?words=%d&sort=%s&type=xml", $words, $sort);
$content = file_get_contents($url);
header("Content-Disposition: attachment; filename="download.php");
print $content;
?>
Call that file "force_download.php" and let the users call Download php file instead.