I'm doing a script that takes the image from Twitter API, and return's it on base64, but I have troubles because the file is on a remote server (Twitter). Here I show the code, the main problem is with the fread() and filesize(). I get this:
Warning: filesize() [function.filesize]: stat failed for http://a0.twimg.com/profile_images/...jpg in...
<?
mysql_connect...;
mysql_select_db...;
$autho_name = ...;
include '../twitter/LibTwitter.php';
$sql = mysql_query("SELECT * FROM `users` ORDER BY id DESC");
while($result = mysql_fetch_array($sql)) {
$userid = $result["userid"];
$busqueda = $twitter->usersShow($userid);
$username = $busqueda["screen_name"];
$img_src = str_replace("_normal.", "_reasonably_small.", $busqueda["profile_image_url"]);
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
}
?>
I replaced personal data with ... because of obvious reasons, no problem with that. Thanks!
Just use file_get_contents() to fetch the image, then it's a simple matter of:
$img = file_get_contents('http://a0.twimg...etc....');
$size = strlen($img);
$base64 = base64_encode($img);
Related
I need the file to be downloaded from the directory that is saved. I have used the following code
$sqlh = mysql_query("SELECT * FROM tbl_health WHERE tbl_users_users_id = '".$id."'", $con) or die(mysql_error());
while($data = mysql_fetch_array($sqlh)){
$data['link'];
echo "<a href='view.php?id=" .$data['health_id']. "'>Download</a>";
}
view.php is
require_once('includes/db.php');
if(isset($_GET['id'])){
$sql = mysql_query("SELECT * FROM tbl_health WHERE health_id='".$_GET['id']."'") or die(mysql_error());
echo $_GET['id'];
$data = mysql_fetch_array($sql);
$file = $data['link'];
$name = "health/".$file;
header("Content-Type: application/pdf");
header("Content-Length: ". filesize($name));
header("Content-Disposition:attachment;filename=". $file);
$fp = #fopen($name, "r");
fclose($fp);
}
The file is downloading, but when I open it the contents of the file are missing. When I try to open it through a browser it says This PDF document might not be displayed correctly.
Please can anyone tell me what I have gone wrong.
firstly the echo before the header calls should be giving you an error if you had error checking on.
then fopen creates a stream handle, but you do nothing with it. readfile() will send the file to the client.
I keep getting 3 errors when I use this code:
Warning: fopen() [function.fopen]: Filename cannot be empty
Warning: fwrite(): supplied argument is not a valid stream resource
Warning: fclose(): supplied argument is not a valid stream resource
I don't know what to do. I'm a php noob.
<?php
$random = rand(1, 9999999999);
$location = "saves/".$random;
while (file_exists($location)) {
$random = rand(1, 999999999999);
$location = "saves/".$random;
}
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>
As per your original question before your edit:
Since the file doesn't exist yet, your while condition won't work and that's why you're getting those error messages.
And since you're using a random number for the file, you will never know which file to open in the first place. Just remove the while loop.
Try this:
<?php
$random = rand(1, 999999999999);
$location = "saves/".$random;
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>
From the code you have, it looks like $location only exists inside the scope of the while loop. Try
<?php
$location = "";
while (file_exists($location)) {
$random = rand(1, 999999999999);
$location = "saves/".$random;
}
$content = "some text here";
$fp = fopen($location,"wb");
fwrite($fp,$content);
fclose($fp);
?>
first of all, you must set values to your $location variable or since the file is not yet created try this:
$random = rand(1, 999999999999);
$location = "saves/".$random;
$content = "some text here";
//if(file_exists($location)) $fp = fopen($location,"wb");
$fp = fopen($location, 'wb') or die('Cannot open file: '.$location); //implicitly creates file
fwrite($fp,$content);
fclose($fp);
I post few days ago
Pass MySQL medium blob into IOS NSData\UIImage
but didn't manage to find a solution yet. my specific problem is that when I retrieve images from database, blob or text, it returns NULL, rows that don't have variables in them just return blank
while ($row = mysql_fetch_array($result)) {
$add = array();
$add["Id"] = $row["Id"];
$add["Mail"] = $row["Mail"];
$add["Category"] = $row["Category"];
$add["Phone"] = $row["Phone"];
$add["Msgs"] = $row["Msgs"];
//image from blob
$add["Picture"] = $row["Picture"];
// push single add into final response array
array_push($response["adds"], $add);
}
is there any other way to address images from blob\text?! I tried https://stackoverflow.com/a/6273415/1333294 but nothing works for me.
Finally!!
$img = $row["Picture"];
$b64img = base64_encode ($img);
$b64img = mysql_real_escape_string($b64img);
$add["Picture"] = $b64img;
simple as that! and xcode get it as base64 string and nut NULL. thanks for suggestions...
Add the following code
header("Content-type: image/jpeg");
echo $row['picture'];
// Display image with img html tag
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['picture'] ) . '" />';
echo 'Hello world.';
please find sample code
$response["adds"] = array();
$add = array();
$add["Id"] = 1;
$add["Mail"] = "test#mm.com";
$add["Category"] = "category";
$add["Phone"] = "1234567";
$add["Msgs"] = "ths s txt msg";
//image from blob
$add["Picture"] = "pciture";
// push single add into final response array
array_push($response["adds"], $add);
print_r($response["adds"]);
header("Content-type: image/jpeg");
print $response["adds"][0]['Picture'];
I am trying to write a function to process images in mySQL / PHP but cannot work out how to store the results. I have included a stripped down version of the code to demonstrate the problem.
The blobs in image.image_o are all correctly stored and can be used to output images to the web page. The function runs without error but afterwards the blobs in image.image_r are just a few bytes long and contain text like "Resource id #5"
I am sure I am doing something dumb - just can't see what it is.
function process_images(){
global $mysql
$sql = "select id, image_o from image";
$res = mysqli_query($mysqli, $sql);
if ($res){
while ($ay = mysqli_fetch_array($res, MYSQLI_ASSOC)){
$id = $ay['id'];
$im = imagecreatefromstring($ay['image_o']);
// do something useful with the image
$sql2 = "update image set image_r = '{$im}' where id = $id";
$res2 = mysqli_query($mysqli, $sql2);
if ($res2){
// blah blah
}else{
echo mysqli_error($mysqli)." in res2";
}
}
}else{
echo mysqli_error($mysqli)." in res";
}
}
I agree with the commentary above that this is generally not advisable. However, here is a great article on why you MIGHT do it, and how. It also highlights some of the cons of storing images in the database.
http://forum.codecall.net/topic/40286-tutorial-storing-images-in-mysql-with-php/
You need to make sure you read the data into the field. Not just the file pointer:
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Now take the contents of data and store THAT
In a nutshell, imagecreatefromstring returns "An image resource will be returned on success", not the contents of the file itself. You need to read the contents of that resource before you can store it. Using your code, make the following changes:
function process_images(){
global $mysql
$sql = "select id, image_o from image";
$res = mysqli_query($mysqli, $sql);
if ($res){
while ($ay = mysqli_fetch_array($res, MYSQLI_ASSOC)){
$id = $ay['id'];
$im = imagecreatefromstring($ay['image_o']);
$tempFileName = '/tmp/' . $id . 'jpg';
$imTempFile = imagegd($im, $tempFileName);
$fh = fopen($tempFileName, "r");
$data = fread($fh, filesize($tempFileName));
// do something useful with the image
$sql2 = "update image set image_r = '{$data}' where id = $id";
$res2 = mysqli_query($mysqli, $sql2);
if ($res2){
// blah blah
}else{
echo mysqli_error($mysqli)." in res2";
}
//delete the temp file
unlink($tempFileName);
}
}else{
echo mysqli_error($mysqli)." in res";
}
}
I have had lots of help with creating a PHP script that basically grabs the latest titles and thumbnails of videos from a YouTube playlist. This used to work, but somehow it has stopped working. Could anybody help?
The php script is running at http://new.fearofmobs.com/playlist.php, i've switched on error reporting. The script is mean't to return thumbnails from a YouTube playlist and cache them hourly. The code
<?php error_reporting(E_ALL ^ E_NOTICE); ini_set('display_errors', 1);?>
<?php
$cachefile = 'videobrowser.txt';
$cache_timer = 3600 + #filemtime($cachefile);// files timestamp + 3600 seconds
if (file_exists($cachefile) && time() < $cache_timer ) {
}
else {
$data = file_get_contents("http://gdata.youtube.com/feeds/api/playlists/C82EBDAC0429B6A2?orderby=published&max-results=12");
$fh = fopen($cachefile, 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
}
$thumbnail ='';
$data = simplexml_load_file($cachefile);
$xml = simplexml_load_string($data);
foreach($xml->entry as $playlist){
$media = $playlist->children('http://search.yahoo.com/mrss/');
$attrs = $media->group->thumbnail[1]->attributes();
$thumb = $attrs['url'];
$attrs = $media->group->player->attributes();
$video = $attrs['url'];
$title = substr( $media->group->title, 21);
$url = $video;
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
$vid_Id = $my_array_of_vars['v'];
###################NEW CODE
$toggle = 'hotlink';// replace 'hotlink' with 'null' to save images locally
if ($toggle == 'hotlink'){
$image_ID = $thumb; // hotlink images from YouTube
}
else{
///////////////////////////////// Save Images To Local Webserver
///////////////////////////////// just in case Youtube objects to hotlinking
$image_ID = $vid_Id.".jpg"; /// or use sub folder for neatness -> "images_folder/".$vid_Id.".jpg"
$image_saved = #filemtime($image_ID);// # is used to suppress the error caused by the image not having been seen before
if (!$image_saved){/// if you can't find it on local server go fetch it and save to the sites server
file_put_contents($image_ID, file_get_contents($thumb));
//// you can delete the line below
echo ' fecthed image >> '.$image_ID."<br>" ;
//// you can delete the line above
}//// close if image saved
} ##################### END NEW CODE
$thumbnail .= '<div style="float:left; cursor:pointer;">
<p class="crop"><a class="videobox various iframe" href="http://www.youtube.com/embed/' . $vid_Id . '?autoplay=1&hd=1" onclick=swapper('. $vid_Id .')><img src="' .$image_ID . '" title="' . $title . '" width="74" height="56"/></a></p></div>';
}
?>
<?php echo $thumbnail; ?>
The errors
Warning: simplexml_load_file(): videobrowser.txt:1: parser error : Document is empty in /hermes/waloraweb095/b2598/moo.fearofmobscom/fearofmobs2/playlist.php on line 16
Warning: simplexml_load_file(): in /hermes/waloraweb095/b2598/moo.fearofmobscom/fearofmobs2/playlist.php on line 16
Warning: simplexml_load_file(): ^ in /hermes/waloraweb095/b2598/moo.fearofmobscom/fearofmobs2/playlist.php on line 16
Warning: simplexml_load_file(): videobrowser.txt:1: parser error : Start tag expected, '<' not found in /hermes/waloraweb095/b2598/moo.fearofmobscom/fearofmobs2/playlist.php on line 16
Warning: simplexml_load_file(): in /hermes/waloraweb095/b2598/moo.fearofmobscom/fearofmobs2/playlist.php on line 16
Warning: simplexml_load_file(): ^ in /hermes/waloraweb095/b2598/moo.fearofmobscom/fearofmobs2/playlist.php on line 16
Warning: Invalid argument supplied for foreach() in /hermes/waloraweb095/b2598/moo.fearofmobscom/fearofmobs2/playlist.php on line 18
If anybody needs any further information please do let me know.
As far as I can tell, you are not entering the else clause that populated videobrowser.txt:
if (file_exists($cachefile) && time() < $cache_timer ) {
// you are going here
}
else {
// but you should be going here
$data = file_get_contents("http://gdata.youtube.com/feeds/api/playlists/C82EBDAC0429B6A2?orderby=published&max-results=12");
$fh = fopen($cachefile, 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
}
I'm guessing that at some point videobrowser.txt was created with no content (a completely empty file). This means that you are not re-populating the file, and are expecting it to be filled.
Check and see if videobrowser.txt exists, and if it does, delete it.