I have a file called 'test.php' inside the file i have the following code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
jQuery.ajax({
url : 'http://example.com/TEST/images.php',
type : 'POST',
data : {
name : 'black-ring1.gif'
},
success : function(data, status) {
if(data){
alert(data);
}
}
});
});
});
</script>
</head>
<body>
<p id="btn">Button</p>
</body>
</html>
My 'images.php' file which executes when ajax called conteains the following code.
<?php
$image_name = $_POST['name'];
$src = "http://example.com/images/icons/" . $image_name;
if(file_exists($src)){
echo "Exists";
}else{
echo "Does not exist";
}
inside the 'images.php' file_exists($url) gives me always wrong answer(Does not exist).. I am sure $url really exits in the given url.. But why it does not work. How i can make it work ... Please help me.. Thanks..
file_exists can't be used with http:// URLs. From the documentation:
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
If you follow that link and then follow the http:// link, it says:
Supports stat() No
Instead, you can simply try to open the URL. If it succeeds then the URL exists.
<?php
$image_name = $_POST['name'];
$src = "http://example.com/images/icons/" . $image_name;
if($fh = fopen($src)){
echo "Exists";
close($fh);
}else{
echo "Does not exist";
}
First you need to validate that you pass the name
(!empty($_POST["name"])) {
$image_name = $_POST['name'];
$src = "http://example.com/images/icons/" . $image_name;
}else{
echo "no, name";
}
then you can use CURL to check if the url exist
if(is_url_exist($src)){
echo "Exists";
}else{
echo "Does not exist";
}
this code is from this SO
function is_url_exist($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == 200){
$status = true;
}else{
$status = false;
}
curl_close($ch);
return $status;
}
you can also try from this SO
if (getimagesize($src) !== false) {
echo "Exists";
}else{
echo "Does not exist";
}
file_exists() checks files. A URL is not a file. If the image file you're looking for is on your local server, then you can just use the full path name to it:
if (file_exists('/path/to/images/foo.png')) {
...
}
If the file is on a remote server, and you want to test that the URL referencing it is valid, you might use CURL to perform a HEAD request against it:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
$result = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
if ($info['http_code'] == 200) {
echo "image exists\n";
}
I would not recommend doing something like file_get_contents($url) unless you actually need the image contents, because this will actually download the full image and then just throw it away, wasting bandwidth for both you and the remote server.
Related
I have a very simple piece of code which should return me a JSON object, but doesn't return any value.
When I access the url https://api.kraken.com/0/public/Time directly, you can see the desired JSON output.
However when calling the next function (on the url https://youreka-virtualtours.be/ethereum/functions.php?call=get_kraken), I don't get any output
<?php
if (isset($_GET['call'])) {
$error = '';
switch($_GET['call']) {
case 'get_kraken':
$url = 'https://api.kraken.com/0/public/Time';
$json = file_get_contents($url);
http_response_code(200);
header('Content-Type: application/json');
echo $json;
break;
}
}
?>
Edit: Question: What am I doing wrong since the output of my file_get_contents differs from what the url https://api.kraken.com/0/public/Time shows
The code works fine, I tested it on local. This means that one of two things are happening. 1 : your server does not have the ability to make a file_get_contents call. 2 : your URL is incorrect, you really should echo something in case that happens. Try this to test :
<?php
if(!isset($_GET['call']) || "get_kraken" !== #$_GET['call'] ) {
echo "could not find a valid URL";
}elseif (isset($_GET['call'])) {
$error = '';
switch($_GET['call']) {
case 'get_kraken':
$url = 'https://api.kraken.com/0/public/Time';
$json = file_get_contents($url);
http_response_code(200);
header('Content-Type: application/json');
echo $json;
break;
}
}
?>
I'm developing a browser extension (content script) that scans and highlights certain words on a page, and uses AJAX and PHP to echo back content into a tooltip that appears when a user hover over said words. One thing that gets echoed back from the PHP file is an image, but my problem is that I don't have an image for every keyword - what I want is the PHP to only echo back an image when one exists at the given URL. As of now, certain words show images, others show the "image not found" icon. What I want is for no "image not found" icon if the image doesn't exist.
I have the AJAX send the variable ($data) to the PHP files hosted on my website. Maybe have it check the HTTP header of the url before echoing?
Here is my code:
$data = $_POST['id'];
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
Why don't you just check it like this?
$data = $_POST['id'];
if($data !== "") {
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "http://extension.nicholasrub.in/headshots/notFound.png'>";
}
EDIT:
Use file_exists():
$data = $_POST['id'];
$imagePath = "/path/images/" . $data . ".png";
if (file_exists($imagePath)) {
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "http://extension.nicholasrub.in/headshots/notFound.png'>";
}
You can check if a file exists using this function
http://php.net/manual/en/function.file-exists.php
if you want to check image what is not exist on your server then use this code:
$data = $_POST['id'];
$imagePath = "http://extension.nicholasrub.in/headshots/$data.png";
echo "http://extension.nicholasrub.in/headshots/".(file_get_contents(imagePath) ? $data : 'notFound').".png'>"
I ended up solving the problem by checking whether the HTTP headers were 404 or not.
My Code:
$file = "http://extension.nicholasrub.in/headshots/" . $data . ".png";
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
if ($exists == true) {
echo "<div id='my-tooltip-2986234'><div><img src='http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "<div id='my-tooltip-2986234'><div>";
}
I am a newbie with codeigniter and I want to build a website using codeigniter framework. From first, it look fine I can use database, validation, email, session and then I try to attach a file and send with email :
$this->email->attach('/path/ofyour/constan/file.anything');
thats work too.
since that is a website I want my client to choose file they want to upload.
I try many method, and many of them tell to upload a file to server root and get the file_data, use file_data[file_patch]
$this->email->attach('file_data[file_path]');
the problem is:
since code igniter cant upload multiple data I must use plugin. I tried and its PAIN
I thing its not effective, upload data to server root and then to email?
it better to just get file_path of upload file and send them to email, how?
I build it with jquery mobile, what must I do?
Update
ok i decide to use uploadify i search every website and then i found here and my code is
uploadify.php
<?php
/*
* Functions taken from CI_Upload Class
*
*/
function set_filename($path, $filename, $file_ext, $encrypt_name = FALSE)
{
if ($encrypt_name == TRUE)
{
mt_srand();
$filename = md5(uniqid(mt_rand())).$file_ext;
}
if ( ! file_exists($path.$filename))
{
return $filename;
}
$filename = str_replace($file_ext, '', $filename);
$new_filename = '';
for ($i = 1; $i < 100; $i++)
{
if ( ! file_exists($path.$filename.$i.$file_ext))
{
$new_filename = $filename.$i.$file_ext;
break;
}
}
if ($new_filename == '')
{
return FALSE;
}
else
{
return $new_filename;
}
}
function prep_filename($filename) {
if (strpos($filename, '.') === FALSE) {
return $filename;
}
$parts = explode('.', $filename);
$ext = array_pop($parts);
$filename = array_shift($parts);
foreach ($parts as $part) {
$filename .= '.'.$part;
}
$filename .= '.'.$ext;
return $filename;
}
function get_extension($filename) {
$x = explode('.', $filename);
return '.'.end($x);
}
// Uploadify v1.6.2
// Copyright (C) 2009 by Ronnie Garcia
// Co-developed by Travis Nickels
if (!empty($_FILES)) {
$path = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
//$client_id = $_GET['client_id'];
$file_temp = $_FILES['Filedata']['tmp_name'];
$file_name = prep_filename($_FILES['Filedata']['name']);
$file_ext = get_extension($_FILES['Filedata']['name']);
$real_name = $file_name;
$newf_name = set_filename($path, $file_name, $file_ext);
$file_size = round($_FILES['Filedata']['size']/1024, 2);
$file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES['Filedata']['type']);
$file_type = strtolower($file_type);
$targetFile = str_replace('//','/',$path) . $newf_name;
move_uploaded_file($file_temp,$targetFile);
$filearray = array();
$filearray['file_name'] = $newf_name;
$filearray['real_name'] = $real_name;
$filearray['file_ext'] = $file_ext;
$filearray['file_size'] = $file_size;
$filearray['file_path'] = $targetFile;
$filearray['file_temp'] = $file_temp;
//$filearray['client_id'] = $client_id;
$json_array = json_encode($filearray);
echo $json_array;
}else{
echo "1";
}
i dont relly know what is going on here, like i said i am a newbie but i know something that $json_array, that array hold my data $filearray, that is data file uploaded. mission one complete
now my controller: upload.php
<?php
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
}
/*
* Display upload form
*/
function index()
{
$this->load->view('view');
}
/*
* Handles JSON returned from /js/uploadify/upload.php
*/
function uploadify()
{
//Decode JSON returned by /js/uploadify/upload.php
$file = $this->input->post('filearray');
$data['json'] = json_decode($file);
$this->load->view('uploadify',$data);
}
}
/* End of File /application/controllers/upload.php */
my plan is send the data in onComplete function
my view :view.php
<!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 charset="UTF-8">
<title>Uploadify and Codeigniter Tutorial</title>
<?php
$this->load->helper('html');
echo link_tag('http://uploadify_tutorial/uploadify/uploadify.css');
echo '<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>';
echo '<script src="http://localhost/uploadify_tutorial/uploadify/swfobject.js" type="text/javascript"></script>';
echo '<script src="http://localhost/uploadify_tutorial/uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>';
$uploadpath="";
$uploadpath=str_ireplace($_SERVER['DOCUMENT_ROOT'],"", realpath($_SERVER['SCRIPT_FILENAME']));
$uploadpath=str_ireplace("index.php","",$uploadpath);
?>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#upload").uploadify({
uploader: '<?php echo base_url();?>uploadify/uploadify.swf',
script: '<?php echo base_url();?>uploadify/uploadify.php',
cancelImg: '<?php echo base_url();?>uploadify/cancel.png',
folder: '/uploads',
scriptAccess: 'always',
multi: true,
'onError' : function (a, b, c, d) {
if (d.status == 404)
alert('Could not find upload script.');
else if (d.type === "HTTP")
alert('error '+d.type+": "+d.status);
else if (d.type ==="File Size")
alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
else
alert('error '+d.type+": "+d.text);
},
'onComplete' : function (event, queueID, fileObj, response, data) {
//Post response back to controller
$.post('<?php echo site_url('upload/uploadify');?>',{filearray: response},function(info){
$("#target").append(info); //Add response returned by controller
});
}
});
});
</script>
</head>
<body>
<h1>Uploadify Example</h1>
<?php echo form_open_multipart('upload/index');?>
<p>
<label for="Filedata">Choose a File</label><br/>
<?php echo form_upload(array('name' => 'Filedata', 'id' => 'upload'));?>
Upload File(s)
</p>
<?php echo form_close();?>
<div id="target">
</div>
</body>
</html>
my view : uploadify
<html>
<ul>
<li>Extension: <?php echo $json->{'file_ext'};?></li>
<li>File Size: <?php echo $json->{'file_size'};?></li>
<li>File Path: <?php echo $json->{'file_path'};?></li>
</ul>
</html>
and then parsing that json_array variable to my view, that is the plans, but in reality that code doesn work the data is undefined
an error Trying to get property of non-object i use this code here, I suppose the problem is with json
i just want to use the data file uploaded if anyone can solve that problem please share it or send me CI+uploadify program to my email, if anyone expert about CI and Uploadify plugin please make the tutorial step by step how to use it, step by step, i think it would be great help for newbie like me
thanks....
my email :saya.dean#gmail.com
I'm not really clear on where you are running into a problem. 'that variable' will be the files you uploaded, yes? Create an array of the filepaths as they get uploaded and when the upload is done cycle through each for email attachment.
Have you checked other answers on the site? Maybe take a look here. But CI's documentation clearly states that you can use:
$this->email->attach('/path/to/that_file.jpg');
multiple times.
Update:
You can either try using the onUploadSuccess function in uploadify to append each file name to something that you can use later...
'onUploadSuccess' : function(file, data, response) {
alert('The file name is ' + file.name);
...
OR from within uploadify.php. From there you can store what you need for attaching after.
In your case I'd stick with modifying the uploadify.php. You'll have to give it a shot and post some code if you are stuck, but there are plenty of places to get some ideas like here and here
I have a phpBB forum on my localhost for learning purposes..now I'm trying to do this using PHP :
When a link gets posted,a script checks if the exact link exists and if it does then the process of posting the message doesn't continue.
EDIT: This is what I have in includes/message_parser.php
function url_exists($url) {
$handle = #fopen($url, "r");
if ($handle === false){
return false;
fclose($handle);}
else{
return true;
fclose($handle);}}
And this is what I have in posting.php
$your_url = "http://www.somewhere.com/index.php";
$your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url);
if (url_exists($your_url))
{
echo 'yeah, its reachable';
}
else
{
echo 'what da hell..';
}
It works. I can see it echoing what da hell when I post a link that exists,but the problem is that the post gets posted. what I want now is,if the link exists,then don't allow the post to be posted.
2ND EDIT:
if($submit){
$URL = "http://www.fileserve.com/file/rP59FZ2";
preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $url);
if(url_exists($url)) {
echo "Link exists!";
}
That's what I did to prevent submitting the topic when the url exists. not working :\
Checking if link return status code 200 (dunno about 30x)
Using cURL:
function url_exists($url) {
$ch = #curl_init($url);
#curl_setopt($ch, CURLOPT_HEADER, TRUE);
#curl_setopt($ch, CURLOPT_NOBODY, TRUE);
#curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$status = array();
preg_match('/HTTP\/.* ([0-9]+) .*/', #curl_exec($ch) , $status);
return ($status[1] == 200);
}
// now call the function
$myUrl = "http://www.somewhere.com";
if(url_exists($myUrl)) {
echo "Link exists!";
} else {
echo "Link does not exist :(";
}
Without cURL:
function url_exists($url) {
$h = get_headers($url);
$status = array();
preg_match('/HTTP\/.* ([0-9]+) .*/', $h[0] , $status);
return ($status[1] == 200);
}
// now call the function
$myUrl = "http://www.somewhere.com";
if(url_exists($myUrl)) {
echo "Link exists!";
} else {
echo "Link does not exist :(";
}
You can play around with it :)
UPDATE
To the updated question.
I don't know exactly how phpBB works or where you're trying to catch it, but some suggestions to stop the posting might be to check for the link using javascript/jQuery and then disable the submit button alerting/printing a statement as to why the post wasn't posted.
I'm not that into regex and such, but you would check the post if it contains any link you where looking for, and then "block" the submit of the form.
Something along the lines of:
$('#myform').submit(function(event){
// disable the submit button so the user doesn't spam it
$('#myform input[type=submit]', this).attr('disabled', 'disabled');
// check with regex for the links
// if it's found return true else return false to variable preventSubmit
if(preventSubmit) {
// prevent the form from being submitted
event.preventDefault();
// notify the user
alert("You cannot post that link!");
return false;
}
});
as extra security, you could disable the submit by default, and only enable it once the javascript has loaded.
try:
$url = 'http://www.anyURL.com';
$hndl = #fopen($url,'r');
if($hndl !== false){
echo 'URL Exists';
}
else
{
echo "URL Doesn't exist";
}
First check to see whether the link format is valid:
function isValidURL($url) {
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
Then make sure the resource that the link refers to actually exists:
function checkLink() {
$handle = fopen("http://www.example.com/", "r");
if ($handle) { fclose($handle); return true; }
return false;
}
I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.