I am newbie trying to code a file upload validator that sends an image as a blob to a MySQL database. The image is taken from a gravity form file upload in wordpress (form ID is 1). When I run the below script, no blob is sent to my mallampati_images table, however the file format alert displays. It also outputs this error:
Warning: file_get_contents(/home/clients/4ceaa5faab208e8af4350138684e6d6d/web/wp-content/uploads/mallampati.png): failed to open stream: No such file or directory in /home/clients/4ceaa5faab208e8af4350138684e6d6d/web/wp-content/themes/twentytwelve/functions.php on line 535
What I do not understand is how to format the link to the file. I have been trying every way I could find on the net for some hours, but I cannot make it work. I edited the code below to return the link (that is a correct absolute link, it seems...)
The script:
function testimage($path)
{
if(!preg_match("/\.(png|jpg|gif)$/",$path,$ext)) return 0;
$ret = null;
switch($ext[1])
{
case 'png': $ret = @imagecreatefrompng($path); break;
case 'jpg': $ret = @imagecreatefromjpeg($path); break;
case 'gif': $ret = @imagecreatefromgif($path); break;
default: $ret = 0;
}
return $ret;
}
add_action("gform_after_submission_1", "input_fields", 10, 3);
function input_fields($entry){
global $wpdb;
if (isset($_FILES['input_1'])) {
$file_url = $entry['1'];
//$img_blob = file_get_contents($file_url);
$validate = testimage($file_url);
$udir = wp_upload_dir();
$basedir = $udir['basedir'];
$target=$basedir.'/'.basename($_FILES['input_1']['name']);
//$try = $_FILES['input_1']['tmp_name'];
$img_blob = file_get_contents ($target);
echo "<script type='text/javascript'>alert('value: $target');</script>";
}
if(!empty($validate)) {
echo "<script type='text/javascript'>alert('The file was of the correct format');</script>";
$SQL = "INSERT INTO mallampati_images (img_blob) VALUES ( $img_blob )";
$wpdb->query($SQL);
}
}
I finally made it.
Gravity forms seems to not handle files exactly as examples I have been looking at. The problem was that it resulted in an incorrect file path being used in the SQL query.
function testimage($path)
{
if(!preg_match("/\.(png|jpg|gif)$/",$path,$ext)) return 0;
$ret = null;
switch($ext[1])
{
case 'png': $ret = @imagecreatefrompng($path); break;
case 'jpg': $ret = @imagecreatefromjpeg($path); break;
case 'gif': $ret = @imagecreatefromgif($path); break;
default: $ret = 0;
}
return $ret;
}
add_action("gform_after_submission_1", "input_fields", 10, 2);
function input_fields($entry){
global $wpdb;
if(isset($entry[1])){
$valid = testimage($entry[1]);
if($valid){
$mpFilePath= $entry[1];
$blob = file_get_contents($mpFilePath) or die ('cannot read file');
$blob = mysql_escape_string($blob);
$SQL = "INSERT INTO mallampati_images (img_blob) VALUES ( '$blob' )";
$wpdb->query($SQL) or die ('query failed');
}
else{
echo "<script type='text/javascript'>alert('Incorrect file format');</script>";
}
}
}