Make Image into String to Put in MySQL to Solve No Write Permissions Problem
- How to Get Around Needing Write Permissions When Saving Images on Server
- Make image into string to put in mysql to solve no write permissions problem
- Read image immediately into mysql to solve no write permissions problem
- Image enlarges on mouseover but uses PHP script in all image tags
- Building a picture from scratch and displaying it on a web page but with no write permissions
Building a picture from scratch and displaying it on a web page but with no write permissions
This page is a tutorial on Make Image into String to Put in MySQL to Solve No Write Permissions Problem. Our overall method is to use MySQL and PHP. All over the Internet, the discussions of using PHP to upload image files to the server seem to have a common thread. "You have to have write permissions." This is sort of true and sort of not true. All of our experiments were done with CHMOD 750 on our public_html folder and CHMOD 755 on our test subfolder. Server warnings were all we got from trying to CHMOD from either a script or from our FTP program. So we had to live without write permissions (sigh . . . ). But we still got the job done 3 different ways!
Since none of the forums or expert sites (in our research) ever mentioned any alternatives to the write permissions method, we felt prompted into action—hence this tutorial.
For those of you with write permissions, How to Get Around Needing Write Permissions When Saving Images on Server contains listings of the 2 files that will let you upload and manipulate images.
The following method is a perfect workaround for needing write permissions that you simply do not have and cannot get.
Here are this workaround's steps: get the image URL via a form; and use the PHP file_get_contents() function to put the image into a string; and the base64_encode() function to make it POST better; and, once POSTed to the db-stuffing script, the base64_decode() function is used to decode the encode; and the mysql_real_escape_string() function is used to get it safe to put into a MySQL table; then we put it in the db table and use the imagecreatefromstring() function to turn the long string into an image; and the header('Content-Type: image/jpg') and imagejpeg() functions to make the image; and the <img src="show-pic.php"> method on an HTML page to display the image on a web page by running the script from an image tag.
If you'd prefer file functions like fread() to file stringifying functions like file_get_contents(), feel free to use our other workaround: Read image immediately into mysql to solve no write permissions problem.
As trivial an HTML page as the following can display your MySQL-stored image in the browser (the width parameter shown will turn a large image into a thumbnail, while leaving out parameters will let the image display at its original size):
<html>
<head>
</head>
<body>
<img src="show-pic.php" alt="Hillary" width="100px">
</body>
</html>
Anyway, the Make Image into String to Put in MySQL to Solve No Write Permissions Problem script is below, and it is composed of 3 parts. Of course, to actually use the script on a web page, you need some version of the script above which merely runs the show-pic.php script from a web page image tag, thereby displaying one or more image. The first script is called: send-image-form.php
<html>
<head>
<style type="text/css">
BODY {background-color:#88f;}
.pw{position:absolute;top:120px;left:300px}
</style>
</head>
<body>
<?php
error_reporting(E_ERROR);
$f=$_POST['myjpg'];$n=$_POST['imagename'];
if (!isset($f)){
echo '<div class="pw"><table class="ts"><tr><td style="text-align:center"><form id="formjpg" name="formjpg" method="post" action="send-image-form.php"><b>JPG URL (must end with .jpg)</b><BR><label for="JPG URL">JPG URL: </b><input type="text" name="myjpg" size="66" maxlength="99" value=""></label><br><br><label for="Image name">Image name: </b><input type="text" name="imagename" size="50" maxlength="50" value=""></label><br><br><input type="submit" value="Submit URL"><br><br><input type="reset" value="Reset"></form></td></tr></table></div>';
}else{
if (substr($f,-4)==".jpg"){
$f=strip_tags($f);
$L=strlen($f);
$f = str_replace(" ", "%20", $f); $f=trim($f);
$f = base64_encode(file_get_contents($f));
?>
<form name="MyForm" method="POST" action="make-pic.php">
<input type="hidden" name="jpg" value="<?php echo $f; ?>">
<input type="hidden" name="imagename" value="<?php echo $n; ?>">
</form>
<script language="javascript">
//var jpg = <?php echo json_encode($f); ?>;
//document.MyForm.jpg.value=jpg;
document.MyForm.submit();
</script>
<?php
}}
?>
</body>
</html>
In the script above, after some CSS styling we show a form in which the user can input the image URL and a name to call it. Note that the form action is to refresh the page to send the form input to the PHP part of the page via POSTing. Note also that the form does not display during the refresh because the input gets detected with the PHP isset function. If the script detects that the image is a .jpg type, it runs the strip_tags() function to be safe, the str_replace() function to make URLs with spaces in them PHP readable, and the trim() function to get rid of surrounding spaces. The image data gets pulled from the image URL with file_get_contents() and the data is made more POSTable with base64_encode(). You may notice that we attempted to stick the 50,000 to 90,000 bytes of data into the hidden form's hidden field, but this use of json_encode() failed, so we just snuck it into the form with PHP. Perhaps there was a way for json_encode() to handle it without choking. If so, it got by us. Oh well, the PHP method works fine. The only reason we ended up leaving the JavaScript section is because of the document.MyForm.submit() line, which submits the invisible form. Note the lack of a submit button. One can submit via JavaScript without need of submit being in the form anywhere. Forms are quite forgiving that way.
The next script is called make-pic.php
<?php
include_once"config.php";
$sql = "CREATE TABLE IF NOT EXISTS userimages (
id int(4) NOT NULL AUTO_INCREMENT,
image mediumblob NOT NULL,
image_size int(4) NOT NULL,
image_name varchar(50) NOT NULL default '',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
mysql_query($sql);//mediumblob max is 16mb
$jpg=$_POST['jpg'];
$thename=$_POST['imagename'];
$jpg = base64_decode($jpg);
$L=strlen($jpg);
if ($jpg !== false){
$jpg=mysql_real_escape_string($jpg);
mysql_query("INSERT INTO userimages (id, image, image_size, image_name)
VALUES(NULL,'$jpg','$L','$thename')") or die(mysql_error());
}else{
echo 'Image failed.';}
?>
In the script above, we use the config.php file to get connected up to the correct MySQL table since we are about to WRITE to it. WE are allowed to write to it since we are the 7 in the CHMOD 750 of our public_html folder. There wouldn't be much use of a host offering MySQL in their control panels if one could not use them! So now you see the trick. We avoid the need for write permissions by using the methods that ARE open to us, like file_get_contents() and MySQL queries. This may not upload the image files to file folders, but it surely does upload their data to MySQL, which affords us the further opportunity of displaying the data as an image on a web page(s) of our choice. Think of those mean old hosts as merely protecting our files and folders from dastardly devils with hacking in mind, by denying the CHMOD 777. Surely we can appreciate that! So—use our workarounds.
Now we make the MySQL table, if we haven't already done so, using the mediumblob type for our data. It has a maximum of 16MB, although in practice we'd tend to disallow any image over 200K. If the users have a bigger one, introduce these users to Irfanview or ImageForge or other graphics apps that can easily optimize their images to a much smaller file size. How to Get Around Needing Write Permissions When Saving Images on Server has an upload feature (for those allowed 777) that uses imagejpeg($tmp,null,70) to optimize and reduce file size, as well as a type checker and size checker to ensure only JPEGs under 200K are uploaded, as well as an image dimension tweaker that brings the size to a 570-pixel-wide maximum. (You may prefer different parameters—if so, tweak away!)
Note that the POSTed image string now uses base64_decode() to reverse what the previous script did with base64_encode() (which was done for better POSTing). Finally this image string data gets a taste of mysql_real_escape_string() to make it safer to put into MySQL. Then we INSERT the data into the database table and get ready for a call to action that grabs the data and makes it into an image again. But that script is below.
The next script is called show-pic.php
<?php
include_once"config.php";
$image_name="hillary";
$sql = mysql_query("SELECT image FROM userimages WHERE image_name = '$image_name'") or die(mysql_error());
$row=mysql_fetch_assoc($sql);
$jpg=$row['image'];
$jpg = imagecreatefromstring($jpg);
if ($jpg !== false){
header('Content-Type: image/jpg');
header('Content-Disposition: inline');
imagejpeg($jpg);
imagedestroy($jpg);
}else{
echo 'Image failed.';}
?>
</B></P>
In the script above, we use the config.php file to get connected up to the correct MySQL table. And we made the simplest possible choices, like hardcoding in the image name and thereby using this script exclusively for that image. You'll of course want to use a URL query string like <img src="show-pic.php?p1=4" alt="Lady" width="100px"> on your web page and a GET in this show-pic.php script that grabs the image id and uses that in the WHERE part of the SELECT phrase in the MySQL query, since GETs grab query strings from URLs without needing POSTs.
So we query the db table and use the imagecreatefromstring() function to turn the resultant long string into an image; and the header('Content-Type: image/jpg') and imagejpeg() functions to make the image. But since the web page script below, or a tweaked one, like the one mentioned below, is where the actual image will display, we need to recall that imagejpeg($jpg) creates the image but is fine about the fact that what it makes is shown elsewhere—think of it as a wee bit of notoriety. (The header('Content-Disposition: inline'); line is an optional function to encourage the browser to display the image, not try to send it somewhere as an attachment. The main thing that went wrong in our experiments was the image elicited a Would You Like To Open or Save the file, or Cancel? But our workarounds seem to have precluded such browser impertinence. I.e., they work super for us. Your mileage may vary—probably due to different PHP directives or no GD support.)
Although you will like Image enlarges on mouseover but uses PHP script in all image tags better (since it uses the show-pic.php script but does more), as trivial an HTML page as the following can display your MySQL-stored image in the browser (the width parameter shown will turn a large image into a thumbnail, while leaving out parameters will let the image display at its original size):
<html>
<head>
</head>
<body>
<img src="show-pic.php" alt="Hillary" width="100px">
</body>
</html>